-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpress.js
More file actions
57 lines (49 loc) · 1.51 KB
/
Copy pathexpress.js
File metadata and controls
57 lines (49 loc) · 1.51 KB
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
const {idempotencyMiddleware} = require('./../index.js')
const {createCache} = require('cache-manager')
const express = require('express')
const {Keyv} = require('keyv')
const {CacheableMemory} = require('cacheable')
const SERVICE_NAME = 'express-demo'
function getCurrentUserId(req) {
// Replace this with the real authenticated user identifier.
// In Express you typically read it from req.user after authentication.
return req.user?.id ?? 'anonymous'
}
const cache = createCache({
stores: [
new Keyv({
// for Redis support: https://www.npmjs.com/package/cache-manager#update-on-redis-and-ioredis-support
store: new CacheableMemory({ttl: 60000, lruSize: 5000}),
}),
],
})
function extractIdempotencyKey(req) {
const header = req.headers['x-custom-req-id']
const value = Array.isArray(header) ? header[0] : header
if (!value || !/^[a-zA-Z0-9_.~-]{1,128}$/.test(value)) {
return undefined
}
// Scope the key with a service and user identifier to prevent cross-user collisions.
return `${SERVICE_NAME}-${getCurrentUserId(req)}-${value}`
}
const app = express()
app.use(
idempotencyMiddleware({
ttl: 5000,
idempotencyKeyExtractor: extractIdempotencyKey,
cache: {
get: async (key) => {
return cache.get(key)
},
set: async (key, value, {ttl}) => {
return cache.set(key, value, ttl)
},
},
}),
)
app.post('/create', (req, res) => {
res.send('Resource created!')
})
app.listen(3000, () => {
console.log('Server is running on port 3000')
})