Skip to content

Commit

Permalink
make code more generic
Browse files Browse the repository at this point in the history
  • Loading branch information
phryneas committed Oct 8, 2023
1 parent 2cc28c1 commit 9c68261
Showing 1 changed file with 18 additions and 25 deletions.
43 changes: 18 additions & 25 deletions packages/rtk-query-codegen-openapi/src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,29 +258,26 @@ export async function generateApi(

const allNames = parameters.map((p) => p.name);
const queryArg: QueryArgDefinitions = {};
for (const param of parameters) {
const isPureSnakeCase = /^[a-zA-Z][a-zA-Z0-9_]*$/.test(param.name);
const camelCaseName = camelCase(param.name);

let name = isPureSnakeCase && !allNames.includes(camelCaseName) ? camelCaseName : param.name;

if (name in queryArg) {
let duplicatedNewName = `${queryArg[name].param?.in}_${name}`
duplicatedNewName = isPureSnakeCase && !allNames.includes(duplicatedNewName) ? camelCase(duplicatedNewName) : duplicatedNewName
while (duplicatedNewName in queryArg) {
duplicatedNewName = '_' + duplicatedNewName;
}
queryArg[duplicatedNewName] = queryArg[name]
queryArg[duplicatedNewName].name = duplicatedNewName
delete queryArg[name]

name = `${param.in}_${name}`
name = isPureSnakeCase && !allNames.includes(name) ? camelCase(name) : name;
function generateName(name: string, potentialPrefix: string) {
const isPureSnakeCase = /^[a-zA-Z][a-zA-Z0-9_]*$/.test(name);
// prefix with `query`, `path` or `body` if there are multiple paramters with the same name
const hasNamingConflict = allNames.filter((n) => n === name).length > 1;
if (hasNamingConflict) {
name = `${potentialPrefix}_${name}`;
}
// convert to camelCase if the name is pure snake_case and there are no naming conflicts
const camelCaseName = camelCase(name);
if (isPureSnakeCase && !allNames.includes(camelCaseName)) {
name = camelCaseName;
}
// if there are still any naming conflicts, prepend with underscore
while (name in queryArg) {
name = '_' + name;
}

return name;
}
for (const param of parameters) {
const name = generateName(param.name, param.in);
queryArg[name] = {
origin: 'param',
name,
Expand All @@ -296,11 +293,7 @@ export async function generateApi(
const schema = apiGen.getSchemaFromContent(body.content);
const type = apiGen.getTypeFromSchema(schema);
const schemaName = camelCase((type as any).name || getReferenceName(schema) || 'body');
let name = schemaName in queryArg ? 'body' : schemaName;

while (name in queryArg) {
name = '_' + name;
}
const name = generateName(schemaName in queryArg ? 'body' : schemaName, 'body');

queryArg[name] = {
origin: 'body',
Expand Down Expand Up @@ -507,7 +500,7 @@ type QueryArgDefinition = {
originalName: string;
type: ts.TypeNode;
required?: boolean;
param?: OpenAPIV3.ParameterObject
param?: OpenAPIV3.ParameterObject;
} & (
| {
origin: 'param';
Expand Down

0 comments on commit 9c68261

Please sign in to comment.