Skip to content

Commit

Permalink
fix: escape non-identifier keys in generated interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
adelsz committed Sep 26, 2023
1 parent b9a2b98 commit f9704e0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
16 changes: 16 additions & 0 deletions packages/cli/src/generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,22 @@ test('comment escaping', () => {
);
});

test('interface generation with escaped keys', () => {
const expected = `export interface ExplainResult {
"QUERY PLAN": string;
}
`;
const fields = [
{
fieldName: 'QUERY PLAN',
fieldType: 'string',
},
];
const result = generateInterface('ExplainResult', fields);
expect(result).toEqual(expected);
});

test('interface generation', () => {
const expected = `export interface User {
age: number;
Expand Down
23 changes: 18 additions & 5 deletions packages/cli/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,29 @@ export function escapeComment(comment: string) {
return comment.replace(/\*\//g, '*\\/');
}

/** Escape a key if it isn't an identifier literal */
export function escapeKey(key: string) {
if (/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(key)) {
return key;
}
return `"${key}"`;
}

export const generateInterface = (interfaceName: string, fields: IField[]) => {
const sortedFields = fields
.slice()
.sort((a, b) => a.fieldName.localeCompare(b.fieldName));
const contents = sortedFields
.map(
({ fieldName, fieldType, comment, optional }) =>
(comment ? ` /** ${escapeComment(comment)} */\n` : '') +
` ${fieldName}${optional ? '?' : ''}: ${fieldType};`,
)
.map(({ fieldName, fieldType, comment, optional }) => {
const lines = [];
if (comment) {
lines.push(` /** ${escapeComment(comment)} */`);
}
const keySuffix = optional ? '?' : '';
const entryLine = ` ${escapeKey(fieldName)}${keySuffix}: ${fieldType};`;
lines.push(entryLine);
return lines.join('\n');
})
.join('\n');
return interfaceGen(interfaceName, contents);
};
Expand Down

0 comments on commit f9704e0

Please sign in to comment.