1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | (function (define) {
|
9 | 'use strict';
|
10 |
|
11 | define(function (require) {
|
12 |
|
13 | var interceptor, mime, registry, noopConverter, when;
|
14 |
|
15 | interceptor = require('../interceptor');
|
16 | mime = require('../mime');
|
17 | registry = require('../mime/registry');
|
18 | when = require('when');
|
19 |
|
20 | noopConverter = {
|
21 | read: function (obj) { return obj; },
|
22 | write: function (obj) { return obj; }
|
23 | };
|
24 |
|
25 | |
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | return interceptor({
|
47 | init: function (config) {
|
48 | config.registry = config.registry || registry;
|
49 | return config;
|
50 | },
|
51 | request: function (request, config) {
|
52 | var type, headers;
|
53 |
|
54 | headers = request.headers || (request.headers = {});
|
55 | type = mime.parse(headers['Content-Type'] = headers['Content-Type'] || config.mime || 'text/plain');
|
56 | headers.Accept = headers.Accept || config.accept || type.raw + ', application/json;q=0.8, text/plain;q=0.5, */*;q=0.2';
|
57 |
|
58 | if (!('entity' in request)) {
|
59 | return request;
|
60 | }
|
61 |
|
62 | return config.registry.lookup(type).otherwise(function () {
|
63 |
|
64 | if (config.permissive) {
|
65 | return noopConverter;
|
66 | }
|
67 | throw 'mime-unknown';
|
68 | }).then(function (converter) {
|
69 | var client = config.client || request.originator;
|
70 |
|
71 | return when.attempt(converter.write, request.entity, { client: client, request: request, mime: type, registry: config.registry })
|
72 | .otherwise(function() {
|
73 | throw 'mime-serialization';
|
74 | })
|
75 | .then(function(entity) {
|
76 | request.entity = entity;
|
77 | return request;
|
78 | });
|
79 | });
|
80 | },
|
81 | response: function (response, config) {
|
82 | if (!(response.headers && response.headers['Content-Type'] && response.entity)) {
|
83 | return response;
|
84 | }
|
85 |
|
86 | var type = mime.parse(response.headers['Content-Type']);
|
87 |
|
88 | return config.registry.lookup(type).otherwise(function () { return noopConverter; }).then(function (converter) {
|
89 | var client = config.client || response.request && response.request.originator;
|
90 |
|
91 | return when.attempt(converter.read, response.entity, { client: client, response: response, mime: type, registry: config.registry })
|
92 | .otherwise(function (e) {
|
93 | response.error = 'mime-deserialization';
|
94 | response.cause = e;
|
95 | throw response;
|
96 | })
|
97 | .then(function (entity) {
|
98 | response.entity = entity;
|
99 | return response;
|
100 | });
|
101 | });
|
102 | }
|
103 | });
|
104 |
|
105 | });
|
106 |
|
107 | }(
|
108 | typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }
|
109 |
|
110 | ));
|