1 |
|
2 |
|
3 | var Hoek = require('hoek');
|
4 | var Boom = require('boom');
|
5 | var MediaType = require('media-type');
|
6 | var Pack = require('../package.json');
|
7 |
|
8 |
|
9 |
|
10 | var internals = {};
|
11 |
|
12 |
|
13 | internals.onPreHandler = function (request, reply) {
|
14 |
|
15 |
|
16 |
|
17 | if (request.method === 'options') {
|
18 | return reply.continue();
|
19 | };
|
20 |
|
21 | if(internals.isntJsonApiRequest(request)) {
|
22 | return reply.continue();
|
23 | }
|
24 |
|
25 | |
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | var contentType = request.headers['content-type'];
|
45 |
|
46 | if (contentType) {
|
47 | var contentMedia = MediaType.fromString(contentType);
|
48 |
|
49 |
|
50 | if (contentMedia.type !== 'application' || contentMedia.subtype !== 'vnd.api' || Object.keys(contentMedia.parameters).length > 0) {
|
51 |
|
52 | return reply(Boom.unsupportedMediaType('Only `application/vnd.api+json` content-type supported'));
|
53 | }
|
54 | }
|
55 | return reply.continue();
|
56 | };
|
57 |
|
58 |
|
59 | internals.onPreResponse = function (request, reply) {
|
60 |
|
61 | var response = request.response;
|
62 |
|
63 | if (request.method === 'options') {
|
64 | return reply.continue();
|
65 | }
|
66 |
|
67 | if(internals.isntJsonApiRequest(request)) {
|
68 | return reply.continue();
|
69 | }
|
70 |
|
71 | if (response.isBoom) {
|
72 | var error = {
|
73 | title: response.output.payload.error,
|
74 | status: response.output.statusCode,
|
75 | detail: response.output.payload.message
|
76 | };
|
77 | response.output.payload = {
|
78 | errors: [error],
|
79 | meta: Hoek.applyToDefaults({id: request.id}, internals.meta)
|
80 | };
|
81 | response.output.headers['content-type'] = 'application/vnd.api+json';
|
82 | } else {
|
83 | if (response.source) {
|
84 | response.source.meta = Hoek.applyToDefaults({id: request.id}, internals.meta);
|
85 | }
|
86 | response.headers['content-type'] = 'application/vnd.api+json';
|
87 | }
|
88 | return reply.continue();
|
89 | };
|
90 |
|
91 | internals.isntJsonApiRequest = function (request) {
|
92 | if(!request.headers.accept) {
|
93 | return true;
|
94 | }
|
95 |
|
96 | if (request.headers.accept.indexOf('application/vnd.api+json') === -1) {
|
97 | return true;
|
98 | }
|
99 |
|
100 | return false;
|
101 | }
|
102 |
|
103 |
|
104 |
|
105 | exports.register = function (plugin, options, done) {
|
106 |
|
107 | internals.meta = options.meta || {};
|
108 |
|
109 | plugin.ext('onPreHandler', internals.onPreHandler);
|
110 | plugin.ext('onPreResponse', internals.onPreResponse);
|
111 |
|
112 | return done();
|
113 | };
|
114 |
|
115 | exports.register.attributes = {
|
116 | name: Pack.name,
|
117 | version: Pack.version
|
118 | };
|