Skip to content
Open
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
41 changes: 41 additions & 0 deletions codegen/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,47 @@ export type FullRequestOptions = RequestOptions & {
method?: HTTPMethod;
};

const requestOptionKeys = new Set<keyof RequestOptions>([
"authorization",
"headers",
"host",
"maxRetries",
"signal",
"timeout",
]);

export function isRequestOptions(
value: RequestOptions | QueryParams | undefined,
): value is RequestOptions {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return false;
}

return Object.keys(value).some((key) =>
requestOptionKeys.has(key as keyof RequestOptions),
);
}

export function splitOptionalQueryAndOptions<TQuery extends QueryParams>(
queryOrOptions: TQuery | RequestOptions | undefined,
options: RequestOptions | undefined,
): {
query: TQuery | undefined;
options: RequestOptions | undefined;
} {
if (isRequestOptions(queryOrOptions)) {
return {
query: undefined,
options: queryOrOptions,
};
}

return {
query: queryOrOptions,
options,
};
}

export class SumUpError extends Error {}

export class APIError<T> extends SumUpError {
Expand Down
185 changes: 132 additions & 53 deletions codegen/src/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,25 @@ export async function generateResource(
w0() {},
};

const hasOptionalQueryMethods = [...iterPathConfig(spec.paths)].some(
({ methodSpec, pathSpec }) => {
if (!methodSpec.tags?.includes(tag.name)) {
return false;
}

const params = (pathSpec.parameters || []).concat(
methodSpec.parameters || [],
);
const queryParams = params.filter(
(p) => "in" in p && p.in === "query",
) as OpenAPIV3_1.ParameterObject[];

return (
queryParams.length > 0 && !queryParams.some((param) => param.required)
);
},
);

const resolveResponseObject = (
response: OpenAPIV3_1.ResponseObject | OpenAPIV3_1.ReferenceObject,
) => {
Expand Down Expand Up @@ -181,7 +200,7 @@ export async function generateResource(

writer.w("// Code generated by @sumup/sumup-ts-codegen. DO NOT EDIT.\n");
writer.w(
'import { APIResource, type RequestOptions, type WithResponse } from "../../core";',
`import { APIResource, type RequestOptions${hasOptionalQueryMethods ? ", splitOptionalQueryAndOptions" : ""}, type WithResponse } from "../../core";`,
);

const sortedSharedTypes = [...usedSharedTypes].sort((a, b) =>
Expand Down Expand Up @@ -310,82 +329,142 @@ export class ${resourceClassName} extends APIResource {`);
);
const successTypes = unique(successResponses);
const successType = successTypes.join(" | ") || "void";
const hasOptionalQueryParams =
queryParams.length > 0 && !queryParams.some((param) => param.required);

const comment = docComment(methodSpec.description || methodSpec.summary);
if (comment) {
writer.w(comment);
}

const body = getRequestBody(opId, methodSpec);
writer.w0(`${methodName}(`);

if (pathParams.length > 0) {
for (const param of pathParams) {
writer.w0(Case.camel(param.name));
writer.w0(": ");
schemaToTypes(param.schema!, writer);
writer.w0(", ");
const writeMethodSignature = ({
includeMethodName,
withResponse,
queryVariant,
}: {
includeMethodName: boolean;
withResponse: boolean;
queryVariant: "query" | "optionsOnly" | "queryOrOptions";
}) => {
if (includeMethodName) {
writer.w0(
`${withResponse ? `${methodName}WithResponse` : methodName}(`,
);
}
}

if (body) {
writer.w0(`body${body.required ? "" : "?"}: ${body.typeName}, `);
}
if (pathParams.length > 0) {
for (const param of pathParams) {
writer.w0(Case.camel(param.name));
writer.w0(": ");
schemaToTypes(param.schema!, writer);
writer.w0(", ");
}
}

if (queryParams.length > 0) {
writer.w0("query");
if (!queryParams.some((param) => param.required)) writer.w0("?");
writer.w0(`: ${queryParamsType(methodNameType)}, `);
}
if (body) {
writer.w0(`body${body.required ? "" : "?"}: ${body.typeName}, `);
}

writer.w(`options?: RequestOptions): Promise<${successType}> {
return this._client.${method}<${successType}>({
path: ${pathToTemplateStr(path)},`);
if (methodSpec.requestBody) {
writer.w(" body,");
}
if (queryParams.length > 0) {
writer.w(" query,");
}
writer.w(` ...options,
})
}\n`);
if (queryParams.length > 0) {
if (queryVariant === "query") {
writer.w0("query");
if (!queryParams.some((param) => param.required)) writer.w0("?");
writer.w0(`: ${queryParamsType(methodNameType)}, `);
} else if (queryVariant === "queryOrOptions") {
writer.w0(
`queryOrOptions?: ${queryParamsType(methodNameType)} | RequestOptions, `,
);
}
}

writer.w0(`${methodName}WithResponse(`);
writer.w0("options?: RequestOptions): ");
writer.w0(
withResponse
? `Promise<WithResponse<${successType}>>`
: `Promise<${successType}>`,
);
};

if (pathParams.length > 0) {
for (const param of pathParams) {
writer.w0(Case.camel(param.name));
writer.w0(": ");
schemaToTypes(param.schema!, writer);
writer.w0(", ");
}
if (hasOptionalQueryParams) {
writeMethodSignature({
includeMethodName: true,
withResponse: false,
queryVariant: "query",
});
writer.w(";");
writeMethodSignature({
includeMethodName: true,
withResponse: false,
queryVariant: "optionsOnly",
});
writer.w(";");
}

if (body) {
writer.w0(`body${body.required ? "" : "?"}: ${body.typeName}, `);
writeMethodSignature({
includeMethodName: true,
withResponse: false,
queryVariant: hasOptionalQueryParams ? "queryOrOptions" : "query",
});
writer.w(" {");
if (hasOptionalQueryParams) {
writer.w(
` const { query, options: requestOptions } = splitOptionalQueryAndOptions<${queryParamsType(methodNameType)}>(queryOrOptions, options);`,
);
}
writer.w(` return this._client.${method}<${successType}>({`);
writer.w(` path: ${pathToTemplateStr(path)},`);
if (methodSpec.requestBody) {
writer.w(" body,");
}

if (queryParams.length > 0) {
writer.w0("query");
if (!queryParams.some((param) => param.required)) writer.w0("?");
writer.w0(`: ${queryParamsType(methodNameType)}, `);
writer.w(" query,");
}

writer.w(
`options?: RequestOptions): Promise<WithResponse<${successType}>> {
return this._client.${method}WithResponse<${successType}>({
path: ${pathToTemplateStr(path)},`,
` ...${hasOptionalQueryParams ? "requestOptions" : "options"},`,
);
writer.w(" });");
writer.w("}\n");

if (hasOptionalQueryParams) {
writeMethodSignature({
includeMethodName: true,
withResponse: true,
queryVariant: "query",
});
writer.w(";");
writeMethodSignature({
includeMethodName: true,
withResponse: true,
queryVariant: "optionsOnly",
});
writer.w(";");
}

writeMethodSignature({
includeMethodName: true,
withResponse: true,
queryVariant: hasOptionalQueryParams ? "queryOrOptions" : "query",
});
writer.w(" {");
if (hasOptionalQueryParams) {
writer.w(
` const { query, options: requestOptions } = splitOptionalQueryAndOptions<${queryParamsType(methodNameType)}>(queryOrOptions, options);`,
);
}
writer.w(` return this._client.${method}WithResponse<${successType}>({`);
writer.w(` path: ${pathToTemplateStr(path)},`);
if (methodSpec.requestBody) {
writer.w(" body,");
writer.w(" body,");
}
if (queryParams.length > 0) {
writer.w(" query,");
writer.w(" query,");
}
writer.w(` ...options,
})
}\n`);
writer.w(
` ...${hasOptionalQueryParams ? "requestOptions" : "options"},`,
);
writer.w(" });");
writer.w("}\n");
}
writer.w("}");

Expand Down
2 changes: 1 addition & 1 deletion sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ console.info(merchant);
Per-request options are available as the last argument to any SDK call. For example, you can override authorization, timeout, retries, or headers for a single request:

```ts
await client.checkouts.list(undefined, {
await client.checkouts.list({
timeout: 5_000,
});

Expand Down
4 changes: 1 addition & 3 deletions sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,7 @@ export class HTTPClient {
});
}

public request<T>({
...params
}: Core.FullRequestOptions): Promise<T> {
public request<T>({ ...params }: Core.FullRequestOptions): Promise<T> {
return this.requestWithResponse<T>(params).then(({ data }) => data);
}

Expand Down
41 changes: 41 additions & 0 deletions sdk/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,47 @@ export type FullRequestOptions = RequestOptions & {
method?: HTTPMethod;
};

const requestOptionKeys = new Set<keyof RequestOptions>([
"authorization",
"headers",
"host",
"maxRetries",
"signal",
"timeout",
]);

export function isRequestOptions(
value: RequestOptions | QueryParams | undefined,
): value is RequestOptions {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return false;
}

return Object.keys(value).some((key) =>
requestOptionKeys.has(key as keyof RequestOptions),
);
}

export function splitOptionalQueryAndOptions<TQuery extends QueryParams>(
queryOrOptions: TQuery | RequestOptions | undefined,
options: RequestOptions | undefined,
): {
query: TQuery | undefined;
options: RequestOptions | undefined;
} {
if (isRequestOptions(queryOrOptions)) {
return {
query: undefined,
options: queryOrOptions,
};
}

return {
query: queryOrOptions,
options,
};
}

export class SumUpError extends Error {}

export class APIError<T> extends SumUpError {
Expand Down
Loading
Loading