Last active
December 17, 2015 12:19
-
-
Save Deraen/5609256 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
var express = require('./server'); | |
var app = express(); | |
app.get('/cars/:id', function (req, res) { | |
res.send({id: req.params.id, name: 'Corolla'}); | |
}, {summary: 'Retrieve a car'}); | |
var auth = function (req, res, next) { | |
next(); | |
}; | |
auth.__meta__ = { | |
auth: true | |
}; | |
app.post('/cars', auth, function (req, res) { | |
res.send(200); | |
}, {summary: 'Create a car'}); | |
app.get('/', function (req, res) { | |
res.send(app.describe()); | |
}, {summary: 'Describe the API'}); | |
app.listen(3000); |
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
[ | |
{ | |
"method": "get", | |
"path": "/cars/:id", | |
"keys": [ | |
{ | |
"name": "id", | |
"optional": false | |
} | |
], | |
"summary": "Retrieve a car" | |
}, | |
{ | |
"method": "get", | |
"path": "/", | |
"keys": [], | |
"summary": "Describe the API" | |
}, | |
{ | |
"method": "post", | |
"path": "/cars", | |
"keys": [], | |
"summary": "Create a car", | |
"auth": true | |
} | |
] |
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
var express = require('express'); | |
var app = express.application; | |
var methods = require('methods'); | |
var _ = require('lodash'); | |
exports = module.exports = express; | |
var meta = {}; | |
methods.forEach(function (method) { | |
meta[method] = {}; | |
var orig = app[method]; | |
app[method] = function(path) { | |
var tmp = {}; | |
var lastArg = _.last(arguments); | |
if (arguments.length >= 2 && _.isObject(lastArg)) { | |
tmp = _.extend(tmp, lastArg); | |
arguments = _.initial(arguments); | |
} | |
_.forEach(arguments, function (arg) { | |
if (_.isFunction(arg) && _.has(arg, '__meta__')) { | |
tmp = _.extend(tmp, arg.__meta__); | |
} | |
}); | |
meta[method][path] = tmp; | |
return orig.apply(this, arguments); | |
}; | |
}); | |
app.describe = function () { | |
var endpoints = []; | |
var map = this._router.map; | |
var f = function (route) { | |
endpoints.push(_.extend(_.pick(route, 'method', 'path', 'keys'), meta[route.method][route.path])); | |
}.bind(this); | |
map.forEach(function (method) { | |
method.forEach(f); | |
}); | |
return endpoints; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment