1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | const _ = require('lodash');
|
7 | const wrap = require('word-wrap');
|
8 | const bundler = require('./bundler');
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | const generateOperationId = (method_name, path_name) => {
|
19 | if (path_name === '/') return method_name;
|
20 |
|
21 |
|
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 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | const 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 |
|
77 | module.exports = swagger2;
|