-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
65 lines (53 loc) · 1.74 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
const {createKey} = require('./lib/utils');
const {getLock} = require('./lib/mutex');
const {getStoreProvider} = require('./lib/storeProviders');
const HEADER_NAME = 'Idempotency-Key';
const storeResponse = async (idempotencyKey, store, ctx) => {
const {path, body: reqBody} = ctx.request;
const {status, body, header} = ctx.response;
const response = {status, body, header};
await store.set(createKey(path, reqBody, idempotencyKey), response);
}
const checkStoreRoot = (getStoreProvider, createKey) => async (storeOptions, idempotencyKey, ctx, next) => {
const {path, body: reqBody} = ctx.request;
const store = getStoreProvider(storeOptions);
const cachedResponse = await store.get(createKey(path, reqBody, idempotencyKey));
if(!cachedResponse) {
await next();
return await storeResponse(idempotencyKey, store, ctx);
}
const {status, body: resBody, header} = cachedResponse;
ctx.status = status;
ctx.body = resBody;
ctx.set(header);
ctx.set('X-Cache', 'HIT');
}
const idempotenceRoot = checkStore => (opts={}) => async (ctx, next) => {
let releaseLock;
try {
const {storeOptions} = opts;
const idempotencyKey = ctx.request.header[HEADER_NAME]
? ctx.request.header[HEADER_NAME]
: ctx.request.header[HEADER_NAME.toLocaleLowerCase()];
if(!idempotencyKey) {
return await next();
}
releaseLock = await getLock(idempotencyKey);
await checkStore(storeOptions, idempotencyKey, ctx, next);
}
catch(error) {
throw error;
}
finally {
if(releaseLock) {
releaseLock();
}
}
}
const checkStore = checkStoreRoot(getStoreProvider, createKey);
const idempotence = idempotenceRoot(checkStore);
module.exports = {
idempotenceRoot,
checkStoreRoot,
idempotence,
};