forked from travis4all/baucis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
92 lines (79 loc) · 2.23 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// __Dependencies__
var deco = require('deco');
var es = require('event-stream');
var mongoose = require('mongoose');
var Api = require('./Api');
var Controller = require('./Controller');
var Model = require('./Model');
var RestError = require('rest-error');
var plugins = {
json: require('baucis-json'),
links: require('baucis-links')
};
var instance;
var parsers = {};
var formatters = {};
var errorFormatters = {};
// __Module Definition__
var baucis = module.exports = function (options) {
return baucis.empty();
};
// __Public Members__
baucis.rest = function (model) {
if (!instance) instance = Api();
return instance.rest(model);
};
baucis.empty = function () {
var previous = instance;
instance = Api();
return previous;
};
baucis.formatters = function (response, callback) {
// if (response._headerSent) {
// callback(null, function () {
// return es.through(function (data) { console.log(data) }, function () {
// this.emit('end');
// });
// });
// return;
// }
var handlers = {
default: function () {
callback(RestError.NotAcceptable());
}
};
Object.keys(formatters).map(function (mime) {
handlers[mime] = formatters[mime](callback);
});
response.format(handlers);
};
// Adds a formatter for the given mime type. Needs a function that returns a stream.
baucis.setFormatter = function (mime, f) {
formatters[mime] = function (callback) { return function () { callback(null, f) } };
return baucis;
};
baucis.parser = function (mime, handler) {
// Default to JSON when no MIME type is provided.
mime = mime || 'application/json';
// Not interested in any additional parameters at this point.
mime = mime.split(';')[0].trim();
var handler = parsers[mime];
return handler ? handler() : undefined;
};
// Adds a parser for the given mime type. Needs a function that returns a stream.
baucis.setParser = function (mime, f) {
parsers[mime] = f;
return baucis;
};
// __Expose Modules__
baucis.Api = Api;
baucis.Controller = Controller;
baucis.Error = RestError;
baucis.Model = Model;
Api.container(baucis);
Controller.container(baucis);
RestError.container(baucis);
Model.container(baucis);
// __Plugins__
plugins.json.apply(baucis);
plugins.links.apply(baucis);