Skip to content

Commit

Permalink
fix: sanitize enum key (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
akashrpo authored Dec 20, 2024
1 parent efdc6cd commit 97b1d11
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/generators/android/android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import camelCase from 'lodash/camelCase.js';
import upperFirst from 'lodash/upperFirst.js';
import { Type, Schema, getPropertiesSchema } from '../ast.js';
import { Generator, GeneratorClient } from '../gen.js';
import { sanitizeKey } from '../utils.js';
import { sanitizeEnumKey, sanitizeKey } from '../utils.js';

// These contexts are what will be passed to Handlebars to perform rendering.
// Everything in these contexts should be properly sanitized.
Expand Down Expand Up @@ -195,7 +195,7 @@ function defaultPropertyContext(
hasEnum: !!hasEnum,
enumName: hasEnum
? client.namer.register(schema.name, namespace, {
transform: (name) => upperFirst(camelCase(name)),
transform: (name) => sanitizeEnumKey(camelCase(name)),
})
: undefined,
enumValues: hasEnum && 'enum' in schema ? convertToEnum(schema.enum!, type) : undefined,
Expand Down
4 changes: 2 additions & 2 deletions src/generators/javascript/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Generator, GeneratorClient, type File } from '../gen.js';
import { toTarget, toModule } from './targets.js';
import { registerPartial } from '../../templates.js';
import lodash from 'lodash';
import { sanitizeKey } from '../utils.js';
import { sanitizeEnumKey, sanitizeKey } from '../utils.js';

const { camelCase, upperFirst } = lodash;

Expand Down Expand Up @@ -236,7 +236,7 @@ function conditionallyNullable(
...property,
type: !!schema.isNullable && !hasEnum ? `${property.type} | null` : property.type,
hasEnum: !!hasEnum,
enumName: upperFirst(schema.name),
enumName: sanitizeEnumKey(schema.name),
enumValues:
hasEnum && 'enum' in schema ? convertToEnum(schema.enum!, property.type) : undefined,
};
Expand Down
11 changes: 11 additions & 0 deletions src/generators/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,14 @@ export const sanitizeKey = (value: any) =>
.toUpperCase()
.replace(/[^a-zA-Z0-9_]+|^_+|_+$/g, '_')
.replace(/_+/g, '_');

export const sanitizeEnumKey = (value: string) =>
value
.toString()
.trim()
.replace(/[^a-zA-Z0-9]+/g, '_') // Replace non-alphanumeric characters with '_'
.replace(/_+/g, '_') // Merge consecutive underscores
.replace(/(^_+)|(_+$)/g, '') // Remove leading/trailing underscores
.split('_') // Split by underscores
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) // Capitalize each word
.join(''); // Join words into PascalCase

0 comments on commit 97b1d11

Please sign in to comment.