Skip to content

Commit ea195e7

Browse files
committed
Replace inline require with dynamic import
1 parent 6466cc2 commit ea195e7

File tree

5 files changed

+80
-81
lines changed

5 files changed

+80
-81
lines changed

packages/rtk-query-codegen-openapi/src/bin/cli.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
#!/usr/bin/env node
22

3-
import { dirname, resolve } from 'path';
4-
import { generateEndpoints, parseConfig } from '../';
5-
63
import program from 'commander';
4+
import { dirname, resolve } from 'node:path';
5+
import { generateEndpoints, parseConfig } from '../';
76

87
let ts = false;
98
try {

packages/rtk-query-codegen-openapi/src/generate.ts

Lines changed: 61 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,25 @@
1-
import * as path from 'path';
2-
1+
import { camelCase } from 'lodash';
2+
import path from 'node:path';
33
import ApiGenerator, {
44
getOperationName as _getOperationName,
55
getReferenceName,
66
isReference,
77
supportDeepObjects,
88
} from 'oazapfts/lib/codegen/generate';
9-
import type { EndpointMatcher, EndpointOverrides, GenerationOptions, OperationDefinition, TextMatcher } from './types';
10-
import { capitalize, getOperationDefinitions, getV3Doc, removeUndefined, isQuery as testIsQuery } from './utils';
119
import {
1210
createPropertyAssignment,
1311
createQuestionToken,
1412
isValidIdentifier,
1513
keywordType,
1614
} from 'oazapfts/lib/codegen/tscodegen';
17-
import { generateCreateApiCall, generateEndpointDefinition, generateImportNode, generateTagTypes } from './codegen';
18-
19-
import type { ObjectPropertyDefinitions } from './codegen';
2015
import type { OpenAPIV3 } from 'openapi-types';
21-
import { camelCase } from 'lodash';
22-
import { factory } from './utils/factory';
23-
import { generateReactHooks } from './generators/react-hooks';
2416
import ts from 'typescript';
17+
import type { ObjectPropertyDefinitions } from './codegen';
18+
import { generateCreateApiCall, generateEndpointDefinition, generateImportNode, generateTagTypes } from './codegen';
19+
import { generateReactHooks } from './generators/react-hooks';
20+
import type { EndpointMatcher, EndpointOverrides, GenerationOptions, OperationDefinition, TextMatcher } from './types';
21+
import { capitalize, getOperationDefinitions, getV3Doc, removeUndefined, isQuery as testIsQuery } from './utils';
22+
import { factory } from './utils/factory';
2523

2624
const generatedApiName = 'injectedRtkApi';
2725

@@ -175,13 +173,13 @@ export async function generateApi(
175173
...apiGen.enumAliases,
176174
...(hooks
177175
? [
178-
generateReactHooks({
179-
exportName: generatedApiName,
180-
operationDefinitions,
181-
endpointOverrides,
182-
config: hooks,
183-
}),
184-
]
176+
generateReactHooks({
177+
exportName: generatedApiName,
178+
operationDefinitions,
179+
endpointOverrides,
180+
config: hooks,
181+
}),
182+
]
185183
: []),
186184
],
187185
factory.createToken(ts.SyntaxKind.EndOfFileToken),
@@ -301,7 +299,9 @@ export async function generateApi(
301299
const body = apiGen.resolve(requestBody);
302300
const schema = apiGen.getSchemaFromContent(body.content);
303301
const type = apiGen.getTypeFromSchema(schema);
304-
const schemaName = camelCase((type as any).name || getReferenceName(schema) || ("title" in schema && schema.title) || 'body');
302+
const schemaName = camelCase(
303+
(type as any).name || getReferenceName(schema) || ('title' in schema && schema.title) || 'body'
304+
);
305305
const name = generateName(schemaName in queryArg ? 'body' : schemaName, 'body');
306306

307307
queryArg[name] = {
@@ -335,19 +335,19 @@ export async function generateApi(
335335
? isFlatArg
336336
? withQueryComment({ ...queryArgValues[0].type }, queryArgValues[0], false)
337337
: factory.createTypeLiteralNode(
338-
queryArgValues.map((def) =>
339-
withQueryComment(
340-
factory.createPropertySignature(
341-
undefined,
342-
propertyName(def.name),
343-
createQuestionToken(!def.required),
344-
def.type
345-
),
346-
def,
347-
true
338+
queryArgValues.map((def) =>
339+
withQueryComment(
340+
factory.createPropertySignature(
341+
undefined,
342+
propertyName(def.name),
343+
createQuestionToken(!def.required),
344+
def.type
345+
),
346+
def,
347+
true
348+
)
348349
)
349350
)
350-
)
351351
: factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword)
352352
)
353353
).name
@@ -391,18 +391,18 @@ export async function generateApi(
391391
return parameters.length === 0
392392
? undefined
393393
: factory.createPropertyAssignment(
394-
factory.createIdentifier(propertyName),
395-
factory.createObjectLiteralExpression(
396-
parameters.map(
397-
(param) =>
398-
createPropertyAssignment(
399-
param.originalName,
400-
isFlatArg ? rootObject : accessProperty(rootObject, param.name)
401-
),
402-
true
394+
factory.createIdentifier(propertyName),
395+
factory.createObjectLiteralExpression(
396+
parameters.map(
397+
(param) =>
398+
createPropertyAssignment(
399+
param.originalName,
400+
isFlatArg ? rootObject : accessProperty(rootObject, param.name)
401+
),
402+
true
403+
)
403404
)
404-
)
405-
);
405+
);
406406
}
407407

408408
return factory.createArrowFunction(
@@ -423,17 +423,17 @@ export async function generateApi(
423423
isQuery && verb.toUpperCase() === 'GET'
424424
? undefined
425425
: factory.createPropertyAssignment(
426-
factory.createIdentifier('method'),
427-
factory.createStringLiteral(verb.toUpperCase())
428-
),
426+
factory.createIdentifier('method'),
427+
factory.createStringLiteral(verb.toUpperCase())
428+
),
429429
bodyParameter === undefined
430430
? undefined
431431
: factory.createPropertyAssignment(
432-
factory.createIdentifier('body'),
433-
isFlatArg
434-
? rootObject
435-
: factory.createPropertyAccessExpression(rootObject, factory.createIdentifier(bodyParameter.name))
436-
),
432+
factory.createIdentifier('body'),
433+
isFlatArg
434+
? rootObject
435+
: factory.createPropertyAccessExpression(rootObject, factory.createIdentifier(bodyParameter.name))
436+
),
437437
createObjectLiteralProperty(pickParams('cookie'), 'cookies'),
438438
createObjectLiteralProperty(pickParams('header'), 'headers'),
439439
createObjectLiteralProperty(pickParams('query'), 'params'),
@@ -445,12 +445,12 @@ export async function generateApi(
445445
}
446446

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

452452
// eslint-disable-next-line no-empty-pattern
453-
function generateMutationEndpointProps({ }: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions {
453+
function generateMutationEndpointProps({}: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions {
454454
return {}; /* TODO needs implementation - skip for now */
455455
}
456456
}
@@ -480,16 +480,16 @@ function generatePathExpression(
480480

481481
return expressions.length
482482
? factory.createTemplateExpression(
483-
factory.createTemplateHead(head),
484-
expressions.map(([prop, literal], index) =>
485-
factory.createTemplateSpan(
486-
isFlatArg ? rootObject : accessProperty(rootObject, prop),
487-
index === expressions.length - 1
488-
? factory.createTemplateTail(literal)
489-
: factory.createTemplateMiddle(literal)
483+
factory.createTemplateHead(head),
484+
expressions.map(([prop, literal], index) =>
485+
factory.createTemplateSpan(
486+
isFlatArg ? rootObject : accessProperty(rootObject, prop),
487+
index === expressions.length - 1
488+
? factory.createTemplateTail(literal)
489+
: factory.createTemplateMiddle(literal)
490+
)
490491
)
491492
)
492-
)
493493
: factory.createNoSubstitutionTemplateLiteral(head);
494494
}
495495

@@ -500,13 +500,13 @@ type QueryArgDefinition = {
500500
required?: boolean;
501501
param?: OpenAPIV3.ParameterObject;
502502
} & (
503-
| {
503+
| {
504504
origin: 'param';
505505
param: OpenAPIV3.ParameterObject;
506506
}
507-
| {
507+
| {
508508
origin: 'body';
509509
body: OpenAPIV3.RequestBodyObject;
510510
}
511-
);
511+
);
512512
type QueryArgDefinitions = Record<string, QueryArgDefinition>;

packages/rtk-query-codegen-openapi/src/index.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import path from 'path';
2-
import fs from 'fs';
1+
import fs from 'node:fs';
2+
import path from 'node:path';
33
import type { CommonOptions, ConfigFile, GenerationOptions, OutputFileOptions } from './types';
44
import { isValidUrl, prettify } from './utils';
55
export type { ConfigFile } from './types';
@@ -11,11 +11,11 @@ export async function generateEndpoints(options: GenerationOptions): Promise<str
1111
? options.schemaFile
1212
: path.resolve(process.cwd(), schemaLocation);
1313

14-
const sourceCode = await enforceOazapftsTsVersion(() => {
15-
const { generateApi } = require('./generate');
14+
const sourceCode = await enforceOazapftsTsVersion(async () => {
15+
const { generateApi } = await import('./generate');
1616
return generateApi(schemaAbsPath, options);
1717
});
18-
const outputFile = options.outputFile;
18+
const { outputFile } = options;
1919
if (outputFile) {
2020
fs.writeFileSync(path.resolve(process.cwd(), outputFile), await prettify(outputFile, sourceCode));
2121
} else {

packages/rtk-query-codegen-openapi/test/cli.test.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import type { ExecException } from 'child_process';
2-
import { exec } from 'child_process';
3-
import * as fs from 'fs';
4-
import path from 'path';
51
import del from 'del';
2+
import type { ExecException } from 'node:child_process';
3+
import { exec } from 'node:child_process';
4+
import fs from 'node:fs';
5+
import path from 'node:path';
66

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

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

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

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

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

7171
expect(fromTs).toEqual(fromJs);
7272
expect(fromJson).toEqual(fromJs);
73-
}, 120000);
73+
}, 120_000);
7474

7575
test('missing parameters doesnt fail', async () => {
7676
const out = await cli([`./config.invalid-example.json`], __dirname);
7777
expect(out.stderr).toContain("Error: path parameter petId does not seem to be defined in '/pet/{petId}'!");
78-
}, 25000);
78+
}, 25_000);
7979
});

packages/rtk-query-codegen-openapi/test/generateEndpoints.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import del from 'del';
2-
import fs from 'fs';
3-
import path, { resolve } from 'path';
2+
import fs from 'node:fs';
3+
import path, { resolve } from 'node:path';
44
import { generateEndpoints } from '../src';
55

66
const tmpDir = path.resolve(__dirname, 'tmp');
@@ -379,7 +379,7 @@ describe('openapi spec', () => {
379379
unionUndefined: true,
380380
schemaFile: './fixtures/readOnlyWriteOnly.yaml',
381381
apiFile: './fixtures/emptyApi.ts',
382-
mergeReadWriteOnly: true
382+
mergeReadWriteOnly: true,
383383
});
384384
expect(api).toMatchSnapshot();
385385
});

0 commit comments

Comments
 (0)