forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecord-redirect.js
31 lines (28 loc) · 922 Bytes
/
record-redirect.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
import { v4 as uuidv4 } from 'uuid'
import { hydroNames } from '../lib/schema-event.js'
export default function recordRedirects(req, res, next) {
if (!req.hydro.maySend()) return next()
res.on('finish', async function recordRedirect() {
// We definitely don't want 304
if (![301, 302, 303, 307, 308].includes(res.statusCode)) return
const schemaName = hydroNames.redirect
const redirectEvent = {
context: {
user: req.cookies['_docs-events'] || uuidv4(),
event_id: uuidv4(),
version: '1.0.0',
created: new Date().toISOString(),
path: req.path,
referrer: req.get('referer'),
},
redirect_from: req.originalUrl,
redirect_to: res.get('location'),
}
try {
await req.hydro.publish(schemaName, redirectEvent)
} catch (err) {
console.error('Failed to record redirect to Hydro', err)
}
})
return next()
}