1
0
mirror of synced 2025-12-30 12:02:01 -05:00
Files
docs/middleware/events.js
Peter Bengtsson 7e614adc12 wrap async middlewares correctly (#28030)
* wrap async middlewares correctly

* clean up more

* feedbacked
2022-06-01 15:13:23 +00:00

38 lines
932 B
JavaScript

import express from 'express'
import { omit } from 'lodash-es'
import Ajv from 'ajv'
import addFormats from 'ajv-formats'
import { eventSchema, hydroNames } from '../lib/schema-event.js'
import catchMiddlewareError from './catch-middleware-error.js'
const OMIT_FIELDS = ['type']
const ajv = new Ajv()
addFormats(ajv)
const router = express.Router()
router.post(
'/',
catchMiddlewareError(async function postEvents(req, res, next) {
const isDev = process.env.NODE_ENV === 'development'
const fields = omit(req.body, '_csrf')
if (!ajv.validate(eventSchema, fields)) {
return res.status(400).json(isDev ? ajv.errorsText() : {})
}
res.json({})
if (req.hydro.maySend()) {
try {
await req.hydro.publish(hydroNames[fields.type], omit(fields, OMIT_FIELDS))
} catch (err) {
console.error('Failed to submit event to Hydro', err)
}
}
})
)
export default router