Skip to content

Templates implementation #1

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 4 commits into from
Nov 25, 2020
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
2 changes: 1 addition & 1 deletion .prettierrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "avoid",
"printWidth": 200,
"printWidth": 120,
"tabWidth": 4
}
2 changes: 2 additions & 0 deletions bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ program
.requiredOption('-i, --input <value>', 'OpenAPI specification, can be a path, url or string content (required)')
.requiredOption('-o, --output <value>', 'Output directory (required)')
.option('-c, --client <value>', 'HTTP client to generate [fetch, xhr, node]', 'fetch')
.option('-t --templates <value>', 'Path to custom templates directory')
.option('--useOptions', 'Use options instead of arguments')
.option('--useUnionTypes', 'Use union types instead of enums')
.option('--exportCore <value>', 'Write core files to disk', true)
Expand All @@ -34,6 +35,7 @@ if (OpenAPI) {
exportServices: JSON.parse(program.exportServices) === true,
exportModels: JSON.parse(program.exportModels) === true,
exportSchemas: JSON.parse(program.exportSchemas) === true,
customTemplatesPath: program.templates,
})
.then(() => {
process.exit(0);
Expand Down
16 changes: 9 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
{
"name": "openapi-typescript-codegen",
"name": "dh-api-client-codegen",
"version": "0.5.4",
"description": "NodeJS library that generates Typescript or Javascript clients based on the OpenAPI specification.",
"author": "Ferdi Koomen",
"homepage": "https://github.com/ferdikoomen/openapi-typescript-codegen",
"author": "DoclerLabs",
"homepage": "https://github.com/DoclerLabs/openapi-typescript-codegen",
"repository": {
"type": "git",
"url": "git+https://github.com/ferdikoomen/openapi-typescript-codegen.git"
"url": "git+https://github.com/DoclerLabs/openapi-typescript-codegen.git"
},
"bugs": {
"url": "https://github.com/ferdikoomen/openapi-typescript-codegen/issues"
"url": "https://github.com/DoclerLabs/openapi-typescript-codegen/issues"
},
"license": "MIT",
"keywords": [
Expand All @@ -28,8 +28,8 @@
],
"maintainers": [
{
"name": "Ferdi Koomen",
"email": "info@madebyferdi.com"
"name": "DoclerLabs",
"email": "info@DoclerLabs.com"
}
],
"main": "dist/index.js",
Expand Down Expand Up @@ -64,6 +64,7 @@
"dependencies": {
"camelcase": "6.1.0",
"commander": "6.2.0",
"fs-extra": "^9.0.1",
"handlebars": "4.7.6",
"js-yaml": "3.14.0",
"mkdirp": "1.0.4",
Expand Down Expand Up @@ -98,6 +99,7 @@
"prettier": "2.1.2",
"puppeteer": "5.4.1",
"rollup": "2.32.1",
"rollup-plugin-copy": "^3.3.0",
"rollup-plugin-terser": "7.0.2",
"rollup-plugin-typescript2": "0.28.0",
"typescript": "4.0.5"
Expand Down
20 changes: 7 additions & 13 deletions rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

const copy = require('rollup-plugin-copy');
const commonjs = require('@rollup/plugin-commonjs');
const { nodeResolve } = require('@rollup/plugin-node-resolve');
const { terser } = require('rollup-plugin-terser');
Expand All @@ -23,7 +24,7 @@ const handlebarsPlugin = () => ({
}
return null;
},
load: (file) => {
load: file => {
if (path.extname(file) === '.hbs') {
const template = fs.readFileSync(file, 'utf8').toString().trim();
const templateSpec = handlebars.precompile(template, {
Expand All @@ -39,7 +40,7 @@ const handlebarsPlugin = () => ({
return `export default ${templateSpec};`;
}
return null;
}
},
});

const getPlugins = () => {
Expand All @@ -48,27 +49,20 @@ const getPlugins = () => {
typescript(),
nodeResolve(),
commonjs(),
]
copy({ targets: [{ src: 'src/templates/', dest: 'dist' }] }),
];
if (process.env.NODE_ENV === 'development') {
return plugins;
}
return [...plugins, terser()];
}
};

module.exports = {
input: './src/index.ts',
output: {
file: './dist/index.js',
format: 'cjs',
},
external: [
'fs',
'os',
'util',
'http',
'https',
'handlebars/runtime',
...external,
],
external: ['fs', 'os', 'util', 'http', 'https', 'handlebars/runtime', ...external],
plugins: getPlugins(),
};
19 changes: 19 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import * as fse from 'fs-extra';
import * as path from 'path';
import * as OpenAPI from './index';

beforeAll(() => {
fse.symlinkSync(path.resolve(__dirname, 'templates'), path.resolve(__dirname, 'utils/templates'), 'dir');
});

afterAll(() => {
fse.unlinkSync(path.resolve(__dirname, 'utils/templates'));
});

describe('index', () => {
it('parses v2 without issues', async () => {
await OpenAPI.generate({
Expand Down Expand Up @@ -32,4 +42,13 @@ describe('index', () => {
write: false,
});
});

it('apply templates customisation without issues', async () => {
await OpenAPI.generate({
input: './test/spec/v3.json',
output: './generated/v3/',
customTemplatesPath: './test/templates',
write: false,
});
});
});
31 changes: 28 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface Options {
exportModels?: boolean;
exportSchemas?: boolean;
write?: boolean;
customTemplatesPath?: string;
}

/**
Expand All @@ -40,6 +41,7 @@ export interface Options {
* @param exportModels: Generate models
* @param exportSchemas: Generate schemas
* @param write Write the files to disk (true or false)
* @param customTemplatesPath: Provide custom templates to override default set
*/
export async function generate({
input,
Expand All @@ -52,25 +54,48 @@ export async function generate({
exportModels = true,
exportSchemas = false,
write = true,
customTemplatesPath,
}: Options): Promise<void> {
const openApi = isString(input) ? await getOpenApiSpec(input) : input;
const openApiVersion = getOpenApiVersion(openApi);
const templates = registerHandlebarTemplates();
const templates = registerHandlebarTemplates(customTemplatesPath);

switch (openApiVersion) {
case OpenApiVersion.V2: {
const client = parseV2(openApi);
const clientFinal = postProcessClient(client);
if (!write) break;
await writeClient(clientFinal, templates, output, httpClient, useOptions, useUnionTypes, exportCore, exportServices, exportModels, exportSchemas);
await writeClient(
clientFinal,
templates,
output,
httpClient,
useOptions,
useUnionTypes,
exportCore,
exportServices,
exportModels,
exportSchemas
);
break;
}

case OpenApiVersion.V3: {
const client = parseV3(openApi);
const clientFinal = postProcessClient(client);
if (!write) break;
await writeClient(clientFinal, templates, output, httpClient, useOptions, useUnionTypes, exportCore, exportServices, exportModels, exportSchemas);
await writeClient(
clientFinal,
templates,
output,
httpClient,
useOptions,
useUnionTypes,
exportCore,
exportServices,
exportModels,
exportSchemas
);
break;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/registerHandlebarHelpers.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as Handlebars from 'handlebars/runtime';
import * as Handlebars from 'handlebars';

import { registerHandlebarHelpers } from './registerHandlebarHelpers';

Expand Down
2 changes: 1 addition & 1 deletion src/utils/registerHandlebarHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-nocheck

import * as Handlebars from 'handlebars/runtime';
import * as Handlebars from 'handlebars';

export function registerHandlebarHelpers(): void {
Handlebars.registerHelper('equals', function (a: string, b: string, options: Handlebars.HelperOptions): string {
Expand Down
66 changes: 66 additions & 0 deletions src/utils/registerHandlebarPartials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import * as Handlebars from 'handlebars';
import { resolveHandlebarTemplate } from './resolveHandlebarTemplate';

export const registerHandlebarPartials = () => {
// Partials for the generations of the models, services, etc.
Handlebars.registerPartial('exportEnum', resolveHandlebarTemplate('partials/exportEnum'));
Handlebars.registerPartial('exportInterface', resolveHandlebarTemplate('partials/exportInterface'));
Handlebars.registerPartial('exportType', resolveHandlebarTemplate('partials/exportType'));
Handlebars.registerPartial('extends', resolveHandlebarTemplate('partials/extends'));
Handlebars.registerPartial('header', resolveHandlebarTemplate('partials/header'));
Handlebars.registerPartial('isNullable', resolveHandlebarTemplate('partials/isNullable'));
Handlebars.registerPartial('isReadOnly', resolveHandlebarTemplate('partials/isReadOnly'));
Handlebars.registerPartial('isRequired', resolveHandlebarTemplate('partials/isRequired'));
Handlebars.registerPartial('parameters', resolveHandlebarTemplate('partials/parameters'));
Handlebars.registerPartial('result', resolveHandlebarTemplate('partials/result'));
Handlebars.registerPartial('schema', resolveHandlebarTemplate('partials/schema'));
Handlebars.registerPartial('schemaArray', resolveHandlebarTemplate('partials/schemaArray'));
Handlebars.registerPartial('schemaDictionary', resolveHandlebarTemplate('partials/schemaDictionary'));
Handlebars.registerPartial('schemaEnum', resolveHandlebarTemplate('partials/schemaEnum'));
Handlebars.registerPartial('schemaGeneric', resolveHandlebarTemplate('partials/schemaGeneric'));
Handlebars.registerPartial('schemaInterface', resolveHandlebarTemplate('partials/schemaInterface'));
Handlebars.registerPartial('type', resolveHandlebarTemplate('partials/type'));
Handlebars.registerPartial('typeArray', resolveHandlebarTemplate('partials/typeArray'));
Handlebars.registerPartial('typeDictionary', resolveHandlebarTemplate('partials/typeDictionary'));
Handlebars.registerPartial('typeEnum', resolveHandlebarTemplate('partials/typeEnum'));
Handlebars.registerPartial('typeGeneric', resolveHandlebarTemplate('partials/typeGeneric'));
Handlebars.registerPartial('typeInterface', resolveHandlebarTemplate('partials/typeInterface'));
Handlebars.registerPartial('typeReference', resolveHandlebarTemplate('partials/typeReference'));
Handlebars.registerPartial('base', resolveHandlebarTemplate('partials/base'));

// Generic functions used in 'request' file @see src/templates/core/request.hbs for more info
Handlebars.registerPartial('functions/catchErrors', resolveHandlebarTemplate('core/functions/catchErrors'));
Handlebars.registerPartial('functions/getFormData', resolveHandlebarTemplate('core/functions/getFormData'));
Handlebars.registerPartial('functions/getToken', resolveHandlebarTemplate('core/functions/getToken'));
Handlebars.registerPartial('functions/getQueryString', resolveHandlebarTemplate('core/functions/getQueryString'));
Handlebars.registerPartial('functions/getUrl', resolveHandlebarTemplate('core/functions/getUrl'));
Handlebars.registerPartial('functions/isBinary', resolveHandlebarTemplate('core/functions/isBinary'));
Handlebars.registerPartial('functions/isBlob', resolveHandlebarTemplate('core/functions/isBlob'));
Handlebars.registerPartial('functions/isDefined', resolveHandlebarTemplate('core/functions/isDefined'));
Handlebars.registerPartial('functions/isString', resolveHandlebarTemplate('core/functions/isString'));
Handlebars.registerPartial('functions/isSuccess', resolveHandlebarTemplate('core/functions/isSuccess'));

// Specific files for the fetch client implementation
Handlebars.registerPartial('fetch/getHeaders', resolveHandlebarTemplate('core/fetch/getHeaders'));
Handlebars.registerPartial('fetch/getRequestBody', resolveHandlebarTemplate('core/fetch/getRequestBody'));
Handlebars.registerPartial('fetch/getResponseBody', resolveHandlebarTemplate('core/fetch/getResponseBody'));
Handlebars.registerPartial('fetch/getResponseHeader', resolveHandlebarTemplate('core/fetch/getResponseHeader'));
Handlebars.registerPartial('fetch/sendRequest', resolveHandlebarTemplate('core/fetch/sendRequest'));
Handlebars.registerPartial('fetch/request', resolveHandlebarTemplate('core/fetch/request'));

// Specific files for the xhr client implementation
Handlebars.registerPartial('xhr/getHeaders', resolveHandlebarTemplate('core/xhr/getHeaders'));
Handlebars.registerPartial('xhr/getRequestBody', resolveHandlebarTemplate('core/xhr/getRequestBody'));
Handlebars.registerPartial('xhr/getResponseBody', resolveHandlebarTemplate('core/xhr/getResponseBody'));
Handlebars.registerPartial('xhr/getResponseHeader', resolveHandlebarTemplate('core/xhr/getResponseHeader'));
Handlebars.registerPartial('xhr/sendRequest', resolveHandlebarTemplate('core/xhr/sendRequest'));
Handlebars.registerPartial('xhr/request', resolveHandlebarTemplate('core/xhr/request'));

// Specific files for the node client implementation
Handlebars.registerPartial('node/getHeaders', resolveHandlebarTemplate('core/node/getHeaders'));
Handlebars.registerPartial('node/getRequestBody', resolveHandlebarTemplate('core/node/getRequestBody'));
Handlebars.registerPartial('node/getResponseBody', resolveHandlebarTemplate('core/node/getResponseBody'));
Handlebars.registerPartial('node/getResponseHeader', resolveHandlebarTemplate('core/node/getResponseHeader'));
Handlebars.registerPartial('node/sendRequest', resolveHandlebarTemplate('core/node/sendRequest'));
Handlebars.registerPartial('node/request', resolveHandlebarTemplate('core/node/request'));
};
Loading