-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (61 loc) · 1.69 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
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
// Returns a number between 10000000 and 29999999 (8 digits)
const createBaseNumber = () => Math.floor(Math.random() * 29999999) + 10000000;
// Returns the modulus-11 check digit
const checkDigit = (number) => {
const digits = number.split('');
const reducer = (acc, current, idx) => ((9 - idx) * current) + acc;
const sum = digits.reduce(reducer, 0);
const mod = sum % 11;
return mod < 2 ? 0 : 11 - mod;
};
const generateNIF = () => {
const baseNumber = createBaseNumber().toString();
const cd = checkDigit(baseNumber);
return baseNumber + cd.toString();
};
const responseCacheHook = context => {
const requestId = context.response.getRequestId();
context.store.removeItem(requestId);
};
const run = async (context, CacheType) => {
// No cache, just return the new value
if (!CacheType || CacheType == 'none')
return generateNIF();
// For now caches are per request only
const { requestId } = context.meta;
const cachedValue = await context.store.getItem(requestId);
// If no cached value, set one
if (cachedValue === null) {
const nif = generateNIF();
context.store.setItem(requestId, nif); // Don't need to wait for this
return nif;
}
// Return cached value for request
return context.store.getItem(requestId);
};
module.exports.responseHooks = [ responseCacheHook ];
module.exports.templateTags = [
{
name: "NIFgen",
displayName: "Random NIF Generator",
description: "Generates a rendom valid portuguese NIF",
args: [
{
displayName: "CacheType",
type: "enum",
defaultValue: "none",
options: [
{
displayName: "None",
value: "none"
},
{
displayName: "Request",
value: "request"
}
]
}
],
run
}
];