@openapi-qraft/react 1.13.1 → 1.14.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/cjs/lib/requestFn.cjs +15 -1
- package/dist/cjs/lib/requestFn.cjs.map +1 -1
- package/dist/esm/lib/requestFn.js +15 -1
- package/dist/esm/lib/requestFn.js.map +1 -1
- package/dist/types/lib/requestFn.d.ts +15 -0
- package/dist/types/lib/requestFn.d.ts.map +1 -1
- package/dist/types/lib/urlSerializer.test.d.ts +2 -0
- package/dist/types/lib/urlSerializer.test.d.ts.map +1 -0
- package/package.json +4 -4
- package/src/lib/requestFn.ts +15 -0
- package/src/lib/urlSerializer.test.ts +219 -0
package/CHANGELOG.md
CHANGED
|
@@ -56,7 +56,21 @@
|
|
|
56
56
|
}
|
|
57
57
|
return await getResponseBody(clonedResponse);
|
|
58
58
|
}
|
|
59
|
-
|
|
59
|
+
/**
|
|
60
|
+
* Serializes the given schema and request payload into a URL string.
|
|
61
|
+
*
|
|
62
|
+
* This function is implemented according to the URI Template standard
|
|
63
|
+
* defined in RFC 6570. It supports the expansion of path and query parameters,
|
|
64
|
+
* correctly handling empty arrays, `null`, and `undefined` values by ignoring
|
|
65
|
+
* them during the expansion process, as specified by the standard.
|
|
66
|
+
*
|
|
67
|
+
* For more information, refer to the official documentation:
|
|
68
|
+
* https://datatracker.ietf.org/doc/html/rfc6570
|
|
69
|
+
*
|
|
70
|
+
* @param schema - The operation schema containing the URL template and method.
|
|
71
|
+
* @param info - The request payload including baseUrl, path parameters, and query parameters.
|
|
72
|
+
* @returns The fully constructed URL string.
|
|
73
|
+
*/ function urlSerializer(schema, info) {
|
|
60
74
|
const path = schema.url.replace(/{(.*?)}/g, (substring, group)=>{
|
|
61
75
|
if (info.parameters?.path && Object.prototype.hasOwnProperty.call(info.parameters.path, group)) {
|
|
62
76
|
return encodeURI(String(info.parameters?.path[group]));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requestFn.cjs","sources":["../../../src/lib/requestFn.ts"],"sourcesContent":["/**\n * This function is used to make a request to a specified endpoint.\n *\n * @template T The expected return type of the request.\n *\n * @param schema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param [options] Optional. Additional options for the request. It includes custom urlSerializer, bodySerializer, and fetch function.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function requestFn<T>(\n schema: OperationSchema,\n requestInfo: RequestFnInfo,\n options?: RequestFnOptions\n): Promise<T> {\n return baseRequestFn(schema, requestInfo, {\n urlSerializer,\n bodySerializer,\n ...options,\n });\n}\n\n/**\n * This function is used to make a request to a specified endpoint.\n * It's needed to create a custom `requestFn` with a custom `urlSerializer`\n * and `bodySerializer`, with the tree-shaking of the default `requestFn`\n * and its serializers.\n *\n * @template T The expected return type of the request.\n *\n * @param requestSchema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param options The options for the request. It includes urlSerializer, bodySerializer, and fetch function. The 'urlSerializer' and 'bodySerializer' are required.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function baseRequestFn<T>(\n requestSchema: OperationSchema,\n requestInfo: RequestFnInfo,\n options: WithRequired<RequestFnOptions, 'urlSerializer' | 'bodySerializer'>\n): Promise<T> {\n const { parameters, headers, body, ...requestInfoRest } = requestInfo;\n\n const requestBody = options.bodySerializer(requestSchema, requestInfo);\n\n const baseFetch = options.fetch ?? fetch;\n\n const response = await baseFetch(\n options.urlSerializer(requestSchema, requestInfo),\n {\n method: requestSchema.method.toUpperCase(),\n body: requestBody,\n headers: mergeHeaders(\n {\n Accept: 'application/json',\n 'Content-Type': requestSchema.mediaType ?? getBodyContentType(body),\n },\n headers,\n parameters?.header,\n requestBody instanceof FormData\n ? // remove `Content-Type` if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n { 'Content-Type': null }\n : undefined\n ),\n ...requestInfoRest,\n }\n );\n\n // clone response to allow multiple reads\n const clonedResponse = response.clone();\n\n if (!response.ok) {\n throw await getResponseBody(clonedResponse);\n }\n\n return (await getResponseBody(clonedResponse)) as T;\n}\n\nexport function urlSerializer(\n schema: OperationSchema,\n info: RequestFnPayload\n): string {\n const path = schema.url.replace(\n /{(.*?)}/g,\n (substring: string, group: string) => {\n if (\n info.parameters?.path &&\n Object.prototype.hasOwnProperty.call(info.parameters.path, group)\n ) {\n return encodeURI(String(info.parameters?.path[group]));\n }\n return substring;\n }\n );\n\n const baseUrl = info.baseUrl ?? '';\n\n if (info.parameters?.query) {\n return `${baseUrl}${path}${getQueryString(info.parameters.query)}`;\n }\n\n return `${baseUrl}${path}`;\n}\n\nfunction getQueryString(params: Record<string, any>): string {\n const qs: string[] = [];\n\n const append = (key: string, value: any) => {\n qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n };\n\n const process = (key: string, value: any) => {\n if (typeof value === 'undefined' || value === null) return;\n\n if (Array.isArray(value)) {\n value.forEach((v) => {\n process(key, v);\n });\n } else if (typeof value === 'object') {\n Object.entries(value).forEach(([k, v]) => {\n process(`${key}[${k}]`, v);\n });\n } else {\n append(key, value);\n }\n };\n\n Object.entries(params).forEach(([key, value]) => {\n process(key, value);\n });\n\n if (qs.length > 0) {\n return `?${qs.join('&')}`;\n }\n\n return '';\n}\n\nexport function mergeHeaders(...allHeaders: (HeadersOptions | undefined)[]) {\n const headers = new Headers();\n\n for (const headerSet of allHeaders) {\n if (!headerSet || typeof headerSet !== 'object') {\n continue;\n }\n\n const headersIterator =\n headerSet instanceof Headers\n ? headerSet.entries()\n : Object.entries(headerSet);\n\n for (const [headerKey, headerValue] of headersIterator) {\n if (headerValue === null) {\n headers.delete(headerKey);\n } else if (headerValue !== undefined) {\n headers.set(headerKey, headerValue);\n }\n }\n }\n\n return headers;\n}\n\nexport function bodySerializer(\n schema: OperationSchema,\n info: RequestFnPayload\n) {\n if (info.body === undefined) return;\n\n if (\n schema.method === 'get' ||\n schema.method === 'head' ||\n schema.method === 'options'\n )\n return;\n\n if (schema.mediaType?.includes('/form-data'))\n return getRequestBodyFormData(info);\n\n if (\n !schema.mediaType?.includes('/json') &&\n (typeof info.body === 'string' ||\n info.body instanceof Blob ||\n info.body instanceof FormData)\n ) {\n return info.body;\n }\n\n return JSON.stringify(info.body);\n}\n\nfunction getRequestBodyFormData({\n body,\n}: Pick<RequestFnPayload, 'body'>): FormData | undefined {\n if (body instanceof FormData) return body;\n if (body === null) return;\n\n if (body instanceof Blob) throw new Error('Blob not supported in form-data');\n if (body instanceof ArrayBuffer)\n throw new Error('ArrayBuffer not supported in form-data');\n if (body instanceof URLSearchParams)\n throw new Error('URLSearchParams not supported in form-data');\n if (body instanceof ReadableStream)\n throw new Error('ReadableStream not supported in form-data');\n if (typeof body === 'string')\n throw new Error('String not supported in form-data');\n if (typeof body !== 'object')\n throw new Error(`Unsupported body type ${typeof body} in form-data.`);\n\n const formData = new FormData();\n\n const process = (key: string, value: any) => {\n if (typeof value === 'string' || value instanceof Blob) {\n formData.append(key, value);\n } else {\n formData.append(key, JSON.stringify(value));\n }\n };\n\n Object.entries(body)\n .filter(([_, value]) => typeof value !== 'undefined' && value !== null)\n .forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => process(key, v));\n } else {\n process(key, value);\n }\n });\n\n return formData;\n}\n\nfunction getBodyContentType(body: RequestFnPayload['body']) {\n if (!body) return;\n if (body instanceof Blob) return body.type || 'application/octet-stream';\n if (typeof body === 'string') return 'text/plain';\n if (!(body instanceof FormData)) return 'application/json';\n}\n\nasync function getResponseBody<T>(response: Response): Promise<T | undefined> {\n if (response.status === 204 || response.headers.get('Content-Length') === '0')\n return undefined;\n\n const contentType = response.headers.get('Content-Type')?.toLowerCase();\n const isJSON =\n contentType?.includes('/json') || contentType?.includes('+json');\n\n if (isJSON) {\n // attempt to parse JSON for successful responses, otherwise fail\n if (response.ok) return response.json();\n\n const errorFallbackResponse = response.clone(); // clone to allow multiple reads\n\n return response.json().catch(() => {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Failed to parse response body as JSON. Falling back to .text()'\n );\n }\n // falling back to .text() when necessary for error messages\n return errorFallbackResponse.text();\n });\n }\n\n return response.text() as Promise<T>;\n}\n\n// To have definitely typed headers without a conversion to stings\nexport type HeadersOptions =\n | HeadersInit\n | Record<string, string | number | boolean | null | undefined>;\n\nexport interface OperationSchema {\n /**\n * Operation path\n * @example /user/{id}\n */\n readonly url: string; //todo::rename to `path`\n\n /**\n * Operation method\n */\n readonly method:\n | 'get'\n | 'put'\n | 'post'\n | 'patch'\n | 'delete'\n | 'options'\n | 'head'\n | 'trace';\n\n /**\n * Media type of the request body\n * @example application/json\n */\n readonly mediaType?: string;\n\n readonly security?: string[];\n}\n\nexport interface RequestFnPayload {\n /**\n * Base URL to use for the request\n * @example 'https://api.example.com'\n */\n baseUrl: string | undefined;\n\n /**\n * OpenAPI parameters\n * @example\n * ```ts\n * { path: {id: 1}, query: {search: 'hello'} }\n * ```\n */\n readonly parameters?: {\n readonly path?: Record<string, any>;\n readonly header?: Record<string, any>;\n readonly query?: Record<string, any>;\n };\n\n /**\n * Request body\n * @example { name: 'John' }\n */\n readonly body?: BodyInit | Record<string, unknown> | null;\n\n /**\n * Tanstack Query Meta\n */\n meta?: Record<string, unknown>;\n\n /** An AbortSignal to set request's signal. */\n signal?: AbortSignal | null;\n}\n\nexport interface RequestFnInfo\n extends RequestFnPayload,\n Omit<RequestInit, 'headers' | 'method' | 'body' | 'signal'> {\n /**\n * Request headers\n * @example { 'X-Auth': '123' }\n */\n readonly headers?: HeadersOptions;\n}\n\nexport interface RequestFnOptions {\n urlSerializer?: typeof urlSerializer;\n bodySerializer?: typeof bodySerializer;\n fetch?: typeof fetch;\n}\n\nexport type RequestFn<T> = typeof requestFn<T>;\n\ntype WithRequired<T, K extends keyof T> = T & {\n [_ in K]: {};\n};\n"],"names":["requestFn","schema","requestInfo","options","baseRequestFn","urlSerializer","bodySerializer","requestSchema","parameters","headers","body","requestInfoRest","requestBody","baseFetch","fetch","response","method","toUpperCase","mergeHeaders","Accept","mediaType","getBodyContentType","header","FormData","undefined","clonedResponse","clone","ok","getResponseBody","info","path","url","replace","substring","group","Object","prototype","hasOwnProperty","call","encodeURI","String","baseUrl","query","getQueryString","params","qs","append","key","value","push","encodeURIComponent","process","Array","isArray","forEach","v","entries","k","length","join","allHeaders","Headers","headerSet","headersIterator","headerKey","headerValue","delete","set","includes","getRequestBodyFormData","Blob","JSON","stringify","Error","ArrayBuffer","URLSearchParams","ReadableStream","formData","filter","_","type","status","get","contentType","toLowerCase","isJSON","json","errorFallbackResponse","catch","env","NODE_ENV","console","warn","text"],"mappings":";;AAAA;;;;;;;;;;;;AAYC,IACM,eAAeA,SAAAA,CACpBC,MAAuB,EACvBC,WAA0B,EAC1BC,OAA0B,EAAA;IAE1B,OAAOC,aAAAA,CAAcH,QAAQC,WAAa,EAAA;AACxCG,QAAAA,aAAAA;AACAC,QAAAA,cAAAA;AACA,QAAA,GAAGH,OAAO;AACZ,KAAA,CAAA,CAAA;AACF,CAAA;AAEA;;;;;;;;;;;;;;;AAeC,IACM,eAAeC,aAAAA,CACpBG,aAA8B,EAC9BL,WAA0B,EAC1BC,OAA2E,EAAA;IAE3E,MAAM,EAAEK,UAAU,EAAEC,OAAO,EAAEC,IAAI,EAAE,GAAGC,eAAAA,EAAiB,GAAGT,WAAAA,CAAAA;AAE1D,IAAA,MAAMU,WAAcT,GAAAA,OAAAA,CAAQG,cAAc,CAACC,aAAeL,EAAAA,WAAAA,CAAAA,CAAAA;IAE1D,MAAMW,SAAAA,GAAYV,OAAQW,CAAAA,KAAK,IAAIA,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AAe,EAAA;AAC1CC,gBAAAA,OAAAA,CAAQC,IAAI,CACV,gEAAA,CAAA,CAAA;AAEJ,aAAA;;AAEA,YAAA,OAAOL,sBAAsBM,IAAI,EAAA,CAAA;AACnC,SAAA,CAAA,CAAA;AACF,KAAA;AAEA,IAAA,OAAO9E,SAAS8E,IAAI,EAAA,CAAA;AACtB;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"requestFn.cjs","sources":["../../../src/lib/requestFn.ts"],"sourcesContent":["/**\n * This function is used to make a request to a specified endpoint.\n *\n * @template T The expected return type of the request.\n *\n * @param schema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param [options] Optional. Additional options for the request. It includes custom urlSerializer, bodySerializer, and fetch function.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function requestFn<T>(\n schema: OperationSchema,\n requestInfo: RequestFnInfo,\n options?: RequestFnOptions\n): Promise<T> {\n return baseRequestFn(schema, requestInfo, {\n urlSerializer,\n bodySerializer,\n ...options,\n });\n}\n\n/**\n * This function is used to make a request to a specified endpoint.\n * It's needed to create a custom `requestFn` with a custom `urlSerializer`\n * and `bodySerializer`, with the tree-shaking of the default `requestFn`\n * and its serializers.\n *\n * @template T The expected return type of the request.\n *\n * @param requestSchema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param options The options for the request. It includes urlSerializer, bodySerializer, and fetch function. The 'urlSerializer' and 'bodySerializer' are required.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function baseRequestFn<T>(\n requestSchema: OperationSchema,\n requestInfo: RequestFnInfo,\n options: WithRequired<RequestFnOptions, 'urlSerializer' | 'bodySerializer'>\n): Promise<T> {\n const { parameters, headers, body, ...requestInfoRest } = requestInfo;\n\n const requestBody = options.bodySerializer(requestSchema, requestInfo);\n\n const baseFetch = options.fetch ?? fetch;\n\n const response = await baseFetch(\n options.urlSerializer(requestSchema, requestInfo),\n {\n method: requestSchema.method.toUpperCase(),\n body: requestBody,\n headers: mergeHeaders(\n {\n Accept: 'application/json',\n 'Content-Type': requestSchema.mediaType ?? getBodyContentType(body),\n },\n headers,\n parameters?.header,\n requestBody instanceof FormData\n ? // remove `Content-Type` if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n { 'Content-Type': null }\n : undefined\n ),\n ...requestInfoRest,\n }\n );\n\n // clone response to allow multiple reads\n const clonedResponse = response.clone();\n\n if (!response.ok) {\n throw await getResponseBody(clonedResponse);\n }\n\n return (await getResponseBody(clonedResponse)) as T;\n}\n\n/**\n * Serializes the given schema and request payload into a URL string.\n *\n * This function is implemented according to the URI Template standard\n * defined in RFC 6570. It supports the expansion of path and query parameters,\n * correctly handling empty arrays, `null`, and `undefined` values by ignoring\n * them during the expansion process, as specified by the standard.\n *\n * For more information, refer to the official documentation:\n * https://datatracker.ietf.org/doc/html/rfc6570\n *\n * @param schema - The operation schema containing the URL template and method.\n * @param info - The request payload including baseUrl, path parameters, and query parameters.\n * @returns The fully constructed URL string.\n */\nexport function urlSerializer(\n schema: OperationSchema,\n info: RequestFnPayload\n): string {\n const path = schema.url.replace(\n /{(.*?)}/g,\n (substring: string, group: string) => {\n if (\n info.parameters?.path &&\n Object.prototype.hasOwnProperty.call(info.parameters.path, group)\n ) {\n return encodeURI(String(info.parameters?.path[group]));\n }\n return substring;\n }\n );\n\n const baseUrl = info.baseUrl ?? '';\n\n if (info.parameters?.query) {\n return `${baseUrl}${path}${getQueryString(info.parameters.query)}`;\n }\n\n return `${baseUrl}${path}`;\n}\n\nfunction getQueryString(params: Record<string, any>): string {\n const qs: string[] = [];\n\n const append = (key: string, value: any) => {\n qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n };\n\n const process = (key: string, value: any) => {\n if (typeof value === 'undefined' || value === null) return;\n\n if (Array.isArray(value)) {\n value.forEach((v) => {\n process(key, v);\n });\n } else if (typeof value === 'object') {\n Object.entries(value).forEach(([k, v]) => {\n process(`${key}[${k}]`, v);\n });\n } else {\n append(key, value);\n }\n };\n\n Object.entries(params).forEach(([key, value]) => {\n process(key, value);\n });\n\n if (qs.length > 0) {\n return `?${qs.join('&')}`;\n }\n\n return '';\n}\n\nexport function mergeHeaders(...allHeaders: (HeadersOptions | undefined)[]) {\n const headers = new Headers();\n\n for (const headerSet of allHeaders) {\n if (!headerSet || typeof headerSet !== 'object') {\n continue;\n }\n\n const headersIterator =\n headerSet instanceof Headers\n ? headerSet.entries()\n : Object.entries(headerSet);\n\n for (const [headerKey, headerValue] of headersIterator) {\n if (headerValue === null) {\n headers.delete(headerKey);\n } else if (headerValue !== undefined) {\n headers.set(headerKey, headerValue);\n }\n }\n }\n\n return headers;\n}\n\nexport function bodySerializer(\n schema: OperationSchema,\n info: RequestFnPayload\n) {\n if (info.body === undefined) return;\n\n if (\n schema.method === 'get' ||\n schema.method === 'head' ||\n schema.method === 'options'\n )\n return;\n\n if (schema.mediaType?.includes('/form-data'))\n return getRequestBodyFormData(info);\n\n if (\n !schema.mediaType?.includes('/json') &&\n (typeof info.body === 'string' ||\n info.body instanceof Blob ||\n info.body instanceof FormData)\n ) {\n return info.body;\n }\n\n return JSON.stringify(info.body);\n}\n\nfunction getRequestBodyFormData({\n body,\n}: Pick<RequestFnPayload, 'body'>): FormData | undefined {\n if (body instanceof FormData) return body;\n if (body === null) return;\n\n if (body instanceof Blob) throw new Error('Blob not supported in form-data');\n if (body instanceof ArrayBuffer)\n throw new Error('ArrayBuffer not supported in form-data');\n if (body instanceof URLSearchParams)\n throw new Error('URLSearchParams not supported in form-data');\n if (body instanceof ReadableStream)\n throw new Error('ReadableStream not supported in form-data');\n if (typeof body === 'string')\n throw new Error('String not supported in form-data');\n if (typeof body !== 'object')\n throw new Error(`Unsupported body type ${typeof body} in form-data.`);\n\n const formData = new FormData();\n\n const process = (key: string, value: any) => {\n if (typeof value === 'string' || value instanceof Blob) {\n formData.append(key, value);\n } else {\n formData.append(key, JSON.stringify(value));\n }\n };\n\n Object.entries(body)\n .filter(([_, value]) => typeof value !== 'undefined' && value !== null)\n .forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => process(key, v));\n } else {\n process(key, value);\n }\n });\n\n return formData;\n}\n\nfunction getBodyContentType(body: RequestFnPayload['body']) {\n if (!body) return;\n if (body instanceof Blob) return body.type || 'application/octet-stream';\n if (typeof body === 'string') return 'text/plain';\n if (!(body instanceof FormData)) return 'application/json';\n}\n\nasync function getResponseBody<T>(response: Response): Promise<T | undefined> {\n if (response.status === 204 || response.headers.get('Content-Length') === '0')\n return undefined;\n\n const contentType = response.headers.get('Content-Type')?.toLowerCase();\n const isJSON =\n contentType?.includes('/json') || contentType?.includes('+json');\n\n if (isJSON) {\n // attempt to parse JSON for successful responses, otherwise fail\n if (response.ok) return response.json();\n\n const errorFallbackResponse = response.clone(); // clone to allow multiple reads\n\n return response.json().catch(() => {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Failed to parse response body as JSON. Falling back to .text()'\n );\n }\n // falling back to .text() when necessary for error messages\n return errorFallbackResponse.text();\n });\n }\n\n return response.text() as Promise<T>;\n}\n\n// To have definitely typed headers without a conversion to stings\nexport type HeadersOptions =\n | HeadersInit\n | Record<string, string | number | boolean | null | undefined>;\n\nexport interface OperationSchema {\n /**\n * Operation path\n * @example /user/{id}\n */\n readonly url: string; //todo::rename to `path`\n\n /**\n * Operation method\n */\n readonly method:\n | 'get'\n | 'put'\n | 'post'\n | 'patch'\n | 'delete'\n | 'options'\n | 'head'\n | 'trace';\n\n /**\n * Media type of the request body\n * @example application/json\n */\n readonly mediaType?: string;\n\n readonly security?: string[];\n}\n\nexport interface RequestFnPayload {\n /**\n * Base URL to use for the request\n * @example 'https://api.example.com'\n */\n baseUrl: string | undefined;\n\n /**\n * OpenAPI parameters\n * @example\n * ```ts\n * { path: {id: 1}, query: {search: 'hello'} }\n * ```\n */\n readonly parameters?: {\n readonly path?: Record<string, any>;\n readonly header?: Record<string, any>;\n readonly query?: Record<string, any>;\n };\n\n /**\n * Request body\n * @example { name: 'John' }\n */\n readonly body?: BodyInit | Record<string, unknown> | null;\n\n /**\n * Tanstack Query Meta\n */\n meta?: Record<string, unknown>;\n\n /** An AbortSignal to set request's signal. */\n signal?: AbortSignal | null;\n}\n\nexport interface RequestFnInfo\n extends RequestFnPayload,\n Omit<RequestInit, 'headers' | 'method' | 'body' | 'signal'> {\n /**\n * Request headers\n * @example { 'X-Auth': '123' }\n */\n readonly headers?: HeadersOptions;\n}\n\nexport interface RequestFnOptions {\n urlSerializer?: typeof urlSerializer;\n bodySerializer?: typeof bodySerializer;\n fetch?: typeof fetch;\n}\n\nexport type RequestFn<T> = typeof requestFn<T>;\n\ntype WithRequired<T, K extends keyof T> = T & {\n [_ in K]: {};\n};\n"],"names":["requestFn","schema","requestInfo","options","baseRequestFn","urlSerializer","bodySerializer","requestSchema","parameters","headers","body","requestInfoRest","requestBody","baseFetch","fetch","response","method","toUpperCase","mergeHeaders","Accept","mediaType","getBodyContentType","header","FormData","undefined","clonedResponse","clone","ok","getResponseBody","info","path","url","replace","substring","group","Object","prototype","hasOwnProperty","call","encodeURI","String","baseUrl","query","getQueryString","params","qs","append","key","value","push","encodeURIComponent","process","Array","isArray","forEach","v","entries","k","length","join","allHeaders","Headers","headerSet","headersIterator","headerKey","headerValue","delete","set","includes","getRequestBodyFormData","Blob","JSON","stringify","Error","ArrayBuffer","URLSearchParams","ReadableStream","formData","filter","_","type","status","get","contentType","toLowerCase","isJSON","json","errorFallbackResponse","catch","env","NODE_ENV","console","warn","text"],"mappings":";;AAAA;;;;;;;;;;;;AAYC,IACM,eAAeA,SAAAA,CACpBC,MAAuB,EACvBC,WAA0B,EAC1BC,OAA0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AA,MAAM2D,cAAcpE,QAASN,CAAAA,OAAO,CAACyE,GAAG,CAAC,cAAiBE,CAAAA,EAAAA,WAAAA,EAAAA,CAAAA;AAC1D,IAAA,MAAMC,MACJF,GAAAA,WAAAA,EAAaf,QAAS,CAAA,OAAA,CAAA,IAAYe,aAAaf,QAAS,CAAA,OAAA,CAAA,CAAA;AAE1D,IAAA,IAAIiB,MAAQ,EAAA;;AAEV,QAAA,IAAItE,QAASY,CAAAA,EAAE,EAAE,OAAOZ,SAASuE,IAAI,EAAA,CAAA;AAErC,QAAA,MAAMC,qBAAwBxE,GAAAA,QAAAA,CAASW,KAAK,EAAA,CAAA;AAE5C,QAAA,OAAOX,QAASuE,CAAAA,IAAI,EAAGE,CAAAA,KAAK,CAAC,IAAA;AAC3B,YAAA,IAAIrC,OAAQsC,CAAAA,GAAG,CAACC,QAAQ,KAAK,aAAe,EAAA;AAC1CC,gBAAAA,OAAAA,CAAQC,IAAI,CACV,gEAAA,CAAA,CAAA;AAEJ,aAAA;;AAEA,YAAA,OAAOL,sBAAsBM,IAAI,EAAA,CAAA;AACnC,SAAA,CAAA,CAAA;AACF,KAAA;AAEA,IAAA,OAAO9E,SAAS8E,IAAI,EAAA,CAAA;AACtB;;;;;;;;"}
|
|
@@ -54,7 +54,21 @@
|
|
|
54
54
|
}
|
|
55
55
|
return await getResponseBody(clonedResponse);
|
|
56
56
|
}
|
|
57
|
-
|
|
57
|
+
/**
|
|
58
|
+
* Serializes the given schema and request payload into a URL string.
|
|
59
|
+
*
|
|
60
|
+
* This function is implemented according to the URI Template standard
|
|
61
|
+
* defined in RFC 6570. It supports the expansion of path and query parameters,
|
|
62
|
+
* correctly handling empty arrays, `null`, and `undefined` values by ignoring
|
|
63
|
+
* them during the expansion process, as specified by the standard.
|
|
64
|
+
*
|
|
65
|
+
* For more information, refer to the official documentation:
|
|
66
|
+
* https://datatracker.ietf.org/doc/html/rfc6570
|
|
67
|
+
*
|
|
68
|
+
* @param schema - The operation schema containing the URL template and method.
|
|
69
|
+
* @param info - The request payload including baseUrl, path parameters, and query parameters.
|
|
70
|
+
* @returns The fully constructed URL string.
|
|
71
|
+
*/ function urlSerializer(schema, info) {
|
|
58
72
|
const path = schema.url.replace(/{(.*?)}/g, (substring, group)=>{
|
|
59
73
|
if (info.parameters?.path && Object.prototype.hasOwnProperty.call(info.parameters.path, group)) {
|
|
60
74
|
return encodeURI(String(info.parameters?.path[group]));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requestFn.js","sources":["../../../src/lib/requestFn.ts"],"sourcesContent":["/**\n * This function is used to make a request to a specified endpoint.\n *\n * @template T The expected return type of the request.\n *\n * @param schema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param [options] Optional. Additional options for the request. It includes custom urlSerializer, bodySerializer, and fetch function.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function requestFn<T>(\n schema: OperationSchema,\n requestInfo: RequestFnInfo,\n options?: RequestFnOptions\n): Promise<T> {\n return baseRequestFn(schema, requestInfo, {\n urlSerializer,\n bodySerializer,\n ...options,\n });\n}\n\n/**\n * This function is used to make a request to a specified endpoint.\n * It's needed to create a custom `requestFn` with a custom `urlSerializer`\n * and `bodySerializer`, with the tree-shaking of the default `requestFn`\n * and its serializers.\n *\n * @template T The expected return type of the request.\n *\n * @param requestSchema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param options The options for the request. It includes urlSerializer, bodySerializer, and fetch function. The 'urlSerializer' and 'bodySerializer' are required.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function baseRequestFn<T>(\n requestSchema: OperationSchema,\n requestInfo: RequestFnInfo,\n options: WithRequired<RequestFnOptions, 'urlSerializer' | 'bodySerializer'>\n): Promise<T> {\n const { parameters, headers, body, ...requestInfoRest } = requestInfo;\n\n const requestBody = options.bodySerializer(requestSchema, requestInfo);\n\n const baseFetch = options.fetch ?? fetch;\n\n const response = await baseFetch(\n options.urlSerializer(requestSchema, requestInfo),\n {\n method: requestSchema.method.toUpperCase(),\n body: requestBody,\n headers: mergeHeaders(\n {\n Accept: 'application/json',\n 'Content-Type': requestSchema.mediaType ?? getBodyContentType(body),\n },\n headers,\n parameters?.header,\n requestBody instanceof FormData\n ? // remove `Content-Type` if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n { 'Content-Type': null }\n : undefined\n ),\n ...requestInfoRest,\n }\n );\n\n // clone response to allow multiple reads\n const clonedResponse = response.clone();\n\n if (!response.ok) {\n throw await getResponseBody(clonedResponse);\n }\n\n return (await getResponseBody(clonedResponse)) as T;\n}\n\nexport function urlSerializer(\n schema: OperationSchema,\n info: RequestFnPayload\n): string {\n const path = schema.url.replace(\n /{(.*?)}/g,\n (substring: string, group: string) => {\n if (\n info.parameters?.path &&\n Object.prototype.hasOwnProperty.call(info.parameters.path, group)\n ) {\n return encodeURI(String(info.parameters?.path[group]));\n }\n return substring;\n }\n );\n\n const baseUrl = info.baseUrl ?? '';\n\n if (info.parameters?.query) {\n return `${baseUrl}${path}${getQueryString(info.parameters.query)}`;\n }\n\n return `${baseUrl}${path}`;\n}\n\nfunction getQueryString(params: Record<string, any>): string {\n const qs: string[] = [];\n\n const append = (key: string, value: any) => {\n qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n };\n\n const process = (key: string, value: any) => {\n if (typeof value === 'undefined' || value === null) return;\n\n if (Array.isArray(value)) {\n value.forEach((v) => {\n process(key, v);\n });\n } else if (typeof value === 'object') {\n Object.entries(value).forEach(([k, v]) => {\n process(`${key}[${k}]`, v);\n });\n } else {\n append(key, value);\n }\n };\n\n Object.entries(params).forEach(([key, value]) => {\n process(key, value);\n });\n\n if (qs.length > 0) {\n return `?${qs.join('&')}`;\n }\n\n return '';\n}\n\nexport function mergeHeaders(...allHeaders: (HeadersOptions | undefined)[]) {\n const headers = new Headers();\n\n for (const headerSet of allHeaders) {\n if (!headerSet || typeof headerSet !== 'object') {\n continue;\n }\n\n const headersIterator =\n headerSet instanceof Headers\n ? headerSet.entries()\n : Object.entries(headerSet);\n\n for (const [headerKey, headerValue] of headersIterator) {\n if (headerValue === null) {\n headers.delete(headerKey);\n } else if (headerValue !== undefined) {\n headers.set(headerKey, headerValue);\n }\n }\n }\n\n return headers;\n}\n\nexport function bodySerializer(\n schema: OperationSchema,\n info: RequestFnPayload\n) {\n if (info.body === undefined) return;\n\n if (\n schema.method === 'get' ||\n schema.method === 'head' ||\n schema.method === 'options'\n )\n return;\n\n if (schema.mediaType?.includes('/form-data'))\n return getRequestBodyFormData(info);\n\n if (\n !schema.mediaType?.includes('/json') &&\n (typeof info.body === 'string' ||\n info.body instanceof Blob ||\n info.body instanceof FormData)\n ) {\n return info.body;\n }\n\n return JSON.stringify(info.body);\n}\n\nfunction getRequestBodyFormData({\n body,\n}: Pick<RequestFnPayload, 'body'>): FormData | undefined {\n if (body instanceof FormData) return body;\n if (body === null) return;\n\n if (body instanceof Blob) throw new Error('Blob not supported in form-data');\n if (body instanceof ArrayBuffer)\n throw new Error('ArrayBuffer not supported in form-data');\n if (body instanceof URLSearchParams)\n throw new Error('URLSearchParams not supported in form-data');\n if (body instanceof ReadableStream)\n throw new Error('ReadableStream not supported in form-data');\n if (typeof body === 'string')\n throw new Error('String not supported in form-data');\n if (typeof body !== 'object')\n throw new Error(`Unsupported body type ${typeof body} in form-data.`);\n\n const formData = new FormData();\n\n const process = (key: string, value: any) => {\n if (typeof value === 'string' || value instanceof Blob) {\n formData.append(key, value);\n } else {\n formData.append(key, JSON.stringify(value));\n }\n };\n\n Object.entries(body)\n .filter(([_, value]) => typeof value !== 'undefined' && value !== null)\n .forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => process(key, v));\n } else {\n process(key, value);\n }\n });\n\n return formData;\n}\n\nfunction getBodyContentType(body: RequestFnPayload['body']) {\n if (!body) return;\n if (body instanceof Blob) return body.type || 'application/octet-stream';\n if (typeof body === 'string') return 'text/plain';\n if (!(body instanceof FormData)) return 'application/json';\n}\n\nasync function getResponseBody<T>(response: Response): Promise<T | undefined> {\n if (response.status === 204 || response.headers.get('Content-Length') === '0')\n return undefined;\n\n const contentType = response.headers.get('Content-Type')?.toLowerCase();\n const isJSON =\n contentType?.includes('/json') || contentType?.includes('+json');\n\n if (isJSON) {\n // attempt to parse JSON for successful responses, otherwise fail\n if (response.ok) return response.json();\n\n const errorFallbackResponse = response.clone(); // clone to allow multiple reads\n\n return response.json().catch(() => {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Failed to parse response body as JSON. Falling back to .text()'\n );\n }\n // falling back to .text() when necessary for error messages\n return errorFallbackResponse.text();\n });\n }\n\n return response.text() as Promise<T>;\n}\n\n// To have definitely typed headers without a conversion to stings\nexport type HeadersOptions =\n | HeadersInit\n | Record<string, string | number | boolean | null | undefined>;\n\nexport interface OperationSchema {\n /**\n * Operation path\n * @example /user/{id}\n */\n readonly url: string; //todo::rename to `path`\n\n /**\n * Operation method\n */\n readonly method:\n | 'get'\n | 'put'\n | 'post'\n | 'patch'\n | 'delete'\n | 'options'\n | 'head'\n | 'trace';\n\n /**\n * Media type of the request body\n * @example application/json\n */\n readonly mediaType?: string;\n\n readonly security?: string[];\n}\n\nexport interface RequestFnPayload {\n /**\n * Base URL to use for the request\n * @example 'https://api.example.com'\n */\n baseUrl: string | undefined;\n\n /**\n * OpenAPI parameters\n * @example\n * ```ts\n * { path: {id: 1}, query: {search: 'hello'} }\n * ```\n */\n readonly parameters?: {\n readonly path?: Record<string, any>;\n readonly header?: Record<string, any>;\n readonly query?: Record<string, any>;\n };\n\n /**\n * Request body\n * @example { name: 'John' }\n */\n readonly body?: BodyInit | Record<string, unknown> | null;\n\n /**\n * Tanstack Query Meta\n */\n meta?: Record<string, unknown>;\n\n /** An AbortSignal to set request's signal. */\n signal?: AbortSignal | null;\n}\n\nexport interface RequestFnInfo\n extends RequestFnPayload,\n Omit<RequestInit, 'headers' | 'method' | 'body' | 'signal'> {\n /**\n * Request headers\n * @example { 'X-Auth': '123' }\n */\n readonly headers?: HeadersOptions;\n}\n\nexport interface RequestFnOptions {\n urlSerializer?: typeof urlSerializer;\n bodySerializer?: typeof bodySerializer;\n fetch?: typeof fetch;\n}\n\nexport type RequestFn<T> = typeof requestFn<T>;\n\ntype WithRequired<T, K extends keyof T> = T & {\n [_ in K]: {};\n};\n"],"names":["requestFn","schema","requestInfo","options","baseRequestFn","urlSerializer","bodySerializer","requestSchema","parameters","headers","body","requestInfoRest","requestBody","baseFetch","fetch","response","method","toUpperCase","mergeHeaders","Accept","mediaType","getBodyContentType","header","FormData","undefined","clonedResponse","clone","ok","getResponseBody","info","path","url","replace","substring","group","Object","prototype","hasOwnProperty","call","encodeURI","String","baseUrl","query","getQueryString","params","qs","append","key","value","push","encodeURIComponent","process","Array","isArray","forEach","v","entries","k","length","join","allHeaders","Headers","headerSet","headersIterator","headerKey","headerValue","delete","set","includes","getRequestBodyFormData","Blob","JSON","stringify","Error","ArrayBuffer","URLSearchParams","ReadableStream","formData","filter","_","type","status","get","contentType","toLowerCase","isJSON","json","errorFallbackResponse","catch","env","NODE_ENV","console","warn","text"],"mappings":"AAAA;;;;;;;;;;;;AAYC,IACM,eAAeA,SAAAA,CACpBC,MAAuB,EACvBC,WAA0B,EAC1BC,OAA0B,EAAA;IAE1B,OAAOC,aAAAA,CAAcH,QAAQC,WAAa,EAAA;AACxCG,QAAAA,aAAAA;AACAC,QAAAA,cAAAA;AACA,QAAA,GAAGH,OAAO;AACZ,KAAA,CAAA,CAAA;AACF,CAAA;AAEA;;;;;;;;;;;;;;;AAeC,IACM,eAAeC,aAAAA,CACpBG,aAA8B,EAC9BL,WAA0B,EAC1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,IAAItE,QAASY,CAAAA,EAAE,EAAE,OAAOZ,SAASuE,IAAI,EAAA,CAAA;AAErC,QAAA,MAAMC,qBAAwBxE,GAAAA,QAAAA,CAASW,KAAK,EAAA,CAAA;AAE5C,QAAA,OAAOX,QAASuE,CAAAA,IAAI,EAAGE,CAAAA,KAAK,CAAC,IAAA;AAC3B,YAAA,IAAIrC,OAAQsC,CAAAA,GAAG,CAACC,QAAQ,KAAK,aAAe,EAAA;AAC1CC,gBAAAA,OAAAA,CAAQC,IAAI,CACV,gEAAA,CAAA,CAAA;AAEJ,aAAA;;AAEA,YAAA,OAAOL,sBAAsBM,IAAI,EAAA,CAAA;AACnC,SAAA,CAAA,CAAA;AACF,KAAA;AAEA,IAAA,OAAO9E,SAAS8E,IAAI,EAAA,CAAA;AACtB;;;;"}
|
|
1
|
+
{"version":3,"file":"requestFn.js","sources":["../../../src/lib/requestFn.ts"],"sourcesContent":["/**\n * This function is used to make a request to a specified endpoint.\n *\n * @template T The expected return type of the request.\n *\n * @param schema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param [options] Optional. Additional options for the request. It includes custom urlSerializer, bodySerializer, and fetch function.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function requestFn<T>(\n schema: OperationSchema,\n requestInfo: RequestFnInfo,\n options?: RequestFnOptions\n): Promise<T> {\n return baseRequestFn(schema, requestInfo, {\n urlSerializer,\n bodySerializer,\n ...options,\n });\n}\n\n/**\n * This function is used to make a request to a specified endpoint.\n * It's needed to create a custom `requestFn` with a custom `urlSerializer`\n * and `bodySerializer`, with the tree-shaking of the default `requestFn`\n * and its serializers.\n *\n * @template T The expected return type of the request.\n *\n * @param requestSchema The schema of the operation to be performed. It includes the OpenAPI path, HTTP method and media type.\n * @param requestInfo The information required to make the request. It includes parameters, headers, body, etc.\n * @param options The options for the request. It includes urlSerializer, bodySerializer, and fetch function. The 'urlSerializer' and 'bodySerializer' are required.\n *\n * @returns {Promise<T>} Returns a promise that resolves with the response of the request.\n *\n * @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.\n */\nexport async function baseRequestFn<T>(\n requestSchema: OperationSchema,\n requestInfo: RequestFnInfo,\n options: WithRequired<RequestFnOptions, 'urlSerializer' | 'bodySerializer'>\n): Promise<T> {\n const { parameters, headers, body, ...requestInfoRest } = requestInfo;\n\n const requestBody = options.bodySerializer(requestSchema, requestInfo);\n\n const baseFetch = options.fetch ?? fetch;\n\n const response = await baseFetch(\n options.urlSerializer(requestSchema, requestInfo),\n {\n method: requestSchema.method.toUpperCase(),\n body: requestBody,\n headers: mergeHeaders(\n {\n Accept: 'application/json',\n 'Content-Type': requestSchema.mediaType ?? getBodyContentType(body),\n },\n headers,\n parameters?.header,\n requestBody instanceof FormData\n ? // remove `Content-Type` if serialized body is FormData; browser will correctly set Content-Type & boundary expression\n { 'Content-Type': null }\n : undefined\n ),\n ...requestInfoRest,\n }\n );\n\n // clone response to allow multiple reads\n const clonedResponse = response.clone();\n\n if (!response.ok) {\n throw await getResponseBody(clonedResponse);\n }\n\n return (await getResponseBody(clonedResponse)) as T;\n}\n\n/**\n * Serializes the given schema and request payload into a URL string.\n *\n * This function is implemented according to the URI Template standard\n * defined in RFC 6570. It supports the expansion of path and query parameters,\n * correctly handling empty arrays, `null`, and `undefined` values by ignoring\n * them during the expansion process, as specified by the standard.\n *\n * For more information, refer to the official documentation:\n * https://datatracker.ietf.org/doc/html/rfc6570\n *\n * @param schema - The operation schema containing the URL template and method.\n * @param info - The request payload including baseUrl, path parameters, and query parameters.\n * @returns The fully constructed URL string.\n */\nexport function urlSerializer(\n schema: OperationSchema,\n info: RequestFnPayload\n): string {\n const path = schema.url.replace(\n /{(.*?)}/g,\n (substring: string, group: string) => {\n if (\n info.parameters?.path &&\n Object.prototype.hasOwnProperty.call(info.parameters.path, group)\n ) {\n return encodeURI(String(info.parameters?.path[group]));\n }\n return substring;\n }\n );\n\n const baseUrl = info.baseUrl ?? '';\n\n if (info.parameters?.query) {\n return `${baseUrl}${path}${getQueryString(info.parameters.query)}`;\n }\n\n return `${baseUrl}${path}`;\n}\n\nfunction getQueryString(params: Record<string, any>): string {\n const qs: string[] = [];\n\n const append = (key: string, value: any) => {\n qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);\n };\n\n const process = (key: string, value: any) => {\n if (typeof value === 'undefined' || value === null) return;\n\n if (Array.isArray(value)) {\n value.forEach((v) => {\n process(key, v);\n });\n } else if (typeof value === 'object') {\n Object.entries(value).forEach(([k, v]) => {\n process(`${key}[${k}]`, v);\n });\n } else {\n append(key, value);\n }\n };\n\n Object.entries(params).forEach(([key, value]) => {\n process(key, value);\n });\n\n if (qs.length > 0) {\n return `?${qs.join('&')}`;\n }\n\n return '';\n}\n\nexport function mergeHeaders(...allHeaders: (HeadersOptions | undefined)[]) {\n const headers = new Headers();\n\n for (const headerSet of allHeaders) {\n if (!headerSet || typeof headerSet !== 'object') {\n continue;\n }\n\n const headersIterator =\n headerSet instanceof Headers\n ? headerSet.entries()\n : Object.entries(headerSet);\n\n for (const [headerKey, headerValue] of headersIterator) {\n if (headerValue === null) {\n headers.delete(headerKey);\n } else if (headerValue !== undefined) {\n headers.set(headerKey, headerValue);\n }\n }\n }\n\n return headers;\n}\n\nexport function bodySerializer(\n schema: OperationSchema,\n info: RequestFnPayload\n) {\n if (info.body === undefined) return;\n\n if (\n schema.method === 'get' ||\n schema.method === 'head' ||\n schema.method === 'options'\n )\n return;\n\n if (schema.mediaType?.includes('/form-data'))\n return getRequestBodyFormData(info);\n\n if (\n !schema.mediaType?.includes('/json') &&\n (typeof info.body === 'string' ||\n info.body instanceof Blob ||\n info.body instanceof FormData)\n ) {\n return info.body;\n }\n\n return JSON.stringify(info.body);\n}\n\nfunction getRequestBodyFormData({\n body,\n}: Pick<RequestFnPayload, 'body'>): FormData | undefined {\n if (body instanceof FormData) return body;\n if (body === null) return;\n\n if (body instanceof Blob) throw new Error('Blob not supported in form-data');\n if (body instanceof ArrayBuffer)\n throw new Error('ArrayBuffer not supported in form-data');\n if (body instanceof URLSearchParams)\n throw new Error('URLSearchParams not supported in form-data');\n if (body instanceof ReadableStream)\n throw new Error('ReadableStream not supported in form-data');\n if (typeof body === 'string')\n throw new Error('String not supported in form-data');\n if (typeof body !== 'object')\n throw new Error(`Unsupported body type ${typeof body} in form-data.`);\n\n const formData = new FormData();\n\n const process = (key: string, value: any) => {\n if (typeof value === 'string' || value instanceof Blob) {\n formData.append(key, value);\n } else {\n formData.append(key, JSON.stringify(value));\n }\n };\n\n Object.entries(body)\n .filter(([_, value]) => typeof value !== 'undefined' && value !== null)\n .forEach(([key, value]) => {\n if (Array.isArray(value)) {\n value.forEach((v) => process(key, v));\n } else {\n process(key, value);\n }\n });\n\n return formData;\n}\n\nfunction getBodyContentType(body: RequestFnPayload['body']) {\n if (!body) return;\n if (body instanceof Blob) return body.type || 'application/octet-stream';\n if (typeof body === 'string') return 'text/plain';\n if (!(body instanceof FormData)) return 'application/json';\n}\n\nasync function getResponseBody<T>(response: Response): Promise<T | undefined> {\n if (response.status === 204 || response.headers.get('Content-Length') === '0')\n return undefined;\n\n const contentType = response.headers.get('Content-Type')?.toLowerCase();\n const isJSON =\n contentType?.includes('/json') || contentType?.includes('+json');\n\n if (isJSON) {\n // attempt to parse JSON for successful responses, otherwise fail\n if (response.ok) return response.json();\n\n const errorFallbackResponse = response.clone(); // clone to allow multiple reads\n\n return response.json().catch(() => {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Failed to parse response body as JSON. Falling back to .text()'\n );\n }\n // falling back to .text() when necessary for error messages\n return errorFallbackResponse.text();\n });\n }\n\n return response.text() as Promise<T>;\n}\n\n// To have definitely typed headers without a conversion to stings\nexport type HeadersOptions =\n | HeadersInit\n | Record<string, string | number | boolean | null | undefined>;\n\nexport interface OperationSchema {\n /**\n * Operation path\n * @example /user/{id}\n */\n readonly url: string; //todo::rename to `path`\n\n /**\n * Operation method\n */\n readonly method:\n | 'get'\n | 'put'\n | 'post'\n | 'patch'\n | 'delete'\n | 'options'\n | 'head'\n | 'trace';\n\n /**\n * Media type of the request body\n * @example application/json\n */\n readonly mediaType?: string;\n\n readonly security?: string[];\n}\n\nexport interface RequestFnPayload {\n /**\n * Base URL to use for the request\n * @example 'https://api.example.com'\n */\n baseUrl: string | undefined;\n\n /**\n * OpenAPI parameters\n * @example\n * ```ts\n * { path: {id: 1}, query: {search: 'hello'} }\n * ```\n */\n readonly parameters?: {\n readonly path?: Record<string, any>;\n readonly header?: Record<string, any>;\n readonly query?: Record<string, any>;\n };\n\n /**\n * Request body\n * @example { name: 'John' }\n */\n readonly body?: BodyInit | Record<string, unknown> | null;\n\n /**\n * Tanstack Query Meta\n */\n meta?: Record<string, unknown>;\n\n /** An AbortSignal to set request's signal. */\n signal?: AbortSignal | null;\n}\n\nexport interface RequestFnInfo\n extends RequestFnPayload,\n Omit<RequestInit, 'headers' | 'method' | 'body' | 'signal'> {\n /**\n * Request headers\n * @example { 'X-Auth': '123' }\n */\n readonly headers?: HeadersOptions;\n}\n\nexport interface RequestFnOptions {\n urlSerializer?: typeof urlSerializer;\n bodySerializer?: typeof bodySerializer;\n fetch?: typeof fetch;\n}\n\nexport type RequestFn<T> = typeof requestFn<T>;\n\ntype WithRequired<T, K extends keyof T> = T & {\n [_ in K]: {};\n};\n"],"names":["requestFn","schema","requestInfo","options","baseRequestFn","urlSerializer","bodySerializer","requestSchema","parameters","headers","body","requestInfoRest","requestBody","baseFetch","fetch","response","method","toUpperCase","mergeHeaders","Accept","mediaType","getBodyContentType","header","FormData","undefined","clonedResponse","clone","ok","getResponseBody","info","path","url","replace","substring","group","Object","prototype","hasOwnProperty","call","encodeURI","String","baseUrl","query","getQueryString","params","qs","append","key","value","push","encodeURIComponent","process","Array","isArray","forEach","v","entries","k","length","join","allHeaders","Headers","headerSet","headersIterator","headerKey","headerValue","delete","set","includes","getRequestBodyFormData","Blob","JSON","stringify","Error","ArrayBuffer","URLSearchParams","ReadableStream","formData","filter","_","type","status","get","contentType","toLowerCase","isJSON","json","errorFallbackResponse","catch","env","NODE_ENV","console","warn","text"],"mappings":"AAAA;;;;;;;;;;;;AAYC,IACM,eAAeA,SAAAA,CACpBC,MAAuB,EACvBC,WAA0B,EAC1BC,OAA0B,EAAA;IAE1B,OAAOC,aAAAA,CAAcH,QAAQC,WAAa,EAAA;AACxCG,QAAAA,aAAAA;AACAC,QAAAA,cAAAA;AACA,QAAA,GAAGH,OAAO;AACZ,KAAA,CAAA,CAAA;AACF,CAAA;AAEA;;;;;;;;;;;;;;;AAeC,IACM,eAAeC,aAAAA,CACpBG,aAA8B,EAC9BL,WAA0B,EAC1BC,OAA2E,EAAA;IAE3E,MAAM,EAAEK,UAAU,EAAEC,OAAO,EAAEC,IAAI,EAAE,GAAGC,eAAAA,EAAiB,GAAGT,WAAAA,CAAAA;AAE1D,IAAA,MAAMU,WAAcT,GAAAA,OAAAA,CAAQG,cAAc,CAACC,aAAeL,EAAAA,WAAAA,CAAAA,CAAAA;IAE1D,MAAMW,SAAAA,GAAYV,OAAQW,CAAAA,KAAK,IAAIA,KAAAA,CAAAA;AAEnC,IAAA,MAAMC,WAAW,MAAMF,SAAAA,CACrBV,QAAQE,aAAa,CAACE,eAAeL,WACrC,CAAA,EAAA;QACEc,MAAQT,EAAAA,aAAAA,CAAcS,MAAM,CAACC,WAAW,EAAA;QACxCP,IAAME,EAAAA,WAAAA;AACNH,QAAAA,OAAAA,EAASS,YACP,CAAA;YACEC,MAAQ,EAAA,kBAAA;YACR,cAAgBZ,EAAAA,aAAAA,CAAca,SAAS,IAAIC,kBAAmBX,CAAAA,IAAAA,CAAAA;AAChE,SAAA,EACAD,OACAD,EAAAA,UAAAA,EAAYc,MACZV,EAAAA,WAAAA,YAAuBW,QAEnB,GAAA;YAAE,cAAgB,EAAA,IAAA;SACl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AAI,EAAEA,IAAgBa,YAAAA,QAAO,GAAI,OAAO,kBAAA,CAAA;AAC1C,CAAA;AAEA,eAAeK,gBAAmBb,QAAkB,EAAA;IAClD,IAAIA,QAAAA,CAASkE,MAAM,KAAK,GAAOlE,IAAAA,QAAAA,CAASN,OAAO,CAACyE,GAAG,CAAC,gBAAsB,CAAA,KAAA,GAAA,EACxE,OAAO1D,SAAAA,CAAAA;AAET,IAAA,MAAM2D,cAAcpE,QAASN,CAAAA,OAAO,CAACyE,GAAG,CAAC,cAAiBE,CAAAA,EAAAA,WAAAA,EAAAA,CAAAA;AAC1D,IAAA,MAAMC,MACJF,GAAAA,WAAAA,EAAaf,QAAS,CAAA,OAAA,CAAA,IAAYe,aAAaf,QAAS,CAAA,OAAA,CAAA,CAAA;AAE1D,IAAA,IAAIiB,MAAQ,EAAA;;AAEV,QAAA,IAAItE,QAASY,CAAAA,EAAE,EAAE,OAAOZ,SAASuE,IAAI,EAAA,CAAA;AAErC,QAAA,MAAMC,qBAAwBxE,GAAAA,QAAAA,CAASW,KAAK,EAAA,CAAA;AAE5C,QAAA,OAAOX,QAASuE,CAAAA,IAAI,EAAGE,CAAAA,KAAK,CAAC,IAAA;AAC3B,YAAA,IAAIrC,OAAQsC,CAAAA,GAAG,CAACC,QAAQ,KAAK,aAAe,EAAA;AAC1CC,gBAAAA,OAAAA,CAAQC,IAAI,CACV,gEAAA,CAAA,CAAA;AAEJ,aAAA;;AAEA,YAAA,OAAOL,sBAAsBM,IAAI,EAAA,CAAA;AACnC,SAAA,CAAA,CAAA;AACF,KAAA;AAEA,IAAA,OAAO9E,SAAS8E,IAAI,EAAA,CAAA;AACtB;;;;"}
|
|
@@ -29,6 +29,21 @@ export declare function requestFn<T>(schema: OperationSchema, requestInfo: Reque
|
|
|
29
29
|
* @throws {error: object|string, response: Response} Throws an error if the request fails. The error includes the error message and the response from the server.
|
|
30
30
|
*/
|
|
31
31
|
export declare function baseRequestFn<T>(requestSchema: OperationSchema, requestInfo: RequestFnInfo, options: WithRequired<RequestFnOptions, 'urlSerializer' | 'bodySerializer'>): Promise<T>;
|
|
32
|
+
/**
|
|
33
|
+
* Serializes the given schema and request payload into a URL string.
|
|
34
|
+
*
|
|
35
|
+
* This function is implemented according to the URI Template standard
|
|
36
|
+
* defined in RFC 6570. It supports the expansion of path and query parameters,
|
|
37
|
+
* correctly handling empty arrays, `null`, and `undefined` values by ignoring
|
|
38
|
+
* them during the expansion process, as specified by the standard.
|
|
39
|
+
*
|
|
40
|
+
* For more information, refer to the official documentation:
|
|
41
|
+
* https://datatracker.ietf.org/doc/html/rfc6570
|
|
42
|
+
*
|
|
43
|
+
* @param schema - The operation schema containing the URL template and method.
|
|
44
|
+
* @param info - The request payload including baseUrl, path parameters, and query parameters.
|
|
45
|
+
* @returns The fully constructed URL string.
|
|
46
|
+
*/
|
|
32
47
|
export declare function urlSerializer(schema: OperationSchema, info: RequestFnPayload): string;
|
|
33
48
|
export declare function mergeHeaders(...allHeaders: (HeadersOptions | undefined)[]): Headers;
|
|
34
49
|
export declare function bodySerializer(schema: OperationSchema, info: RequestFnPayload): string | Blob | FormData | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requestFn.d.ts","sourceRoot":"","sources":["../../../src/lib/requestFn.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAC/B,MAAM,EAAE,eAAe,EACvB,WAAW,EAAE,aAAa,EAC1B,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,CAAC,CAAC,CAMZ;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACnC,aAAa,EAAE,eAAe,EAC9B,WAAW,EAAE,aAAa,EAC1B,OAAO,EAAE,YAAY,CAAC,gBAAgB,EAAE,eAAe,GAAG,gBAAgB,CAAC,GAC1E,OAAO,CAAC,CAAC,CAAC,CAoCZ;AAED,wBAAgB,aAAa,CAC3B,M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AAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAE/B,8CAA8C;IAC9C,MAAM,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,WAAW,aACf,SAAQ,gBAAgB,EACtB,IAAI,CAAC,WAAW,EAAE,SAAS,GAAG,QAAQ,GAAG,MAAM,GAAG,QAAQ,CAAC;IAC7D;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,cAAc,CAAC;CACnC;AAED,MAAM,WAAW,gBAAgB;IAC/B,aAAa,CAAC,EAAE,OAAO,aAAa,CAAC;IACrC,cAAc,CAAC,EAAE,OAAO,cAAc,CAAC;IACvC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,OAAO,SAAS,CAAC,CAAC,CAAC,CAAC;AAE/C,KAAK,YAAY,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,IAAI,CAAC,GAAG;KAC3C,CAAC,IAAI,CAAC,GAAG,EAAE;CACb,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"urlSerializer.test.d.ts","sourceRoot":"","sources":["../../../src/lib/urlSerializer.test.ts"],"names":[],"mappings":""}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openapi-qraft/react",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.14.0-beta.2",
|
|
4
4
|
"description": "API client for React, providing type-safe requests and dynamic Tanstack Query React Hooks via a modular, Proxy-based architecture.",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "NODE_ENV=production rollup --config rollup.config.mjs && tsc --project tsconfig.build.json --emitDeclarationOnly",
|
|
@@ -10,14 +10,14 @@
|
|
|
10
10
|
"typecheck": "tsc --noEmit",
|
|
11
11
|
"lint": "eslint",
|
|
12
12
|
"clean": "rimraf dist/",
|
|
13
|
-
"codegen": "openapi-qraft --plugin tanstack-query-react --plugin openapi-typescript ../test-fixtures/openapi.json -rm -o src/tests/fixtures/api --openapi-types-file-name openapi.ts --explicit-import-extensions --filter-services '/approval_policies/**,/entities/**,/files/**,!/internal/**' --operation-predefined-parameters '/approval_policies/{approval_policy_id}/**:header.x-monite-entity-id' '/entities/{entity_id}/documents:header.x-monite-version' && yarn _prettify-api",
|
|
13
|
+
"codegen": "openapi-qraft --plugin tanstack-query-react --plugin openapi-typescript ../test-fixtures/openapi.json -rm -o src/tests/fixtures/api --openapi-types-file-name openapi.ts --explicit-import-extensions --filter-services '/approval_policies/**,/entities/**,/files/**,!/internal/**' --operation-predefined-parameters '/approval_policies/{approval_policy_id}/**:header.x-monite-entity-id' '/entities/{entity_id}/documents:header.x-monite-version' --operation-name-modifier '/files/list:[a-zA-Z]+List ==> findAll' && yarn _prettify-api",
|
|
14
14
|
"_prettify-api": "prettier --write src/tests/fixtures/api/**/*.ts"
|
|
15
15
|
},
|
|
16
16
|
"sideEffects": false,
|
|
17
17
|
"devDependencies": {
|
|
18
|
-
"@openapi-qraft/cli": "1.
|
|
18
|
+
"@openapi-qraft/cli": "1.14.0-beta.2",
|
|
19
19
|
"@openapi-qraft/eslint-config": "1.0.0",
|
|
20
|
-
"@openapi-qraft/openapi-typescript-plugin": "^1.0.
|
|
20
|
+
"@openapi-qraft/openapi-typescript-plugin": "^1.1.0-beta.2",
|
|
21
21
|
"@openapi-qraft/rollup-config": "1.0.0",
|
|
22
22
|
"@openapi-qraft/test-fixtures": "1.0.0",
|
|
23
23
|
"@tanstack/react-query": "^5.17.3",
|
package/src/lib/requestFn.ts
CHANGED
|
@@ -81,6 +81,21 @@ export async function baseRequestFn<T>(
|
|
|
81
81
|
return (await getResponseBody(clonedResponse)) as T;
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
/**
|
|
85
|
+
* Serializes the given schema and request payload into a URL string.
|
|
86
|
+
*
|
|
87
|
+
* This function is implemented according to the URI Template standard
|
|
88
|
+
* defined in RFC 6570. It supports the expansion of path and query parameters,
|
|
89
|
+
* correctly handling empty arrays, `null`, and `undefined` values by ignoring
|
|
90
|
+
* them during the expansion process, as specified by the standard.
|
|
91
|
+
*
|
|
92
|
+
* For more information, refer to the official documentation:
|
|
93
|
+
* https://datatracker.ietf.org/doc/html/rfc6570
|
|
94
|
+
*
|
|
95
|
+
* @param schema - The operation schema containing the URL template and method.
|
|
96
|
+
* @param info - The request payload including baseUrl, path parameters, and query parameters.
|
|
97
|
+
* @returns The fully constructed URL string.
|
|
98
|
+
*/
|
|
84
99
|
export function urlSerializer(
|
|
85
100
|
schema: OperationSchema,
|
|
86
101
|
info: RequestFnPayload
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { urlSerializer } from './requestFn.js';
|
|
3
|
+
|
|
4
|
+
describe('urlSerializer', () => {
|
|
5
|
+
it('should correctly replace path parameters', () => {
|
|
6
|
+
expect(
|
|
7
|
+
urlSerializer(
|
|
8
|
+
{ url: '/users/{userId}/posts/{postId}', method: 'get' },
|
|
9
|
+
{
|
|
10
|
+
baseUrl: 'https://api.example.com',
|
|
11
|
+
parameters: { path: { userId: '123', postId: '456' } },
|
|
12
|
+
}
|
|
13
|
+
)
|
|
14
|
+
).toBe('https://api.example.com/users/123/posts/456');
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('should correctly append query parameters', () => {
|
|
18
|
+
expect(
|
|
19
|
+
urlSerializer(
|
|
20
|
+
{ url: '/users/{userId}/posts', method: 'get' },
|
|
21
|
+
{
|
|
22
|
+
baseUrl: 'https://api.example.com',
|
|
23
|
+
parameters: {
|
|
24
|
+
path: { userId: '123' },
|
|
25
|
+
query: { filter: 'recent', limit: 10 },
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
)
|
|
29
|
+
).toBe('https://api.example.com/users/123/posts?filter=recent&limit=10');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('should return URL without query parameters if none specified in path', () => {
|
|
33
|
+
expect(
|
|
34
|
+
urlSerializer(
|
|
35
|
+
{ url: '/users/{userId}/posts', method: 'get' },
|
|
36
|
+
{
|
|
37
|
+
baseUrl: 'https://api.example.com',
|
|
38
|
+
parameters: { path: { userId: '123', postId: '456' } },
|
|
39
|
+
}
|
|
40
|
+
)
|
|
41
|
+
).toBe('https://api.example.com/users/123/posts');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('should handle missing baseUrl gracefully', () => {
|
|
45
|
+
expect(
|
|
46
|
+
urlSerializer(
|
|
47
|
+
{ url: '/users/{userId}/posts', method: 'get' },
|
|
48
|
+
// @ts-expect-error - Missing baseUrl fallback
|
|
49
|
+
{
|
|
50
|
+
parameters: { path: { userId: '123' } },
|
|
51
|
+
}
|
|
52
|
+
)
|
|
53
|
+
).toBe('/users/123/posts');
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('should encode path parameters correctly', () => {
|
|
57
|
+
expect(
|
|
58
|
+
urlSerializer(
|
|
59
|
+
{ url: '/search/{query}', method: 'get' },
|
|
60
|
+
{
|
|
61
|
+
baseUrl: 'https://api.example.com',
|
|
62
|
+
parameters: { path: { query: 'hello world' } },
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
).toBe('https://api.example.com/search/hello%20world');
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('should correctly serialize query parameters with null values', () => {
|
|
69
|
+
expect(
|
|
70
|
+
urlSerializer(
|
|
71
|
+
{ url: '/users', method: 'get' },
|
|
72
|
+
{
|
|
73
|
+
baseUrl: 'https://api.example.com',
|
|
74
|
+
parameters: { query: { name: null, age: 30 } },
|
|
75
|
+
}
|
|
76
|
+
)
|
|
77
|
+
).toBe('https://api.example.com/users?age=30');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('should correctly serialize query parameters with undefined values', () => {
|
|
81
|
+
expect(
|
|
82
|
+
urlSerializer(
|
|
83
|
+
{ url: '/users', method: 'get' },
|
|
84
|
+
{
|
|
85
|
+
baseUrl: 'https://api.example.com',
|
|
86
|
+
parameters: { query: { name: undefined, age: 30 } },
|
|
87
|
+
}
|
|
88
|
+
)
|
|
89
|
+
).toBe('https://api.example.com/users?age=30');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('should correctly serialize query parameters with array values', () => {
|
|
93
|
+
expect(
|
|
94
|
+
urlSerializer(
|
|
95
|
+
{ url: '/users', method: 'get' },
|
|
96
|
+
{
|
|
97
|
+
baseUrl: 'https://api.example.com',
|
|
98
|
+
parameters: { query: { tags: ['admin', 'user'], age: 30 } },
|
|
99
|
+
}
|
|
100
|
+
)
|
|
101
|
+
).toBe('https://api.example.com/users?tags=admin&tags=user&age=30');
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('should correctly serialize query parameters with some null|undefined in array values', () => {
|
|
105
|
+
expect(
|
|
106
|
+
urlSerializer(
|
|
107
|
+
{ url: '/users', method: 'get' },
|
|
108
|
+
{
|
|
109
|
+
baseUrl: 'https://api.example.com',
|
|
110
|
+
parameters: { query: { tags: [null, undefined, 'user'], age: 30 } },
|
|
111
|
+
}
|
|
112
|
+
)
|
|
113
|
+
).toBe('https://api.example.com/users?tags=user&age=30');
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('should correctly serialize query parameters with an empty array', () => {
|
|
117
|
+
expect(
|
|
118
|
+
urlSerializer(
|
|
119
|
+
{ url: '/users', method: 'get' },
|
|
120
|
+
{
|
|
121
|
+
baseUrl: 'https://api.example.com',
|
|
122
|
+
parameters: { query: { tags: [], age: 30 } },
|
|
123
|
+
}
|
|
124
|
+
)
|
|
125
|
+
).toBe('https://api.example.com/users?age=30');
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('should correctly serialize query parameters with an object', () => {
|
|
129
|
+
expect(
|
|
130
|
+
urlSerializer(
|
|
131
|
+
{ url: '/users', method: 'get' },
|
|
132
|
+
{
|
|
133
|
+
baseUrl: 'https://api.example.com',
|
|
134
|
+
parameters: {
|
|
135
|
+
query: {
|
|
136
|
+
tags: {
|
|
137
|
+
one: 'two',
|
|
138
|
+
},
|
|
139
|
+
age: 30,
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
}
|
|
143
|
+
)
|
|
144
|
+
).toBe('https://api.example.com/users?tags%5Bone%5D=two&age=30');
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('should correctly serialize query parameters with an empty object', () => {
|
|
148
|
+
expect(
|
|
149
|
+
urlSerializer(
|
|
150
|
+
{ url: '/users', method: 'get' },
|
|
151
|
+
{
|
|
152
|
+
baseUrl: 'https://api.example.com',
|
|
153
|
+
parameters: {
|
|
154
|
+
query: {
|
|
155
|
+
tags: {},
|
|
156
|
+
age: 30,
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
}
|
|
160
|
+
)
|
|
161
|
+
).toBe('https://api.example.com/users?age=30');
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('should correctly serialize query parameters with an null|undefined object fields', () => {
|
|
165
|
+
expect(
|
|
166
|
+
urlSerializer(
|
|
167
|
+
{ url: '/users', method: 'get' },
|
|
168
|
+
{
|
|
169
|
+
baseUrl: 'https://api.example.com',
|
|
170
|
+
parameters: {
|
|
171
|
+
query: {
|
|
172
|
+
tags: {
|
|
173
|
+
foo: null,
|
|
174
|
+
bar: undefined,
|
|
175
|
+
},
|
|
176
|
+
age: 30,
|
|
177
|
+
},
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
)
|
|
181
|
+
).toBe('https://api.example.com/users?age=30');
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it('should correctly serialize query parameters with nested objects', () => {
|
|
185
|
+
expect(
|
|
186
|
+
urlSerializer(
|
|
187
|
+
{ url: '/search', method: 'get' },
|
|
188
|
+
{
|
|
189
|
+
baseUrl: 'https://api.example.com',
|
|
190
|
+
parameters: { query: { filter: { category: 'books', type: null } } },
|
|
191
|
+
}
|
|
192
|
+
)
|
|
193
|
+
).toBe('https://api.example.com/search?filter%5Bcategory%5D=books');
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
it('should handle null values in path parameters', () => {
|
|
197
|
+
expect(
|
|
198
|
+
urlSerializer(
|
|
199
|
+
{ url: '/users/{userId}/posts/{postId}', method: 'get' },
|
|
200
|
+
{
|
|
201
|
+
baseUrl: 'https://api.example.com',
|
|
202
|
+
parameters: { path: { userId: null, postId: '456' } },
|
|
203
|
+
}
|
|
204
|
+
)
|
|
205
|
+
).toBe('https://api.example.com/users/null/posts/456');
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('should handle undefined values in path parameters', () => {
|
|
209
|
+
expect(
|
|
210
|
+
urlSerializer(
|
|
211
|
+
{ url: '/users/{userId}/posts/{postId}', method: 'get' },
|
|
212
|
+
{
|
|
213
|
+
baseUrl: 'https://api.example.com',
|
|
214
|
+
parameters: { path: { userId: undefined, postId: '456' } },
|
|
215
|
+
}
|
|
216
|
+
)
|
|
217
|
+
).toBe('https://api.example.com/users/undefined/posts/456');
|
|
218
|
+
});
|
|
219
|
+
});
|