Skip to content

Improve query serializer #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 12 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
325 changes: 164 additions & 161 deletions package-lock.json

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,18 @@
"homepage": "https://github.com/marcomuser/openapi-fetch-codegen#readme",
"dependencies": {
"@apidevtools/json-schema-ref-parser": "^10.1.0",
"openapi-typescript": "^6.2.0",
"openapi-typescript": "^6.2.1",
"yargs-parser": "^21.1.1"
},
"devDependencies": {
"@types/node": "^18.15.5",
"@types/node": "^18.15.11",
"@types/yargs-parser": "^21.0.0",
"@typescript-eslint/eslint-plugin": "^5.56.0",
"@typescript-eslint/parser": "^5.56.0",
"eslint": "^8.36.0",
"@typescript-eslint/eslint-plugin": "^5.57.0",
"@typescript-eslint/parser": "^5.57.0",
"eslint": "^8.37.0",
"eslint-config-prettier": "^8.8.0",
"prettier": "^2.8.6",
"prettier": "^2.8.7",
"rimraf": "^4.4.1",
"typescript": "^5.0.2"
"typescript": "^5.0.3"
}
}
14 changes: 7 additions & 7 deletions src/printer/fetchFns/body/printHeaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,34 @@ import type { TransformedOperation } from "../../../transformer/operations/build
import { OMITTABLE_REQ_CONTENT_TYPES } from "../../../utils/constants.js";

