-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (45 loc) · 1.44 KB
/
index.js
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
/**
* @typedef {Object} MiddlewareContext
*
* @property {Object<string, any>} msg
* @property {number} chatId
* @property {Object<string, any>} ctx - Added context property
*/
/**
* Creates context middleware function.
* @return {function(this: MiddlewareContext)} Context middleware function
*/
function createContextMiddleware() {
const contextStore = new WeakMap()
return function() {
const key = this.msg
Object.defineProperty(this, 'ctx', {
get() {
/** @type T */
let ctx = contextStore.get(key)
if (!ctx) {
ctx = new Object(null)
contextStore.set(key, ctx)
}
const ctxHandler = {
get: function(obj, prop) {
return obj[prop]
},
set: function(obj, prop, val) {
obj[prop] = val
contextStore.set(key, obj)
return true
},
}
return new Proxy(ctx, ctxHandler)
},
set() {
throw new Error(
"Value cannot be assigned directly to 'this.ctx'. Use custom properties to save data, e.g. 'this.ctx.myProperty = myValue'."
)
},
enumerable: true,
})
}
}
module.exports = createContextMiddleware