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