Skip to content

Commit

Permalink
fix: Single API export, parameter (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
ffflorian committed May 10, 2019
1 parent 89ef8d7 commit 105196c
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 29 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ swaxios -i ./path/to/swagger.json -o ./path/to/output/directory

```ts
import axios, {AxiosInstance, AxiosRequestConfig} from 'axios';
import {IdentityProvidersService} from './identity-providers/IdentityProvidersService';
import {FinalizeLoginService} from './sso/FinalizeLoginService';
import {IdentityProvidersService} from './identity-providers/';
import {FinalizeLoginService} from './sso/';

export class APIClient {
private readonly httpClient: AxiosInstance;
Expand Down
10 changes: 4 additions & 6 deletions src/generators/APIClientGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ export class APIClientGenerator extends TemplateGenerator {
const api: API = {};

for (const fileName of Object.keys(fileIndex.files)) {
const apiName = StringUtil.camelize(fileName);
api[apiName] = `new ${apiName}(this.httpClient)`;
const objectName = `${fileName.charAt(0).toLowerCase()}${fileName.slice(1)}`;
api[objectName] = `new ${fileName}(this.httpClient)`;
}

for (let [directoryName, directory] of Object.entries(fileIndex.directories)) {
Expand Down Expand Up @@ -76,11 +76,9 @@ export class APIClientGenerator extends TemplateGenerator {
}

protected async getContext() {
const fileIndex = this.fileIndex;

const API = await this.generateAPI(fileIndex);
const API = await this.generateAPI(this.fileIndex.directories.api);
const apiString = inspect(API, {breakLength: Infinity}).replace(/'/gm, '');
const imports = this.generateImports(fileIndex);
const imports = this.generateImports(this.fileIndex);

return {
API: apiString,
Expand Down
24 changes: 14 additions & 10 deletions src/generators/MethodGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,29 @@ import {inspect} from 'util';
import * as StringUtil from '../util/StringUtil';

export class MethodGenerator {
private readonly parameterName?: string;
private readonly responses: Record<string, Response>;
private readonly spec: Spec;
private readonly url: string;
readonly formattedUrl: string;
readonly method: string;
readonly normalizedUrl: string;
readonly parameterData?: string;
readonly parameterMethod: string;
readonly parameterName?: string;
readonly returnType: string;

constructor(url: string, method: string, responses: Record<string, Response>, spec: Spec) {
this.url = url;
this.normalizedUrl = StringUtil.normalizeUrl(url);
this.formattedUrl = `'${url}'`;
this.spec = spec;
this.responses = responses;

const parameterMatch = url.match(/\{([^}]+)\}$/);

if (parameterMatch) {
this.parameterName = parameterMatch[1];
this.parameterData = `{data: ${this.parameterName}}`;
this.formattedUrl = this.formattedUrl.replace(/\{/g, '${').replace(/'/g, '`');
}

const postFix = parameterMatch ? `By${StringUtil.camelCase(parameterMatch.splice(1), true)}` : 'All';
Expand All @@ -38,7 +40,7 @@ export class MethodGenerator {
this.method = method;
}

private buildType(schema: Schema): string {
private buildType(schema: Schema, schemaName: string): string {
const emptyObject = '{}';

let {required, properties, type} = schema;
Expand Down Expand Up @@ -66,15 +68,15 @@ export class MethodGenerator {
}
case 'object': {
if (!properties) {
console.info('Schema definition is "object" but has no properties.');
console.info(`Schema type for "${schemaName}" is "object" but has no properties.`);
return emptyObject;
}

const schema: Record<string, string> = {};

for (const property of Object.keys(properties)) {
const propertyName = required && !required.includes(property) ? `${property}?` : property;
schema[propertyName] = this.buildType(properties[property]);
schema[propertyName] = this.buildType(properties[property], property);
}

return inspect(schema, {breakLength: Infinity})
Expand All @@ -84,15 +86,15 @@ export class MethodGenerator {
}
case 'array': {
if (!schema.items) {
console.info('Schema definition is "array" but has no items.');
console.info(`Schema type for "${schemaName}" is "array" but has no items.`);
return 'any[]';
}

if (!(schema.items instanceof Array)) {
return this.buildType(schema.items);
return this.buildType(schema.items, schemaName);
}

const schemes = schema.items.map(itemSchema => this.buildType(itemSchema)).join('|');
const schemes = schema.items.map(itemSchema => this.buildType(itemSchema, schemaName)).join('|');
return `Array<${schemes}>`;
}
default: {
Expand All @@ -106,8 +108,10 @@ export class MethodGenerator {
const response200 = this.responses['200'];
const response201 = this.responses['201'];

const response200Schema = response200 && response200.schema ? this.buildType(response200.schema) : '';
const response201Schema = response201 && response201.schema ? this.buildType(response201.schema) : '';
const response200Schema =
response200 && response200.schema ? this.buildType(response200.schema, 'response200') : '';
const response201Schema =
response201 && response201.schema ? this.buildType(response201.schema, 'response200') : '';

const responseSchema =
response200Schema && response201Schema
Expand Down
4 changes: 2 additions & 2 deletions src/templates/APIClient.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
{{#each this.files}}
{{{this}}},
{{/each}}
} from './{{{this.dir}}}';
} from './{{{this.dir}}}/';
{{/each}}

export class APIClient {
Expand All @@ -20,7 +20,7 @@ export class APIClient {
this.httpClient = axios.create(configOrBaseURL);
}

get API() {
get api() {
return {{{API}}};
}

Expand Down
8 changes: 2 additions & 6 deletions src/templates/Resource.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,10 @@ export class {{{name}}} {
(
{{#if this.parameterName}}{{{this.parameterName}}}: string{{/if}}
): Promise<{{{this.returnType}}}> {

const resource = '{{{this.normalizedUrl}}}';
const resource = {{{this.formattedUrl}}};
const response = await this.apiClient.{{{this.method}}}
{{#isnt this.returnType "void"}}<{{{this.returnType}}}>{{/isnt}}
(
resource
{{#if this.parameterName}}, {{{this.parameterData}}}{{/if}}
);
(resource);
return response.data;
}
{{/each}}
Expand Down
6 changes: 3 additions & 3 deletions src/util/StringUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ export function pascalCase(words: string[]): string {
return camelCase(words, true);
}

export function camelize(resourceName: string): string {
return pascalCase(resourceName.split('-'));
export function camelize(resourceName: string, isPascalCase = false): string {
return camelCase(resourceName.split('-'), isPascalCase);
}

export function generateServiceName(url: string): string {
Expand All @@ -37,7 +37,7 @@ export function generateServiceName(url: string): string {
const lastUrlPart = urlParts[urlParts.length - 1];
const resourceName = lastUrlPart ? lastUrlPart : 'Root';

return camelize(`${resourceName}-service`);
return camelize(`${resourceName}-service`, true);
}

export function normalizeUrl(url: string): string {
Expand Down

0 comments on commit 105196c

Please sign in to comment.