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
// Copyright 2018 Restify. All rights reserved.
 
'use strict';
 
var assert = require('assert-plus');
 
///--- API
 
/**
 * This plugin creates `req.set(key, val)` and `req.get(key)` methods for
 * setting and retrieving request specific data.
 *
 * @public
 * @function context
 * @returns {Function} Handler
 * @example
 * server.pre(restify.plugins.pre.context());
 * server.get('/', [
 *     function(req, res, next) {
 *         req.set(myMessage, 'hello world');
 *         return next();
 *     },
 *     function two(req, res, next) {
 *         res.send(req.get(myMessage)); // => sends 'hello world'
 *         return next();
 *     }
 * ]);
 */
function ctx() {
    return function context(req, res, next) {
        var data = {};
 
        /**
         * Set context value by key
         * Requires the context plugin.
         *
         * @public
         * @memberof Request
         * @instance
         * @function req.set
         * @param    {String} key - key
         * @param    {*} value - value
         * @returns  {undefined} no return value
         */
        req.set = function set(key, value) {
            assert.string(key, 'key must be string');
 
            if (key === '') {
                assert.fail('key must not be empty string');
            }
            data[key] = value;
        };
 
        /**
         * Get context value by key.
         * Requires the context plugin.
         *
         * @public
         * @memberof Request
         * @instance
         * @function req.get
         * @param    {String} key - key
         * @returns  {*} value stored in context
         */
        req.get = function get(key) {
            assert.string(key, 'key must be string');
 
            if (key === '') {
                assert.fail('key must not be empty string');
            }
            return data[key];
        };
 
        /**
         * Get all context
         * Requires the context plugin.
         *
         * @public
         * @memberof Request
         * @instance
         * @function req.getAll
         * @returns  {*} value stored in context
         */
        req.getAll = function getAll() {
            return data;
        };
 
        return next();
    };
}
 
///--- Exports
 
module.exports = ctx;