Skip to content

Commit 64bae78

Browse files
committed
Convert names containing spaces to use underscores
1 parent dcc2cb5 commit 64bae78

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

src/swagger-2.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ function sanitize(name: string): string {
5454
return name.includes('-') ? `'${name}'` : name;
5555
}
5656

57+
function spacesToUnderscores(name: string): string {
58+
return name.replace(/\s/g, '_');
59+
}
60+
5761
function parse(spec: Swagger2, options: Swagger2Options = {}): string {
5862
const shouldUseWrapper = options.wrapper !== false;
5963
const wrapper =
@@ -172,12 +176,12 @@ function parse(spec: Swagger2, options: Swagger2Options = {}): string {
172176
// Open interface
173177
const isExtending = includes.length ? ` extends ${includes.join(', ')}` : '';
174178

175-
output.push(`export interface ${shouldCamelCase ? camelCase(ID) : ID}${isExtending} {`);
179+
output.push(`export interface ${shouldCamelCase ? camelCase(ID) : spacesToUnderscores(ID)}${isExtending} {`);
176180

177181
// Populate interface
178182
Object.entries(allProperties).forEach(([key, value]): void => {
179183
const optional = !Array.isArray(required) || required.indexOf(key) === -1;
180-
const formattedKey = shouldCamelCase ? camelCase(key) : key;
184+
const formattedKey = shouldCamelCase ? camelCase(key) : spacesToUnderscores(key);
181185
const name = `${sanitize(formattedKey)}${optional ? '?' : ''}`;
182186
const newID = `${ID}${capitalize(formattedKey)}`;
183187
const interfaceType = getType(value, newID);

tests/swagger-2.test.ts

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ function format(
1515
): string {
1616
return prettier.format(
1717
`
18-
${injectWarning ? `${warningMessage} \n` : ''}
19-
${wrapper} {
20-
${spec}
18+
${injectWarning ? `${warningMessage} \n` : ''}
19+
${wrapper} {
20+
${spec}
2121
}
2222
`,
2323
{
@@ -384,6 +384,28 @@ describe('Swagger 2 spec', () => {
384384

385385
expect(swaggerToTS(swagger)).toBe(ts);
386386
});
387+
388+
it('converts names with spaces to names with underscores', () => {
389+
const swagger: Swagger2 = {
390+
definitions: {
391+
'User 1': {
392+
properties: {
393+
'profile image': { type: 'string' },
394+
'address line 1': { type: 'string' },
395+
},
396+
type: 'object',
397+
},
398+
},
399+
};
400+
401+
const ts = format(`
402+
export interface User_1 {
403+
'profile_image'?: string;
404+
'address_line_1'?: string;
405+
}`);
406+
407+
expect(swaggerToTS(swagger)).toBe(ts);
408+
});
387409
});
388410

389411
describe('TS features', () => {

0 commit comments

Comments
 (0)