mswjs / data

Data modeling and relation library for testing JavaScript applications.

Home Page:https://npm.im/@mswjs/data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using wildcard/parameters in baseUrl in toHandlers method

timkolotov opened this issue · comments

I recently started using MSW for both jest and storybook tests.
In our project, we use relative paths for the API, so the resulting URL depends on the environment the call is made. E.g. if storybook is run on http://127.0.0.1:6006/ this host will be used in the API call. But it can also be run on http://localhost:6006/

So in MSW handlers, I used baseUrl with parameters such as http://:hostname/:lang/api/v1/ and it works perfectly. Now I wanted to reduce the amount of boilerplate and add mswjs/data with automatic generation of handles, but it seems to be not possible anymore as the URL constructor in createUrlBuilder fails to parse such a string as that is not a valid URL.

Is there any other way for manipulating the resulting paths in handlers, like just adding prefixes? Or the only way is to manually add all handlers?

Hey, @timkolotov. I think this should be fixed on the library's side. The createUrlBuilder function, as you've rightfully mentioned, should support path strings as well.

export function createUrlBuilder(baseUrl?: string) {
return (path: string) => {
const url = new URL(path, baseUrl || 'http://localhost')
return baseUrl ? url.toString() : url.pathname
}
}

From the look of it, I don't see any implications of supporting that. Would you be interested in opening a pull request with this feature?

Yeah, will do. Probably this weekend.

@kettanaito hey, I created a PR for this. It seems I can't request a review for it, so just FYI 🙂

Thanks, @timkolotov! Not sure what's with the review request permissions but I will look into it regardless.