export const printHeaders = ({
reqContentType,
requestBody,
responsesWithContentType,
}: TransformedOperation) => {
return `const clonedConfig = structuredClone(config);
const { baseUrl, headers: configHeaders, ...rest } = clonedConfig;

const headers = ${getHeaders(reqContentType, responsesWithContentType)}`;
const headers = ${getHeaders(requestBody, responsesWithContentType)}`;
};

const getHeaders = (
reqContentType: TransformedOperation["reqContentType"],
requestBody: TransformedOperation["requestBody"],
responsesWithContentType: TransformedOperation["responsesWithContentType"]
) => {
const hasNonOmittableReqContentType = Boolean(
reqContentType &&
requestBody &&
!OMITTABLE_REQ_CONTENT_TYPES[
reqContentType as keyof typeof OMITTABLE_REQ_CONTENT_TYPES
requestBody.contentType as keyof typeof OMITTABLE_REQ_CONTENT_TYPES
]
);

if (hasNonOmittableReqContentType && responsesWithContentType.size) {
return `new Headers({
"Accept": "${getAcceptValue(responsesWithContentType)}",
"Content-Type": "${reqContentType}",
"Content-Type": "${requestBody?.contentType}",
})`;
} else if (hasNonOmittableReqContentType && !responsesWithContentType.size) {
return `new Headers({
"Content-Type": "${reqContentType}",
"Content-Type": "${requestBody?.contentType}",
})`;
} else if (!hasNonOmittableReqContentType && responsesWithContentType.size) {
return `new Headers({
Expand Down
19 changes: 11 additions & 8 deletions src/printer/fetchFns/body/printOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { indt, nl } from "../../../utils/format.js";

export const printOptions = ({
method,
reqContentType,
requestBody,
parameterTypes,
}: TransformedOperation) => {
let optionsProps = `method: "${method}",`;
optionsProps += getHeadersProp(parameterTypes);
optionsProps += getBodyProp(reqContentType);
optionsProps += getBodyProp(requestBody);

return `const options: RequestInit = {
${indt(optionsProps)}
Expand All @@ -28,15 +28,18 @@ const getHeadersProp = (
return `${nl()}headers: serializeHeaders(headers, configHeaders, params.header),`;
};

const getBodyProp = (
reqContentType: TransformedOperation["reqContentType"]
) => {
if (!reqContentType) {
const getBodyProp = (requestBody: TransformedOperation["requestBody"]) => {
if (!requestBody) {
return "";
}

if (isHandledContentType(reqContentType)) {
return `${nl()}body: ${REQ_BODY_CONTENT_TYPE_DICT[reqContentType]},`;
if (isHandledContentType(requestBody.contentType)) {
return requestBody.contentType === "multipart/form-data" ||
requestBody.contentType === "application/x-www-form-urlencoded"
? `${nl()}body: ${REQ_BODY_CONTENT_TYPE_DICT[requestBody.contentType](
requestBody.encoding
)},`
: `${nl()}body: ${REQ_BODY_CONTENT_TYPE_DICT[requestBody.contentType]},`;
}

return `${nl()}body: params.requestBody,`;
Expand Down
22 changes: 11 additions & 11 deletions src/printer/fetchFns/header/printFnHeader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,27 @@ export const printFnHeader = ({
operationId,
hasParameters,
parameterTypes,
reqContentType,
requestBody,
}: TransformedOperation) => {
const parametersTypeRef = hasParameters
? parameterTypes.cookie
? `Omit<operations["${operationId}"]["parameters"], "cookie">`
: `operations["${operationId}"]["parameters"]`
: "";

const reqBodyTypeRef = reqContentType
const requestBodyTypeRef = requestBody
? `{
[P in keyof Pick<
operations["${operationId}"],
"requestBody"
>]: Exclude<
operations["${operationId}"]["requestBody"],
operations["${operationId}"][P],
undefined
>["content"]["${reqContentType}"];
>["content"]["${requestBody.contentType}"];
}`
: "";

const params = getParams(parametersTypeRef, reqBodyTypeRef);
const params = getParams(parametersTypeRef, requestBodyTypeRef);

const args = params
? `${params}
Expand All @@ -36,13 +36,13 @@ export const printFnHeader = ({
) => {`;
};

const getParams = (parametersTypeRef: string, reqBodyTypeRef: string) => {
if (parametersTypeRef && !reqBodyTypeRef) {
const getParams = (parametersTypeRef: string, requestBodyTypeRef: string) => {
if (parametersTypeRef && !requestBodyTypeRef) {
return `params: ${parametersTypeRef},`;
} else if (!parametersTypeRef && reqBodyTypeRef) {
return `params: ${reqBodyTypeRef},`;
} else if (parametersTypeRef && reqBodyTypeRef) {
return `params: ${parametersTypeRef} & ${reqBodyTypeRef},`;
} else if (!parametersTypeRef && requestBodyTypeRef) {
return `params: ${requestBodyTypeRef},`;
} else if (parametersTypeRef && requestBodyTypeRef) {
return `params: ${parametersTypeRef} & ${requestBodyTypeRef},`;
} else {
return "";
}
Expand Down
2 changes: 1 addition & 1 deletion src/printer/header/printSerializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const querySerializer = `const serializeQuery = <
query: T = {} as T,
options: QuerySerializerOptions<U>
) => {
const { encoder } = options;
const { encoder, encoding = {} } = options;
for (const [key, value] of Object.entries(query)) {
if (Array.isArray(value)) {
for (const item of value) {
Expand Down
4 changes: 4 additions & 0 deletions src/printer/header/printTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,9 @@ type ExtRequestInit = RequestInit & TBaseUrl;

type QuerySerializerOptions<T extends FormData | URLSearchParams> = {
encoder: T;
encoding?: Record<
string,
{ explode?: boolean; style?: string; [key: string]: any }
>;
};`;
};
4 changes: 2 additions & 2 deletions src/transformer/operations/buildOperations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
RequestBodyObj,
} from "../../utils/types.js";
import { getParameterTypes } from "./getParameterTypes.js";
import { getReqSortedContentType } from "./getReqSortedContentType.js";
import { getRequestBody } from "./getRequestBody.js";
import { getResWithSortedContentType } from "./getResWithSortedContentType.js";

export const buildOperations = (spec: OpenAPIObj) => {
Expand All @@ -28,7 +28,7 @@ export const buildOperations = (spec: OpenAPIObj) => {
parameterTypes: getParameterTypes(
methodSchema.parameters as ParameterObj[] | undefined
),
reqContentType: getReqSortedContentType(
requestBody: getRequestBody(
methodSchema.requestBody as RequestBodyObj | undefined
),
responsesWithContentType: getResWithSortedContentType(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { PREFERRED_REQ_CONTENT_TYPES } from "../../utils/constants.js";
import type { RequestBodyObj } from "../../utils/types.js";
import type { MediaTypeObj, RequestBodyObj } from "../../utils/types.js";

export const getReqSortedContentType = (requestBody?: RequestBodyObj) => {
export const getRequestBody = (requestBody?: RequestBodyObj) => {
if (!requestBody?.content) {
return null;
}
Expand All @@ -16,12 +16,19 @@ export const getReqSortedContentType = (requestBody?: RequestBodyObj) => {
(type) => !PREFERRED_REQ_CONTENT_TYPES.includes(type)
);

return availableTypes
const contentType = availableTypes
.sort(
(a, z) =>
PREFERRED_REQ_CONTENT_TYPES.indexOf(a) -
PREFERRED_REQ_CONTENT_TYPES.indexOf(z)
)
.concat(remainingTypes)
.at(0) as string;

const encoding = (requestBody.content[contentType] as MediaTypeObj).encoding;

return {
contentType,
encoding,
} as const;
};
14 changes: 10 additions & 4 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Encoding } from "./types.js";

export const HTTP_VERBS = {
get: true,
head: true,
Expand All @@ -24,10 +26,14 @@ export const REQ_BODY_CONTENT_TYPE_DICT = {
"*/*": "JSON.stringify(params.requestBody)",
"application/*": "JSON.stringify(params.requestBody)",
"application/json": "JSON.stringify(params.requestBody)",
"application/x-www-form-urlencoded":
"serializeQuery(params.requestBody, { encoder: new URLSearchParams() })",
"multipart/form-data":
"serializeQuery(params.requestBody, { encoder: new FormData() })",
"application/x-www-form-urlencoded": (encoding?: Encoding) =>
`serializeQuery(params.requestBody, { encoder: new URLSearchParams(), encoding: ${JSON.stringify(
encoding
)} })`,
"multipart/form-data": (encoding?: Encoding) =>
`serializeQuery(params.requestBody, { encoder: new FormData(), encoding: ${JSON.stringify(
encoding
)} })`,
"text/html": "params.requestBody",
"text/plain": "params.requestBody",
"text/plain charset=utf-8": "params.requestBody",
Expand Down
5 changes: 5 additions & 0 deletions src/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
ResponsesObject,
ResponseObject,
OpenAPITSOptions,
MediaTypeObject,
} from "openapi-typescript";

export type OpenAPIObj = OpenAPI3;
Expand All @@ -17,6 +18,10 @@ export type ParameterObj = ParameterObject;

export type RequestBodyObj = RequestBodyObject;

export type MediaTypeObj = MediaTypeObject;

export type Encoding = MediaTypeObject["encoding"];

export type ResponsesObj = ResponsesObject;

export type ResponseObj = ResponseObject;
Expand Down