Skip to content

Commit

Permalink
chore(fetch): add custom mutator test for fetch client
Browse files Browse the repository at this point in the history
  • Loading branch information
soartec-lab committed Jun 17, 2024
1 parent 82940ca commit 25d64c8
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
17 changes: 17 additions & 0 deletions tests/configs/fetch.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ export default defineConfig({
target: '../specifications/petstore.yaml',
},
},
mutator: {
output: {
target: '../generated/fetch/mutator/endpoints.ts',
schemas: '../generated/fetch/mutator/model',
mock: true,
client: 'fetch',
override: {
mutator: {
path: '../mutators/custom-fetch.ts',
name: 'customFetch',
},
},
},
input: {
target: '../specifications/petstore.yaml',
},
},
multiArguments: {
output: {
target: '../generated/fetch/multi-arguments/endpoints.ts',
Expand Down
57 changes: 57 additions & 0 deletions tests/mutators/custom-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// NOTE: Supports cases where `content-type` is other than `json`
const getBody = <T>(c: Response | Request): Promise<T> => {
const contentType = c.headers.get('content-type');

if (contentType && contentType.includes('application/json')) {
return c.json();
}

if (contentType && contentType.includes('application/pdf')) {
return c.blob() as Promise<T>;
}

return c.text() as Promise<T>;
};

// NOTE: Update just base url
const getUrl = (contextUrl: string): string => {
const url = new URL(contextUrl);
const pathname = url.pathname;
const search = url.search;
const baseUrl =
process.env.NODE_ENV === 'production'
? 'productionBaseUrl'
: 'http://localhost:3000';

const requestUrl = new URL(`${baseUrl}${pathname}${search}`);

return requestUrl.toString();
};

// NOTE: Add headers
const getHeaders = (headers?: HeadersInit): HeadersInit => {
return {
...headers,
Authorization: 'token',
'Content-Type': 'multipart/form-data',
};
};

export const customFetch = async <T>(
url: string,
options: RequestInit,
): Promise<T> => {
const requestUrl = getUrl(url);
const requestHeaders = getHeaders(options.headers);

const requestInit: RequestInit = {
...options,
headers: requestHeaders,
};

const request = new Request(requestUrl, requestInit);
const response = await fetch(request);
const data = await getBody<T>(response);

return data;
};

0 comments on commit 25d64c8

Please sign in to comment.