forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
45 lines (40 loc) · 1.37 KB
/
middleware.js
File metadata and controls
45 lines (40 loc) · 1.37 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
import express from 'express'
import { omit, without, mapValues } from 'lodash-es'
import Ajv from 'ajv'
import addFormats from 'ajv-formats'
import { schemas, hydroNames } from './schema.js'
import catchMiddlewareError from '../../middleware/catch-middleware-error.js'
import { noCacheControl } from '../../middleware/cache-control.js'
import { publish } from './hydro.js'
const router = express.Router()
const ajv = new Ajv()
addFormats(ajv)
const OMIT_FIELDS = ['type']
const allowedTypes = new Set(without(Object.keys(schemas), 'validation'))
const isDev = process.env.NODE_ENV === 'development'
const validations = mapValues(schemas, (schema) => ajv.compile(schema))
router.post(
'/',
catchMiddlewareError(async function postEvents(req, res) {
noCacheControl(res)
// Make sure the type is supported before continuing
const { type } = req.body
if (!type || !allowedTypes.has(type)) {
return res.status(400).json({ message: 'Invalid type' })
}
// Validate the data matches the corresponding data schema
if (!validations[type](req.body)) {
return res.status(400).json(isDev ? ajv.errorsText() : {})
}
res.json({})
try {
await publish({
schema: hydroNames[type],
value: omit(req.body, OMIT_FIELDS),
})
} catch (err) {
console.error('Failed to submit event to Hydro', err)
}
})
)
export default router