wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
'use strict';
 
var errors = require('restify-errors');
var _ = require('lodash');
var assert = require('assert-plus');
var semver = require('semver');
var Negotiator = require('negotiator');
var Chain = require('../chain');
 
///--- Globals
 
var InvalidVersionError = errors.InvalidVersionError;
var UnsupportedMediaTypeError = errors.UnsupportedMediaTypeError;
var DEF_CT = 'application/octet-stream';
 
///--- Exports
 
/**
 * Runs first handler that matches to the condition
 *
 * @public
 * @function conditionalHandler
 * @param {Object|Object[]} candidates - candidates
 * @param {Function|Function[]} candidates.handler - handler(s)
 * @param {String|String[]} [candidates.version] - '1.1.0', ['1.1.0', '1.2.0']
 * @param {String} [candidates.contentType] - accepted content type, '*\/json'
 * @returns  {Function} Handler
 * @throws {InvalidVersionError}
 * @throws {UnsupportedMediaTypeError}
 * @example
 * server.use(restify.plugins.conditionalHandler({
 *    contentType: 'application/json',
 *    version: '1.0.0',
 *    handler: function (req, res, next) {
 *        next();
 *    })
 * });
 *
 * server.get('/hello/:name', restify.plugins.conditionalHandler([
 *   {
 *      version: '1.0.0',
 *      handler: function(req, res, next) { res.send('1.x'); }
 *   },
 *   {
 *      version: ['1.5.0', '2.0.0'],
 *      handler: function(req, res, next) { res.send('1.5.x, 2.x'); }
 *   },
 *   {
 *      version: '3.0.0',
 *      contentType: ['text/html', 'text/html']
 *      handler: function(req, res, next) { res.send('3.x, text'); }
 *   },
 *   {
 *      version: '3.0.0',
 *      contentType: 'application/json'
 *      handler: function(req, res, next) { res.send('3.x, json'); }
 *   },
 *   // Array of handlers
 *   {
 *      version: '4.0.0',
 *      handler: [
 *          function(req, res, next) { next(); },
 *          function(req, res, next) { next(); },
 *          function(req, res, next) { res.send('4.x') }
 *      ]
 *   },
 * ]);
 * // 'accept-version': '^1.1.0' => 1.5.x, 2.x'
 * // 'accept-version': '3.x', accept: 'application/json' => '3.x, json'
 */
function conditionalHandler(candidates) {
    var isVersioned = false;
    var isContentTyped = false;
 
    if (!_.isArray(candidates)) {
        candidates = [candidates];
    }
 
    // Assert
    assert.arrayOfObject(candidates, 'candidates');
    candidates = candidates.map(function map(candidate) {
        // Array of handlers, convert to chain
        if (_.isArray(candidate.handler)) {
            var chain = new Chain();
            candidate.handler.forEach(function forEach(_handler) {
                assert.func(_handler);
                chain.add(_handler);
            });
            candidate.handler = chain.run.bind(chain);
        }
 
        assert.func(candidate.handler);
 
        if (_.isString(candidate.version)) {
            candidate.version = [candidate.version];
        }
        if (_.isString(candidate.contentType)) {
            candidate.contentType = [candidate.contentType];
        }
 
        assert.optionalArrayOfString(candidate.version);
        assert.optionalArrayOfString(candidate.contentType);
 
        isVersioned = isVersioned || !!candidate.version;
        isContentTyped = isContentTyped || !!candidate.contentType;
 
        return candidate;
    });
 
    /**
     * Conditional Handler
     *
     * @private
     * @param  {Request}  req - request
     * @param  {Response} res - response
     * @param  {Function} next - next
     * @returns {undefined} no return value
     */
    return function _conditionalHandlerFactory(req, res, next) {
        var contentType = req.headers.accept || DEF_CT;
        var reqCandidates = candidates;
 
        // Content Type
        if (isContentTyped) {
            var contentTypes = contentType.split(/\s*,\s*/);
            reqCandidates = candidates.filter(function filter(candidate) {
                var neg = new Negotiator({
                    headers: {
                        accept: candidate.contentType.join(', ')
                    }
                });
                var tmp = neg.preferredMediaType(contentTypes);
                return tmp && tmp.length;
            });
 
            if (!reqCandidates.length) {
                next(new UnsupportedMediaTypeError(contentType));
                return;
            }
        }
 
        // Accept Version
        if (isVersioned) {
            var reqVersion = req.version();
            var maxVersion;
            var maxVersionIndex;
 
            reqCandidates.forEach(function forEach(candidate, idx) {
                var version = semver.maxSatisfying(
                    candidate.version,
                    reqVersion
                );
 
                if (version) {
                    if (!maxVersion || semver.gt(version, maxVersion)) {
                        maxVersion = version;
                        maxVersionIndex = idx;
                    }
                }
            });
 
            // No version find
            if (_.isUndefined(maxVersionIndex)) {
                next(
                    new InvalidVersionError(
                        '%s is not supported by %s %s',
                        req.version() || '?',
                        req.method,
                        req.path()
                    )
                );
                return;
            }
 
            // Add api-version response header
            res.header('api-version', maxVersion);
            // Store matched version on request internal
            req._matchedVersion = maxVersion;
            // Run handler
            reqCandidates[maxVersionIndex].handler(req, res, next);
            return;
        }
 
        // When not versioned
        reqCandidates[0].handler(req, res, next);
    };
}
 
module.exports = conditionalHandler;