Skip to content

Commit

Permalink
fix(api): improve identifiers generation
Browse files Browse the repository at this point in the history
Takes in count numbers in identifiers for a better rendering.

BREAKING CHANGE: Some identifiers could change, requiring to update them in your code.
  • Loading branch information
nfroidure committed Jul 18, 2024
1 parent 4b006c6 commit cc91507
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
56 changes: 56 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,62 @@ describe('generateJSONSchemaTypes()', () => {
});
});

test('should work with enums having values starting with a number', async () => {
const schema: JSONSchema7 = {
title: 'Limit',
type: 'string',
enum: ['1m', '1d', '1w'],
};

expect(
toSource(
await generateJSONSchemaTypes(schema, {
brandedTypes: [],
generateRealEnums: true,
tuplesFromFixedArraysLengthLimit: 5,
exportNamespaces: true,
}),
),
).toMatchInlineSnapshot(`
"export type Main = Enums.Limit;
export namespace Enums {
export enum Limit {
_0M = "1m",
_0D = "1d",
_0W = "1w"
}
}"
`);
});

test('should camelize number separated identifiers', async () => {
const schema: JSONSchema7 = {
title: 'Limit',
type: 'string',
enum: ['user1name', 'user_2_name', 'user3_name'],
};

expect(
toSource(
await generateJSONSchemaTypes(schema, {
brandedTypes: [],
generateRealEnums: true,
tuplesFromFixedArraysLengthLimit: 5,
exportNamespaces: true,
}),
),
).toMatchInlineSnapshot(`
"export type Main = Enums.Limit;
export namespace Enums {
export enum Limit {
User1Name = "user1name",
User2Name = "user_2_name",
User3Name = "user3_name"
}
}"
`);
});

test('should work with string literal enums', async () => {
const schema: JSONSchema7 = {
title: 'Limit',
Expand Down
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,12 @@ export function buildIdentifier(part: string): string {
.replace(/(?:^|[^a-z0-9]+)([a-z])/gi, (_: unknown, $1: string) =>
$1.toUpperCase(),
)
.replace(/[^a-z0-9]/gi, '');
.replace(
/([^a-z]+)([a-z])/gi,
(_: unknown, $1: string, $2: string) => $1 + $2.toUpperCase(),
)
.replace(/[^a-z0-9]/gi, '')
.replace(/^[0-9]/, (_: unknown, $1: string) => '_' + $1);

return identifier || 'Unknown';
}
Expand Down

0 comments on commit cc91507

Please sign in to comment.