Skip to content
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

add new feature json crud feature #39

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
133 changes: 127 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,19 @@ npm install -g openapi3-generator

Options:

-V, --version output the version number
-o, --output <outputDir> directory where to put the generated files (defaults to current directory)
-t, --templates <templateDir> directory where templates are located (defaults to internal templates directory)
-b, --basedir <baseDir> directory to use as the base when resolving local file references (defaults to OpenAPI file directory)
-h, --help output usage information
-V, --version output the version number
-o, --output <outputDir> directory where to put the generated files (defaults to current directory)
-t, --templates <templateDir> directory where templates are located (defaults to internal templates directory)
-b, --basedir <baseDir> directory to use as the base when resolving local file references (defaults to OpenAPI file directory)
-c, --curl generate a curl scripts (defaults is false)
-s, --skipExistingFiles skip existing files
-d, --deleteFolders <folderName> directory names to be deleted, e.g. "auto", "*"
-h, --help output usage information
```

#### Examples

The shortest possible syntax:
The shortest possible syntax to create markdowns for the openapi.yaml file:
```bash
og openapi.yaml markdown
```
Expand All @@ -44,6 +47,21 @@ Specify where to put the generated code:
og -o ./my-docs openapi.yaml markdown
```

The syntax to create an express server with only the endpoints for the openapi.yaml file:
```bash
og -o ./express-server openapi.yaml express
```

The syntax to create an full functionaly CRUD-Server, which reads and writes from json-files for the openapi.yaml file:
```bash
og -o ./demo-crud-server openapi.yaml json_crud_server
```

The syntax to create an full functionaly CRUD-Server with own templates and deletion of the existing demo-server :
```bash
og -d * -o ./demo-server -t ./ openapi.yaml demo-server-templates
```

## Templates

