forked from howardabrams/express-api-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make-api-docs.js
280 lines (248 loc) · 8.14 KB
/
make-api-docs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/**
* We can run this program to generate the HTML docs for the API.
*
* Algorithm includes:
* - Reading the router.js and getting the list of files and functions.
*/
var fs = require('fs');
var dox = require('dox');
var handlebars = require('handlebars');
var files = [];
var resources = [];
var funcs = {};
// TODO: Remove this global variable and pass the values around...
var output = { entries: [] };
/**
* Reads a file containing Express routes. This function/behavior is
* the most brittle part of this process, so while many people put the
* routes in the main `app.js`, if you can create another `routes.js`
* file that looks like:
*
* var index = require('./routes/index');
* var user = require('./routes/user');
*
* module.exports.setup = function( app ) {
* app.get( '/', index.index );
* app.get( '/user', user.getAllUsers);
* app.post( '/user', user.createUser);
* app.get( '/user/:email', user.getUser );
* app.delete('/user/:email', user.deleteUser);
* app.put( '/user/:email', user.updateUser );
* };
*
* @param {String} The name of the JavaScript source code to read. If
* not file is given, defaults to `./router.js`
*/
exports.generate = function(inputFile, outputFile) {
if (!inputFile) {
inputFile = "./app.js";
}
if (!outputFile) {
outputFile = "public/api.html";
}
var data = fs.readFileSync (inputFile, 'utf8');
parseRoutes(data);
// if (files.length > 0) {
// console.log(files);
// }
// if (resources.length > 0) {
// console.log(resources);
// }
// console.log(funcs);
files.forEach( function(file) {
analyzeFile(file);
});
resources.forEach( function(resource) {
analyzeResource(resource);
});
writeFile(outputFile);
};
/**
* Combines a *template* with the model (stored in `output`) and writes
* out to a given file.
*
* @param file {String} the name of the output file
*/
var writeFile = function(file) {
var data = fs.readFileSync ( __dirname + '/template.html', 'utf8');
var template = handlebars.compile(data);
// console.log(output);
fs.writeFileSync(file, template(output) );
};
/**
* Walks through a top-level source code, line-by-line, and attempts
* to *parse* the file by using a collection of regular expressions to
* match particular 'patterns' that express and express-resource specifies.
*/
var parseRoutes = function(data) {
data.split(/\n+/).forEach( function(line) {
var r = /^\s*var\s*([A-Za-z0-9_]+)\s*=\s*require\s*\(['"]([^'"]+)['"]\s*\)\s*;/.exec(line);
if ( r ) {
files.push({
label: r[1],
file: r[2]
});
}
var a = /^\s*app\.([A-Za-z0-9]+)\s*\(\s*['"]([^'"]+)['"]\s*,\s*([^.]+)\.([^\) ]+)/.exec(line);
if ( a && a[1] !== 'resource' ) {
funcs[ a[4] ] = {
method: a[1],
route : a[2],
file : a[3],
func : a[4]
};
}
// Express resource lines look like:
// app.resource('user', require('./resources/user'));
var rsc = /^\s*app\.resource\s*\(\s*['"]([^'"]+)['"]\s*,\s*require\s*\(['"]([^'"]+)['"]\s*\)\s*\)\s*;/.exec(line);
if ( rsc ) {
resources.push({
rsc : rsc[1],
file: rsc[2]
});
}
});
};
/**
* Called for each file listed in the 'files' array. This will analyze and
* parse the files functions and comments.
*
* @param file (String) The name of the file, with or without the final '.js'
*/
var analyzeFile = function(file) {
var filename = file.file;
if ( ! /\.js$/.test(filename) ) {
filename = filename + '.js';
}
var js = fs.readFileSync(filename, 'utf8');
var d = dox.parseComments(js);
d.forEach( function(entry) {
if ( entry.ctx &&
( entry.ctx.type == 'method' || entry.ctx.type == 'function') ) {
// console.log("Working on API docs for route: %s", entry.ctx.name);
createRoute(entry.ctx.name, entry);
}
});
};
/**
* Function called for each route referenced in the file.
*
* For each route referenced, we build up part of the "model" that will be
* passed to the template engine for display.
*
* **Note:** Doesn't return anything, but side effects include modifying the
* `output` object model.
*
* @param {String} name route name that should be part of `funcs[]` array
* @param {Object} details acquired by `dox.parse`. Expects a `description` property.
*/
var createRoute = function(name, details) {
var called = funcs[name];
if (called) {
output.entries.push({
"name": name,
"method": called.method.toUpperCase(),
"route": called.route,
"text": details.description.full
});
// console.log("FUNCTION: %s", name);
// console.log(" Method: %s", called.method );
// console.log(" Route: %s", called.route );
// console.log(details);
}
};
/**
* Called for each file listed in the 'resource' array. This will analyze and
* parse the files functions and comments.
*
* @param resource (String) The name of the file, with or without the final '.js'
*/
var analyzeResource = function(resource) {
var label = resource.rsc;
var filename = resource.file;
if ( ! /\.js$/.test(filename) ) {
filename = filename + '.js';
}
try {
var js = fs.readFileSync(filename, 'utf8');
var d = dox.parseComments(js);
d.forEach( function(entry) {
if ( entry.ctx &&
( entry.ctx.type == 'method' || entry.ctx.type == 'function') ) {
console.log("Working on API docs for resource: %s", entry.ctx.name);
var model = createResource(label, entry);
if (model) {
output.entries.push( model );
}
}
});
}
catch (err) {
console.warn( err );
}
};
/**
* Function called for each resource referenced in the file.
*
* For each resource referenced, we build up part of the "model" that will be
* passed to the template engine for display. Of course, with `express-resource`
* the names of the function *imply* a particular route, as in:
*
* - GET /label -> index
* - GET /label/new -> new
* - POST /label -> create
* - GET /label/ID -> show
* - GET /label/ID/edit -> edit
* - PUT /label/ID -> update
* - DELETE /label/ID -> destroy
*
* Where `label` is the name of the resource that is passed in, and `ID` is
* an identification of the resource.
*
* @param {String} label resource name that should be part of route
* @param {Object} entry acquired by `dox.parse`. Expects a `description` property.
* @returns {Object} a model entry that can be pushed into the `output`
*/
function createResource(label, entry) {
var name = entry.ctx.name;
var method = 'GET';
var route = '/' + label;
switch(entry.ctx.name) {
case 'index':
method = 'GET';
route = '/' + label;
break;
case 'new':
method = 'GET';
route = '/' + label + '/new';
break;
case 'create':
method = 'POST';
route = '/' + label;
break;
case 'show':
method = 'GET';
route = '/' + label + '/<ID>';
break;
case 'edit':
method = 'GET';
route = '/' + label + '/<ID>/edit';
break;
case 'update':
method = 'PUT';
route = '/' + label + '/<ID>';
break;
case 'destroy':
method = 'DELETE';
route = '/' + label + '/<ID>';
break;
default:
return;
}
return {
"name": name,
"method": method,
"route": route,
"text": entry.description.full
};
};