UNPKG

2.62 kBJavaScriptView Raw
1/**
2 * This module is used to accommodate Swagger 2 data for easier rendering.
3 * @module swagger2
4 */
5
6const _ = require('lodash');
7const wrap = require('word-wrap');
8const bundler = require('./bundler');
9
10/**
11 * Generates an "operationId" attribute based on path and method names.
12 *
13 * @private
14 * @param {String} method_name HTTP method name.
15 * @param {String} path_name Path name.
16 * @return {String}
17 */
18const generateOperationId = (method_name, path_name) => {
19 if (path_name === '/') return method_name;
20
21 // clean url path for requests ending with '/'
22 let clean_path = path_name;
23 if (clean_path.indexOf('/', clean_path.length - 1) !== -1) {
24 clean_path = clean_path.substring(0, clean_path.length - 1);
25 }
26
27 let segments = clean_path.split('/').slice(1);
28 segments = _.transform(segments, (result, segment) => {
29 if (segment[0] === '{' && segment[segment.length - 1] === '}') {
30 segment = `by-${_.capitalize(segment.substring(1, segment.length - 1))}}`;
31 }
32 result.push(segment);
33 });
34
35 return _.camelCase(`${method_name.toLowerCase()}-${segments.join('-')}`);
36};
37
38/**
39 * Accommodates Swagger object for easier rendering.
40 *
41 * @param {String|Object} swagger File path to Swagger file or **fully bundled and dereferenced** Swagger JS object.
42 * @return {Object} The accommodated Swagger object.
43 */
44const swagger2 = async swagger => {
45 const authorized_methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLIK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND'];
46
47 if (typeof swagger === 'string') {
48 try {
49 swagger = await bundler(swagger);
50 } catch (e) {
51 throw e;
52 }
53 } else if (typeof swagger !== 'object') {
54 throw new Error(`Could not find a valid swagger definition: ${swagger}`);
55 }
56
57 swagger.basePath = swagger.basePath || '';
58
59 _.each(swagger.paths, (path, path_name) => {
60 path.endpointName = path_name === '/' ? 'root' : path_name.split('/')[1];
61 _.each(path, (method, method_name) => {
62 if (authorized_methods.indexOf(method_name.toUpperCase()) === -1) return;
63
64 method.operationId = _.camelCase(method.operationId || generateOperationId(method_name, path_name).replace(/\s/g, '-'));
65 method.descriptionLines = wrap(method.description || method.summary || '', { width: 60, indent: '' }).split(/\n/);
66 _.each(method.parameters, param => {
67 param.type = param.type || (param.schema ? param.schema.type : undefined);
68 });
69 });
70 });
71
72 swagger.endpoints = _.unique(_.pluck(swagger.paths, 'endpointName'));
73
74 return swagger;
75};
76
77module.exports = swagger2;