Skip to content

Commit

Permalink
Replace inline require with dynamic import
Browse files Browse the repository at this point in the history
  • Loading branch information
aryaemami59 committed Jan 29, 2024
1 parent 6466cc2 commit ea195e7
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 81 deletions.
5 changes: 2 additions & 3 deletions packages/rtk-query-codegen-openapi/src/bin/cli.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#!/usr/bin/env node

import { dirname, resolve } from 'path';
import { generateEndpoints, parseConfig } from '../';

import program from 'commander';
import { dirname, resolve } from 'node:path';
import { generateEndpoints, parseConfig } from '../';

let ts = false;
try {
Expand Down
122 changes: 61 additions & 61 deletions packages/rtk-query-codegen-openapi/src/generate.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
import * as path from 'path';

import { camelCase } from 'lodash';
import path from 'node:path';
import ApiGenerator, {
getOperationName as _getOperationName,
getReferenceName,
isReference,
supportDeepObjects,
} from 'oazapfts/lib/codegen/generate';
import type { EndpointMatcher, EndpointOverrides, GenerationOptions, OperationDefinition, TextMatcher } from './types';
import { capitalize, getOperationDefinitions, getV3Doc, removeUndefined, isQuery as testIsQuery } from './utils';
import {
createPropertyAssignment,
createQuestionToken,
isValidIdentifier,
keywordType,
} from 'oazapfts/lib/codegen/tscodegen';
import { generateCreateApiCall, generateEndpointDefinition, generateImportNode, generateTagTypes } from './codegen';

import type { ObjectPropertyDefinitions } from './codegen';
import type { OpenAPIV3 } from 'openapi-types';
import { camelCase } from 'lodash';
import { factory } from './utils/factory';
import { generateReactHooks } from './generators/react-hooks';
import ts from 'typescript';
import type { ObjectPropertyDefinitions } from './codegen';
import { generateCreateApiCall, generateEndpointDefinition, generateImportNode, generateTagTypes } from './codegen';
import { generateReactHooks } from './generators/react-hooks';
import type { EndpointMatcher, EndpointOverrides, GenerationOptions, OperationDefinition, TextMatcher } from './types';
import { capitalize, getOperationDefinitions, getV3Doc, removeUndefined, isQuery as testIsQuery } from './utils';
import { factory } from './utils/factory';

const generatedApiName = 'injectedRtkApi';

Expand Down Expand Up @@ -175,13 +173,13 @@ export async function generateApi(
...apiGen.enumAliases,
...(hooks
? [
generateReactHooks({
exportName: generatedApiName,
operationDefinitions,
endpointOverrides,
config: hooks,
}),
]
generateReactHooks({
exportName: generatedApiName,
operationDefinitions,
endpointOverrides,
config: hooks,
}),
]
: []),
],
factory.createToken(ts.SyntaxKind.EndOfFileToken),
Expand Down Expand Up @@ -301,7 +299,9 @@ export async function generateApi(
const body = apiGen.resolve(requestBody);
const schema = apiGen.getSchemaFromContent(body.content);
const type = apiGen.getTypeFromSchema(schema);
const schemaName = camelCase((type as any).name || getReferenceName(schema) || ("title" in schema && schema.title) || 'body');
const schemaName = camelCase(
(type as any).name || getReferenceName(schema) || ('title' in schema && schema.title) || 'body'
);
const name = generateName(schemaName in queryArg ? 'body' : schemaName, 'body');

queryArg[name] = {
Expand Down Expand Up @@ -335,19 +335,19 @@ export async function generateApi(
? isFlatArg
? withQueryComment({ ...queryArgValues[0].type }, queryArgValues[0], false)
: factory.createTypeLiteralNode(
queryArgValues.map((def) =>
withQueryComment(
factory.createPropertySignature(
undefined,
propertyName(def.name),
createQuestionToken(!def.required),
def.type
),
def,
true
queryArgValues.map((def) =>
withQueryComment(
factory.createPropertySignature(
undefined,
propertyName(def.name),
createQuestionToken(!def.required),
def.type
),
def,
true
)
)
)
)
: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword)
)
).name
Expand Down Expand Up @@ -391,18 +391,18 @@ export async function generateApi(
return parameters.length === 0
? undefined
: factory.createPropertyAssignment(
factory.createIdentifier(propertyName),
factory.createObjectLiteralExpression(
parameters.map(
(param) =>
createPropertyAssignment(
param.originalName,
isFlatArg ? rootObject : accessProperty(rootObject, param.name)
),
true
factory.createIdentifier(propertyName),
factory.createObjectLiteralExpression(
parameters.map(
(param) =>
createPropertyAssignment(
param.originalName,
isFlatArg ? rootObject : accessProperty(rootObject, param.name)
),
true
)
)
)
);
);
}

return factory.createArrowFunction(
Expand All @@ -423,17 +423,17 @@ export async function generateApi(
isQuery && verb.toUpperCase() === 'GET'
? undefined
: factory.createPropertyAssignment(
factory.createIdentifier('method'),
factory.createStringLiteral(verb.toUpperCase())
),
factory.createIdentifier('method'),
factory.createStringLiteral(verb.toUpperCase())
),
bodyParameter === undefined
? undefined
: factory.createPropertyAssignment(
factory.createIdentifier('body'),
isFlatArg
? rootObject
: factory.createPropertyAccessExpression(rootObject, factory.createIdentifier(bodyParameter.name))
),
factory.createIdentifier('body'),
isFlatArg
? rootObject
: factory.createPropertyAccessExpression(rootObject, factory.createIdentifier(bodyParameter.name))
),
createObjectLiteralProperty(pickParams('cookie'), 'cookies'),
createObjectLiteralProperty(pickParams('header'), 'headers'),
createObjectLiteralProperty(pickParams('query'), 'params'),
Expand All @@ -445,12 +445,12 @@ export async function generateApi(
}

// eslint-disable-next-line no-empty-pattern
function generateQueryEndpointProps({ }: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions {
function generateQueryEndpointProps({}: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions {
return {}; /* TODO needs implementation - skip for now */
}

// eslint-disable-next-line no-empty-pattern
function generateMutationEndpointProps({ }: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions {
function generateMutationEndpointProps({}: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions {
return {}; /* TODO needs implementation - skip for now */
}
}
Expand Down Expand Up @@ -480,16 +480,16 @@ function generatePathExpression(

return expressions.length
? factory.createTemplateExpression(
factory.createTemplateHead(head),
expressions.map(([prop, literal], index) =>
factory.createTemplateSpan(
isFlatArg ? rootObject : accessProperty(rootObject, prop),
index === expressions.length - 1
? factory.createTemplateTail(literal)
: factory.createTemplateMiddle(literal)
factory.createTemplateHead(head),
expressions.map(([prop, literal], index) =>
factory.createTemplateSpan(
isFlatArg ? rootObject : accessProperty(rootObject, prop),
index === expressions.length - 1
? factory.createTemplateTail(literal)
: factory.createTemplateMiddle(literal)
)
)
)
)
: factory.createNoSubstitutionTemplateLiteral(head);
}

Expand All @@ -500,13 +500,13 @@ type QueryArgDefinition = {
required?: boolean;
param?: OpenAPIV3.ParameterObject;
} & (
| {
| {
origin: 'param';
param: OpenAPIV3.ParameterObject;
}
| {
| {
origin: 'body';
body: OpenAPIV3.RequestBodyObject;
}
);
);
type QueryArgDefinitions = Record<string, QueryArgDefinition>;
10 changes: 5 additions & 5 deletions packages/rtk-query-codegen-openapi/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from 'path';
import fs from 'fs';
import fs from 'node:fs';
import path from 'node:path';
import type { CommonOptions, ConfigFile, GenerationOptions, OutputFileOptions } from './types';
import { isValidUrl, prettify } from './utils';
export type { ConfigFile } from './types';
Expand All @@ -11,11 +11,11 @@ export async function generateEndpoints(options: GenerationOptions): Promise<str
? options.schemaFile
: path.resolve(process.cwd(), schemaLocation);

const sourceCode = await enforceOazapftsTsVersion(() => {
const { generateApi } = require('./generate');
const sourceCode = await enforceOazapftsTsVersion(async () => {
const { generateApi } = await import('./generate');
return generateApi(schemaAbsPath, options);
});
const outputFile = options.outputFile;
const { outputFile } = options;
if (outputFile) {
fs.writeFileSync(path.resolve(process.cwd(), outputFile), await prettify(outputFile, sourceCode));
} else {
Expand Down
18 changes: 9 additions & 9 deletions packages/rtk-query-codegen-openapi/test/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { ExecException } from 'child_process';
import { exec } from 'child_process';
import * as fs from 'fs';
import path from 'path';
import del from 'del';
import type { ExecException } from 'node:child_process';
import { exec } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';

function cli(args: string[], cwd: string): Promise<{ error: ExecException | null; stdout: string; stderr: string }> {
const pwd = (process.env && process.env.PWD) || '.';
const pwd = process.env?.PWD || '.';
const cmd = `${require.resolve('ts-node/dist/bin')} -T -P ${path.resolve(pwd, 'tsconfig.json')} ${path.resolve(
pwd,
'src/bin/cli.ts'
Expand Down Expand Up @@ -44,7 +44,7 @@ Done
});

expect(fs.readFileSync(path.resolve(tmpDir, 'example.ts'), 'utf-8')).toMatchSnapshot();
}, 25000);
}, 25_000);

test('paths are relative to configfile, not to cwd', async () => {
const out = await cli([`../test/config.example.js`], path.resolve(__dirname, '../src'));
Expand All @@ -58,7 +58,7 @@ Done
});

expect(fs.readFileSync(path.resolve(tmpDir, 'example.ts'), 'utf-8')).toMatchSnapshot();
}, 25000);
}, 25_000);

test('ts, js and json all work the same', async () => {
await cli([`./config.example.js`], __dirname);
Expand All @@ -70,10 +70,10 @@ Done

expect(fromTs).toEqual(fromJs);
expect(fromJson).toEqual(fromJs);
}, 120000);
}, 120_000);

test('missing parameters doesnt fail', async () => {
const out = await cli([`./config.invalid-example.json`], __dirname);
expect(out.stderr).toContain("Error: path parameter petId does not seem to be defined in '/pet/{petId}'!");
}, 25000);
}, 25_000);
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import del from 'del';
import fs from 'fs';
import path, { resolve } from 'path';
import fs from 'node:fs';
import path, { resolve } from 'node:path';
import { generateEndpoints } from '../src';

const tmpDir = path.resolve(__dirname, 'tmp');
Expand Down Expand Up @@ -379,7 +379,7 @@ describe('openapi spec', () => {
unionUndefined: true,
schemaFile: './fixtures/readOnlyWriteOnly.yaml',
apiFile: './fixtures/emptyApi.ts',
mergeReadWriteOnly: true
mergeReadWriteOnly: true,
});
expect(api).toMatchSnapshot();
});
Expand Down

0 comments on commit ea195e7

Please sign in to comment.