-
Notifications
You must be signed in to change notification settings - Fork 1
/
use.injection.js
83 lines (69 loc) · 2.06 KB
/
use.injection.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
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
const tokenValidator = require('twilio-flex-token-validator').validator;
const _ = require('lodash');
const { InternalServerError } = require('./errors/internal-server.error');
const { UnauthorizedError } = require('./errors/unauthorized.error');
/**
* @type { import('../types/use.injection').useInjection }
*/
module.exports.useInjection = (fn, params) => async function (...args) {
const [context, event, callback] = args;
const { getTwilioClient, ...env } = context;
const providers = _.isUndefined(params?.providers)
|| !_.isPlainObject(params?.providers)
? {} : params.providers;
const validateToken = _.isUndefined(params?.validateToken)
|| _.isNull(params?.validateToken)
? false : params.validateToken;
const client = getTwilioClient();
const providerThat = {
client,
env,
};
const {
request, cookies, Token, ...values
} = event;
const providerNames = Object.keys(providers);
const that = {
request,
cookies,
env,
providers: providerNames.reduce((p, c) => {
Reflect.defineProperty(
p, c, {
value: providers[c].bind(providerThat),
enumerable: true,
},
);
return p;
}, {}),
};
try {
if (validateToken) {
const validation = await tokenValidator(
Token, env.ACCOUNT_SID, env.AUTH_TOKEN,
);
if (!validation.valid) {
return callback(undefined, new UnauthorizedError(validation.message));
}
}
return callback(undefined, await fn.apply(that, [values]));
} catch (err) {
if (typeof err === 'string') {
return callback(undefined, new UnauthorizedError(err));
}
console.error(err.stack, err.code);
return callback(undefined, new InternalServerError(err.message));
}
};
/**
* A more precisely type checker than Javascript built-in typeof.
*
* @type { import('../types/use.injection').typeOf }
*/
module.exports.typeOf = function (o) {
/**
* @type { string }
*/
const stringTag = Object.prototype.toString.call(o);
return stringTag.match(/(?<=\[\D+ )[A-Za-z]+/).shift();
};