Created
December 18, 2017 09:40
-
-
Save jettary/080e78f2ec789362b8adbe4f835e0642 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const _ = require('lodash'); | |
const fs = require('fs'); | |
const yaml = require('js-yaml'); | |
const header = { | |
swagger: '2.0', | |
info: { | |
version: '1.0.0', | |
title: 'Some Title', | |
description: 'Some funny description' | |
}, | |
schemes: ['http', 'https'], | |
basePath: '/api' | |
}; | |
/* object */ function readDocs(dir /* string */) { | |
const files = fs.readdirSync(dir); | |
const docs = {}; | |
files.forEach(file => { | |
if (! /\.yaml$/.test(file)) { | |
/* do nothing */ | |
return; | |
} | |
const fullpath = path.join(dir, file) | |
const data = yaml.load(fs.readFileSync(fullpath, 'utf-8').toString()); | |
addGeneratedFields(data); | |
_.merge(docs, data); | |
}); | |
return docs; | |
} | |
/* void */ function addGeneratedFields(data /* object */) { | |
const authParam = { | |
in: 'header', | |
name: 'Authorization', | |
description: 'Authorization token using bearer schema', | |
required: true, type: 'string' | |
}; | |
const pathRequiredParam = (name /* string */) => ({ | |
in: 'path', | |
name: name, | |
required: true, | |
type: 'string', | |
description: 'Path parameter' | |
}); | |
if (! ('paths' in data)) { | |
return; | |
} | |
for (const path in data.paths) { | |
for (const method in data.paths[path]) { | |
const parameters = data.paths[path][method].parameters || []; | |
const pathParams = path.match(/{([\w\s\|]+)}/gi); | |
if (pathParams) { | |
/* path params exists */ | |
for (const pathParam of pathParams.reverse()) { | |
const paramName = pathParam.replace('{', '').replace('}', '') | |
parameters.unshift(pathRequiredParam(paramName)); | |
} | |
} | |
parameters.unshift(authParam); | |
data.paths[path][method].parameters = parameters; | |
} | |
} | |
} | |
module.exports = function GenerateDocs(dir /* string */, outFile /* string */) { | |
const stream = fs.createWriteStream(outFile, { encoding: 'utf-8', flags: 'w' }); | |
stream.once('open', fd => { | |
stream.write('# This file is generated\n'); | |
stream.write(yaml.dump(header)); | |
stream.write(yaml.dump(readDocs(dir))); | |
stream.end(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment