-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.js
71 lines (58 loc) · 1.95 KB
/
http.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
'use strict';
var http = exports;
var _private = {};
var debug = require('ghost-ignition').debug('http');
var _ = require('lodash');
var queryParser = require('./vendor/jsonapi-query-parser');
var formatter = require('./format');
var APIRequest = require('./request');
var APIResponse = require('./response');
// TODO: do this based on req.method instead of apiReq.options.method?
var successCodes = {
GET: 200,
POST: 201,
DELETE: 204,
PATCH: 200
};
_private.toAPI = function toAPI(api, req, options) {
var params = queryParser.parseRequest(req.url);
var payload = req.body;
var source = options.request.sourceProperty ? req[options.request.sourceProperty] : req.user;
source.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
var custom = {};
_.each(options.request.customProperties, function (propName) {
custom[propName] = req[propName];
});
debug('CONVERT to API');
var apiRequest = new APIRequest(api.models[options.model], options, params, payload, source, custom);
var apiResponse = new APIResponse(apiRequest);
return [
apiRequest,
apiResponse
];
};
_private.fromAPI = function fromAPI(api, apiReq, apiRes) {
debug('CONVERT to HTTP');
return {
data: formatter(api, apiReq, apiRes),
status: apiReq.options.response.successCode || successCodes[apiReq.options.method] || 200
};
};
http.adapter = function adapter(api, options, req, res, next) {
var args = _private.toAPI(api, req, options);
var callback = function callback(err, apiReq, apiRes) {
debug('HTTP callback');
if (err) {
debug('Got an error');
return next(err);
}
var json = _private.fromAPI(api, apiReq, apiRes);
if (json) {
debug('Returning JSON');
return res.status(json.status).json(json.data);
}
return next();
};
args.push(callback);
return args;
};