Skip to content

Instantly share code, notes, and snippets.

@KiaraGrouwstra
Last active April 5, 2017 11:05
Show Gist options
  • Save KiaraGrouwstra/7f61e7a5cca951b8a60c38bda8d190cf to your computer and use it in GitHub Desktop.
Save KiaraGrouwstra/7f61e7a5cca951b8a60c38bda8d190cf to your computer and use it in GitHub Desktop.
generate crud endpoints for Swagger/OpenAPI
let R = require('ramda');
const up = (s) => s[0].toUpperCase() + s.substring(1).replace(/\-(\w)/, (match, letter) => letter.toUpperCase());
// JSON.stringify(crudOpenApiEndpoints({ single: 'app' }))
function crudOpenApiEndpoints ({ single, plural = single + 's', id = 'id', type = 'integer' }) {
let $ref = `#/definitions/${up(single)}`;
let resp = (schema) => ({ description: 'OK', schema });
let responses = { 204: resp({}) }; // empty non-GET response
let idPar = { name: id, in: 'path', required: true, type };
let bodyPar = { name: single, in: 'body', required: true, schema: { $ref } };
return {
[`/${plural}`]: {
get: {
responses: {
200: resp({ type: 'array', items: { $ref } }), // { $ref: `#/definitions/${up(plural)}` }
},
},
post: {
parameters: [bodyPar],
responses: {
200: resp({
type: 'object',
properties: {
[single]: {
$ref: `#/definitions/${up(single)}`,
},
},
}),
},
},
},
[`/${plural}/{id}`]: {
get: {
parameters: [idPar],
responses: {
200: resp({ $ref }),
},
},
delete: {
parameters: [idPar],
responses,
},
put: {
parameters: [idPar, bodyPar],
responses,
},
patch: {
parameters: [idPar, bodyPar], // technically need to strip `required`!
responses,
},
},
};
}
const renameBy = R.curry((fn, obj) => R.pipe(R.toPairs, R.map(R.adjust(fn, 0)), R.fromPairs)(obj));
/*
// use in batch:
var info = {
customer: { id: 'integer', name: 'string', address: 'string', phone: 'string' },
product: { id: 'integer', name: 'product', price: 'number' },
invoice: { id: 'integer', customer_id: 'integer', dicount: 'number', total: 'number' },
'invoice-item': { id: 'integer', invoice_id: 'integer', product_id: 'integer', quantity: 'number' },
};
// var makeOptional = R.omit(['required']);
var singles = R.pipe(R.map((properties) => ({ type: 'object', properties })), renameBy(up))(info);
// var plurals = R.pipe(R.keys, R.map((k) => [k+'s', { type: 'array', items: { $ref: '#/definitions/'+k } }]), R.fromPairs)(singles);
// var definitions = R.merge(singles, plurals);
var definitions = singles;
R.pipe(
R.mapObjIndexed((o, single) => crudOpenApiEndpoints({ single, type: o.id })),
R.mergeAll,
R.values,
R.mergeAll,
(paths) => ({ swagger: '2.0', info: { title: 'crud', version: '0.0.01' }, paths, definitions }),
JSON.stringify
)(info)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment