-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (55 loc) · 1.68 KB
/
index.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
var express = require('express');
var _flatten = function(array, flat) {
var flat = flat || [];
for (var i = 0, len = array.length; i < len; i++) {
if (Array.isArray(array[i])) {
_flatten(array[i], flat);
} else {
flat.push(array[i]);
}
}
return flat;
};
express.application.restful = function(path) {
var argc = arguments.length,
middleware,
handlers;
if (argc < 2) {
throw new Error("app.restful requires at least two arguments: path and handlers");
} else if (argc == 2) {
middleware = [];
handlers = arguments[1];
} else if (argc > 2) {
middleware = _flatten(arguments.slice(1, argc - 1));
handlers = arguments[argc - 1];
}
if (typeof handlers == 'undefined') {
throw new Error("Missing handlers definitions for route '" + path + "'");
}
var id = 'id';
if ('$' in handlers) {
if ('id' in handlers.$) {
id = handlers.$.id;
}
if ('pre' in handlers.$) {
middleware = middleware.concat(handlers.$.pre);
}
}
if ('list' in handlers) {
this.get(path, middleware.concat(handlers.list));
}
if ('create' in handlers) {
this.post(path, middleware.concat(handlers.create));
}
var objectPath = path + '/:' + id;
if ('read' in handlers) {
this.get(objectPath, middleware.concat(handlers.read));
}
if ('update' in handlers) {
this.put(objectPath, middleware.concat(handlers.update));
}
if ('delete' in handlers) {
this.delete(objectPath, middleware.concat(handlers.delete));
}
};
exports.version = '1.0.0'