### Creating your own templates
Expand All @@ -55,6 +73,7 @@ The files in your template can be of the following types:
2. Templates: This kind of files will be compiled using [Handlebars](http://handlebarsjs.com/), and copied to the output directory.
3. Path templates: This kind of files will be compiled using [Handlebars](http://handlebarsjs.com/), but it will generate one file per OpenAPI path.

#### Example 1 - Express server
Assuming we have the following OpenAPI Spec:
```yaml
openapi: "3.0.0"
Expand Down Expand Up @@ -109,6 +128,107 @@ In this example the generated directory structure will be like this:
|+ user/
| - route.js // this file also contains the code for methods on users.
```
#### Example 2 - Json CRUD server
Assuming we have the following OpenAPI Spec:
```yaml
openapi: 3.0.0
info:
title: CRUD Service
version: 1.0.0
description: CRUD Service Example.
servers:
- url: http://localhost:8080/crud-service/rest/v1
...
paths:
...
/variants:
get:...
post:...
/variants/{variantId}:
parameters:
- name: variantId ...
get:...
delete:...
put:...
/variants/{variantId}/phases:
parameters:
- name: variantId ...
get:...
post:...
...
components:
...
schemas:
....
Variant:
description: The variant as it is used in the CRUD service.
type: object
properties:
id:
type: "integer"
format: "int64"
description: The variant's internal ID.
example: 123456
name:
type: "string"
description: The variant's name.
example: "Variant"
creationInfo:
$ref: "#/components/schemas/CreationInfo"
modificationInfo:
$ref: "#/components/schemas/ModificationInfo"
objectVersionInfo:
$ref: "#/components/schemas/ObjectVersionInfo"
required:
- name
....
```
And some template files like this:
```
|+ api/
|- index.js.hbs // This is a static template, it contains placeholders that will be filled in, e.g. includes for each file in routes.
|+ constrains/
|- $$schema$$.constrain.js.hbs // This file will be generated for each schema and contains standard functions to check constrains, each could be change.
|+ data/
|- $$schema$$.data.json.hbs // This json file will be generated for each schema and will be filled with the example values of the schemas.
|+ helpers/
|- errorResponse.js // This file will be static and contains the errorModel.
|- helper.js // This file will be static and contains the helper methods for the crud functionality to read, write and search in json files.
|+ models/
|- $$schema$$.model.js.hbs // This file will be generated for each schema and includes the model for the schema and the mandatory field checks.
|+ routes/
|- $$path$$.route.js.hbs // This file will be generated for each operation and contains skeleton code for each method for an operation.
|+ services/
|- $$path$$.service.js.hbs // This file will be generated for each operation and contains the crud functionality code for each method for an operation.

```
The first important thing to notice here is the variable notation in `$$path$$.route.js.hbs`. It will be replaced by the name of the path.
The second important thing to notice here is the variable notation in `$$schema$$.model.js.hbs`. It will be replaced by the name of the schema.


In this example the generated directory structure will be like this:
```
|+ api/
|- index.js // This file will now e.g. have included the files in routes.
|+ constrains/
|- variants.constrain.js // This file will be used to check additionaly constrains. It can be replaced by a static file with the same name.
...
|+ data/
|- variants.data.json // This json filecontains the example values for the Schama Variant and is used to store new variants and changes.
...
|+ helpers/
|- errorResponse.js // This file contains the errorModel.
|- helper.js // This file contains the helper methods for the crud functionality to read, write and search in json files.
|+ models/
|- variants.model.js // This file contains the model for the schema Variants and the mandatory field checks to create or update a variant.
...
|+ routes/
|- variants.route.js // This file contains the code for methods on variants.
...
|+ services/
|- variants.service.js // This file contains the code for methods on variants to read write the data from variants.datajson.
...
```

### Template file extensions
You can (optionally) name your template files with `.hbs` extensions, which will be removed when writing the generated
Expand Down Expand Up @@ -158,3 +278,4 @@ Check out some examples in the [markdown](./templates/markdown/.partials) templa

* Fran Méndez ([@fmvilas](http://twitter.com/fmvilas))
* Richard Klose ([@richardklose](http://github.com/richardklose))
* Matthias Suessmeier ([@suessmma](https://github.com/suessmma))
55 changes: 51 additions & 4 deletions lib/beautifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const beautifySchema = (schema) => {
return schema;
};

const beautifyOperation = (operation, operationName, pathName, options) => {
const beautifyOperation = (operation, operationName, path, pathName, options) => {
operation.slug = slugg(`op-${operationName}-${pathName}`);
operation.summaryAsHTML = mdToHTML(operation.summary);
operation.descriptionAsHTML = mdToHTML(operation.description);
Expand Down Expand Up @@ -116,6 +116,19 @@ const beautifyOperation = (operation, operationName, pathName, options) => {
});
}

operation.parameters = [];
_.each(path.parameters, param => {
operation.parameters.push(param);
if (param.name.toLowerCase() == path.pathIdParameter) {
operation.idparameter = param.name;
}
});
if(operation.operationId == undefined){
operation.operationId = _.camelCase(`${operationName}${pathName}`);
}
if(path.additionalData != undefined){
operation.additionalData = path.additionalData;
}
return operation;
};

Expand All @@ -128,6 +141,20 @@ const cleanBrackets = text => {
return finalText;
};

/**
* Accommodates Openapi object for additional operation with other objects for easier reading.
*/
const generateAdditionalOperation = (operationName, path, id) => {
const pathLower = path.toLowerCase();
const opertationNameLower = "/" + operationName.toLowerCase();
const idLower = '{' + id.toLowerCase() + '}';
if (!pathLower.endsWith(opertationNameLower) && !pathLower.endsWith(idLower)) {
return path.substring(path.lastIndexOf('/')+1,path.length);
} else {
return null;
}
}

module.exports = (openapi, config) => {
openapi.basePath = openapi.basePath || '';
openapi.info = openapi.info || {};
Expand Down Expand Up @@ -177,16 +204,36 @@ module.exports = (openapi, config) => {

const httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLIK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND'];


pathBasic = pathName === '/' ? 'root' : pathName.split('/')[1];
let pathIdParameter = ''
if (pathBasic.endsWith('s')){
pathIdParameter = _.camelCase(pathBasic.slice(0, -1).concat("Id")).toLowerCase();
}else{
pathIdParameter = _.camelCase(pathBasic.slice(0).concat("Id")).toLowerCase();
}
path.pathIdParameter = pathIdParameter;
const additionalData = generateAdditionalOperation(path.endpointName, pathName, pathIdParameter);
if(additionalData !=null){
path.additionalData = additionalData;
}
_.each(path, (operation, operationName) => {
if (httpMethods.includes(operationName.toUpperCase())) beautifyOperation(operation, operationName, pathName, config);
if (httpMethods.includes(operationName.toUpperCase())) beautifyOperation(operation, operationName, path, pathName, config);
});
});

openapi.endpoints = _.uniq(_.map(openapi.paths, 'endpointName'));

const commonPrefix = sharedStart(Object.keys(openapi.paths));
const levels = commonPrefix.split('/').length - 1;
openapi.__commonPrefix = commonPrefix.split('/').slice(0, levels).join('/');

openapi.__commonPrefix = commonPrefix.split('/').slice(0, levels);
let baseServerPath = '';
if (openapi.servers) {
baseServerPath = openapi.servers[0].url;
baseServerPath = baseServerPath.slice(baseServerPath.indexOf('/', 8), baseServerPath.length)
}
if (openapi.basePath == ''){
openapi.basePath = baseServerPath;
}
return openapi;
};
90 changes: 82 additions & 8 deletions lib/generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const HELPERS_DIRNAME = '.helpers';
const PARTIALS_DIRNAME = '.partials';

/**
* Deletes all matching subfolders in target directory
* Deletes all matching subfolders in target directory
*
* @param {Object} config Configuration options
* @returns {Promise}
Expand Down Expand Up @@ -78,7 +78,7 @@ const generateFile = options => new Promise((resolve, reject) => {
console.warn(yellow(`Skipping file: ${generated_path}`));
resolve();
}

} catch (e) {
reject(e);
}
Expand All @@ -97,8 +97,8 @@ const generateOperationFile = (config, operation, operation_name) => new Promise
fs.readFile(path.join(config.root, config.file_name), 'utf8', (err, data) => {
if (err) return reject(err);
const subdir = config.root
.replace(new RegExp(`${config.templates_dir}[/]?`),'')
.replace("$$path$$", _.kebabCase(operation_name));
.replace(config.templates_dir + "\\" ,'')
.replace("$$path$$", _.kebabCase(operation_name));

const new_filename = config.file_name.replace('$$path$$', operation_name).replace(/.hbs$/, '');
const target_file = path.resolve(config.target_dir, subdir, new_filename);
Expand All @@ -112,9 +112,15 @@ const generateOperationFile = (config, operation, operation_name) => new Promise
});

xfs.mkdirpSync(path.dirname(target_file));
fs.writeFile(target_file, content, 'utf8', (err) => {
if (err) return reject(err);
resolve();
fs.access(target_file, fs.F_OK, (err) => {
if (err) {
fs.writeFile(target_file, content, 'utf8', (err) => {
if (err) return reject(err);
resolve();
});
}else{
resolve();
}
});
});
});
Expand All @@ -134,7 +140,6 @@ const generateOperationFiles = config => new Promise((resolve, reject) => {
}

path_name = path_name.replace(/}/g, '').replace(/{/g, ':');

files[operation_name].push({
path_name,
path,
Expand All @@ -148,6 +153,64 @@ const generateOperationFiles = config => new Promise((resolve, reject) => {
});
});

/**
* Recursiv function to add all proporties of the schema with the name
*
* @param {Object} config Configuration options
* @returns {Promise}
*/

function setPropertyName(property, name) {
property.name = name;
_.each(property.properties, (pro, pro_name) => {
setPropertyName(pro,pro_name );
});
}

/**
* Generates all the files for each schema by iterating over the schemas.
*
* @param {Object} config Configuration options
* @returns {Promise}
*/
const generateSchemaFiles = config => new Promise((resolve, reject) => {
const files = {};
_.each(config.data.openapi.components.schemas, (schema, schema_name) => {
_.each(schema.properties, (property, property_name) => {
setPropertyName(property, property_name);
});

fs.readFile(path.join(config.root, config.file_name), 'utf8', (err, data) => {
if (err) return reject(err);
const subdir = config.root
.replace(config.templates_dir + "\\", '');
const new_schema_name = schema_name + "s"
const new_filename = config.file_name.replace('$$schema$$', _.camelCase(new_schema_name)).replace(/.hbs$/, '');
const target_file = path.resolve(config.target_dir, subdir, new_filename);
const template = Handlebars.compile(data.toString());
const content = template({
openbrace: '{',
closebrace: '}',
schema_name: new_schema_name,
schema_properties: schema.properties,
schema_properties_required: schema.required,
openapi: config.data.openapi
});

xfs.mkdirpSync(path.dirname(target_file));
fs.access(target_file, fs.F_OK, (err) => {
if (err) {
fs.writeFile(target_file, content, 'utf8', (err) => {
if (err) return reject(err);
resolve();
});
} else {
resolve();
}
});
});
});
});
/**
* Generates the directory structure.
*
Expand Down Expand Up @@ -181,6 +244,17 @@ const generateDirectoryStructure = config => new Promise((resolve, reject) => {
});
const template_path = path.relative(templates_dir, path.resolve(root, stats.name));
fs.unlink(path.resolve(target_dir, template_path), next);
}else if (stats.name.includes('$$schema$$') || root.includes("$$schema$$")) {
// this file should be handled for each in openapi.paths
await generateSchemaFiles({
root,
templates_dir,
target_dir,
data: config,
file_name: stats.name
});
const template_path = path.relative(templates_dir, path.resolve(root, stats.name));
fs.unlink(path.resolve(target_dir, template_path), next);
} else {
const file_path = path.relative(templates_dir, path.resolve(root, stats.name));
if (!file_path.startsWith(`${PARTIALS_DIRNAME}${path.sep}`) && !file_path.startsWith(`${HELPERS_DIRNAME}${path.sep}`)) {
Expand Down
Loading