Skip to content

Fix underscores in interface names #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module.exports = {
plugins: ['@typescript-eslint', 'prettier'],
rules: {
'@typescript-eslint/camelcase': 0, // This is perfectly acceptable
'prettier/prettier': 'error',
},
env: {
jest: true,
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,6 @@
"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"tslib": "^1.10.0",
"typescript": "^3.5.1"
"typescript": "^3.5.3"
}
}
84 changes: 40 additions & 44 deletions src/swagger-2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,8 @@ function capitalize(str: string): string {
}

function camelCase(name: string): string {
return name.replace(
/(-|_|\.|\s)+\w/g,
(letter): string => letter.toUpperCase().replace(/[^0-9a-z]/gi, '')
return name.replace(/(-|_|\.|\s)+\w/g, (letter): string =>
letter.toUpperCase().replace(/[^0-9a-z]/gi, '')
);
}

Expand Down Expand Up @@ -68,6 +67,8 @@ function parse(spec: Swagger2, options: Swagger2Options = {}): string {
function getType(definition: Swagger2Definition, nestedName: string): string {
const { $ref, items, type, ...value } = definition;

const nextInterface = camelCase(nestedName); // if this becomes an interface, it’ll need to be camelCased

const DEFAULT_TYPE = 'any';

if ($ref) {
Expand All @@ -90,8 +91,9 @@ function parse(spec: Swagger2, options: Swagger2Options = {}): string {
if (TYPES[items.type]) {
return `${TYPES[items.type]}[]`;
}
queue.push([nestedName, items]);
return `${nestedName}[]`;
// If this is an array of items, let’s add it to the stack for later
queue.push([nextInterface, items]);
return `${nextInterface}[]`;
}

if (Array.isArray(value.oneOf)) {
Expand All @@ -100,8 +102,8 @@ function parse(spec: Swagger2, options: Swagger2Options = {}): string {

if (value.properties) {
// If this is a nested object, let’s add it to the stack for later
queue.push([nestedName, { $ref, items, type, ...value }]);
return nestedName;
queue.push([nextInterface, { $ref, items, type, ...value }]);
return nextInterface;
}

if (type) {
Expand All @@ -121,17 +123,15 @@ function parse(spec: Swagger2, options: Swagger2Options = {}): string {

// Include allOf, if specified
if (Array.isArray(allOf)) {
allOf.forEach(
(item): void => {
// Add “implements“ if this references other items
if (item.$ref) {
const [refName] = getRef(item.$ref);
includes.push(refName);
} else if (item.properties) {
allProperties = { ...allProperties, ...item.properties };
}
allOf.forEach((item): void => {
// Add “implements“ if this references other items
if (item.$ref) {
const [refName] = getRef(item.$ref);
includes.push(refName);
} else if (item.properties) {
allProperties = { ...allProperties, ...item.properties };
}
);
});
}

// If nothing’s here, let’s skip this one.
Expand All @@ -149,28 +149,26 @@ function parse(spec: Swagger2, options: Swagger2Options = {}): string {
output.push(`export interface ${shouldCamelCase ? camelCase(ID) : ID}${isExtending} {`);

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

if (typeof value.description === 'string') {
// Print out descriptions as comments, but only if there’s something there (.*)
output.push(`// ${value.description.replace(/\n$/, '').replace(/\n/g, '\n// ')}`);
}

// Handle enums in the same definition
if (Array.isArray(value.enum)) {
output.push(`${name}: ${value.enum.map(option => JSON.stringify(option)).join(' | ')};`);
return;
}
Object.entries(allProperties).forEach(([key, value]): void => {
const optional = !Array.isArray(required) || required.indexOf(key) === -1;
const formattedKey = shouldCamelCase ? camelCase(key) : key;
const name = `${sanitize(formattedKey)}${optional ? '?' : ''}`;
const newID = `${ID}${capitalize(formattedKey)}`;
const interfaceType = getType(value, newID);

if (typeof value.description === 'string') {
// Print out descriptions as comments, but only if there’s something there (.*)
output.push(`// ${value.description.replace(/\n$/, '').replace(/\n/g, '\n// ')}`);
}

output.push(`${name}: ${interfaceType};`);
// Handle enums in the same definition
if (Array.isArray(value.enum)) {
output.push(`${name}: ${value.enum.map(option => JSON.stringify(option)).join(' | ')};`);
return;
}
);

output.push(`${name}: ${interfaceType};`);
});

if (additionalProperties) {
if ((additionalProperties as boolean) === true) {
Expand All @@ -188,14 +186,12 @@ function parse(spec: Swagger2, options: Swagger2Options = {}): string {
}

// Begin parsing top-level entries
Object.entries(definitions).forEach(
(entry): void => {
// Ignore top-level array definitions
if (entry[1].type === 'object') {
queue.push(entry);
}
Object.entries(definitions).forEach((entry): void => {
// Ignore top-level array definitions
if (entry[1].type === 'object') {
queue.push(entry);
}
);
});
queue.sort((a, b) => a[0].localeCompare(b[0]));
while (queue.length > 0) {
buildNextInterface();
Expand Down
54 changes: 53 additions & 1 deletion tests/swagger-2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ describe('Swagger 2 spec', () => {
expect(swaggerToTS(swagger)).toBe(ts);
});

it('handles arrays of complex items', () => {
it('handles arrays of references', () => {
const swagger: Swagger2 = {
definitions: {
Team: {
Expand Down Expand Up @@ -145,6 +145,58 @@ describe('Swagger 2 spec', () => {
expect(swaggerToTS(swagger)).toBe(ts);
});

it('handles nested objects', () => {
const swagger: Swagger2 = {
definitions: {
User: {
properties: {
remote_id: {
type: 'object',
properties: { id: { type: 'string' } },
},
},
type: 'object',
},
},
};

const ts = format(`
export interface User {
remote_id?: UserRemoteId;
}
export interface UserRemoteId {
id?: string;
}`);

expect(swaggerToTS(swagger)).toBe(ts);
});

it('handles arrays of nested objects', () => {
const swagger: Swagger2 = {
definitions: {
User: {
properties: {
remote_ids: {
type: 'array',
items: { type: 'object', properties: { id: { type: 'string' } } },
},
},
type: 'object',
},
},
};

const ts = format(`
export interface User {
remote_ids?: UserRemoteIds[];
}
export interface UserRemoteIds {
id?: string;
}`);

expect(swaggerToTS(swagger)).toBe(ts);
});

it('handles allOf', () => {
const swagger: Swagger2 = {
definitions: {
Expand Down