Skip to content

Commit

Permalink
fix: handle enum names (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
akashrpo authored Dec 13, 2024
1 parent 921f5e4 commit 6ef8b8f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
9 changes: 5 additions & 4 deletions src/generators/android/android.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +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';

// These contexts are what will be passed to Handlebars to perform rendering.
// Everything in these contexts should be properly sanitized.
Expand Down Expand Up @@ -164,13 +165,13 @@ const convertToEnum = (values: any[], type: string) => {
let key, formattedValue;

if (type === 'String' || typeof value === 'string') {
key = 'S_' + value.toString().trim().toUpperCase().replace(/ /g, '');
key = 'S_' + sanitizeKey(value);
formattedValue = `"${value.toString().trim()}"`; // String values
} else if (type === 'Long') {
key = 'L_' + value.toString();
formattedValue = `${value}L`; // Long values
key = 'L_' + sanitizeKey(value);
formattedValue = Number(value) % 1 === 0 ? `${value}L` : value.toString(); // Long values
} else if (type === 'Double') {
key = 'D_' + value.toString().replace('.', '_');
key = 'D_' + sanitizeKey(value);
formattedValue = `${value}D`; // Double values
}

Expand Down
5 changes: 3 additions & 2 deletions src/generators/javascript/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +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';

const { camelCase, upperFirst } = lodash;

Expand Down Expand Up @@ -213,10 +214,10 @@ const convertToEnum = (values: any[], type: string) => {
let key, formattedValue;

if (type === 'string' || typeof value === 'string') {
key = 'S_' + value.toString().trim().toUpperCase().replace(/ /g, '_');
key = 'S_' + sanitizeKey(value);
formattedValue = `'${value.toString().trim()}'`;
} else if (type === 'number') {
key = 'N_' + value.toString().replace('.', '_');
key = 'N_' + sanitizeKey(value);
formattedValue = `${value}`;
}

Expand Down
7 changes: 7 additions & 0 deletions src/generators/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const sanitizeKey = (value: any) =>
value
.toString()
.trim()
.toUpperCase()
.replace(/[^a-zA-Z0-9_]+|^_+|_+$/g, '_')
.replace(/_+/g, '_');

0 comments on commit 6ef8b8f

Please sign in to comment.