Skip to content

Commit b65db31

Browse files
committed
Update to apply json api de/serialization correctly
1 parent eb65789 commit b65db31

File tree

2 files changed

+41
-8
lines changed

2 files changed

+41
-8
lines changed

lib/deserialize.js

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,30 @@
33
module.exports = function (app) {
44
var remotes = app.remotes();
55

6-
//register a handler to run before all remote methods so that we can
7-
//transform JSON API structured JSON payload into something loopback
8-
//can work with.
9-
remotes.before('**', function (ctx, next) {
6+
function deserializeJSONAPIPayload (ctx, next) {
107

11-
//JSON api doesn't support PUT so we only need to apply our changes to
12-
//POST and PATCH operations.
13-
if (ctx.req.method === 'POST' || ctx.req.method === 'PATCH') {
8+
var regexs = [
9+
/\.create/,
10+
/prototype\.updateAttributes/,
11+
/prototype\.__createRelationships__/,
12+
/prototype\.__updateRelationships__/
13+
];
14+
15+
var matches = regexs.filter(function (regex) {
16+
return ctx.methodString.match(regex);
17+
});
18+
19+
if (matches.length > 0) {
1420

1521
//set the JSON API Content-Type response header
1622
ctx.res.set({'Content-Type': 'application/vnd.api+json'});
1723

1824
//check the incoming payload data to ensure it is valid according to the
1925
//JSON API spec.
2026
var data = ctx.args.data;
27+
28+
if (!data) return next();
29+
2130
if (!data.data) return next(new Error('JSON API resource object must contain `data` property'));
2231
if (!data.data.type) return next(new Error('JSON API resource object must contain `data.type` property'));
2332
if (ctx.req.method === 'PATCH') {
@@ -29,5 +38,10 @@ module.exports = function (app) {
2938
}
3039

3140
next();
32-
});
41+
}
42+
43+
//register a handler to run before all remote methods so that we can
44+
//transform JSON API structured JSON payload into something loopback
45+
//can work with.
46+
remotes.before('**', deserializeJSONAPIPayload);
3347
};

lib/serialize.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,25 @@ module.exports = function (app, options) {
8686
var remotes = app.remotes();
8787

8888
remotes.after('**', function (ctx, next) {
89+
90+
var regexs = [
91+
/\.find/,
92+
/\.create/,
93+
/\.deleteById/,
94+
/\.findById/,
95+
/prototype\.__get__/,
96+
/prototype\.updateAttributes/,
97+
/prototype\.__findRelationships__/,
98+
/prototype\.__createRelationships__/,
99+
/prototype\.__updateRelationships__/
100+
];
101+
102+
var matches = regexs.filter(function (regex) {
103+
return ctx.methodString.match(regex);
104+
});
105+
106+
if (matches.length === 0) return next();
107+
89108
ctx.res.set({'Content-Type': 'application/vnd.api+json'});
90109
//housekeeping, just skip verbs we definitely aren't
91110
//interested in handling.

0 commit comments

Comments
 (0)