parseReq.js 924 B

12345678910111213141516171819202122232425262728293031323334
  1. // @ts-check
  2. const { InvalidRequestError, InvalidParamsError } = require('./Errors')
  3. /**
  4. * @typedef {import('zod').ZodType} ZodType
  5. * @typedef {import('express').Request} Request
  6. */
  7. /**
  8. * @template T
  9. * @typedef {import('zod').output<T>} output<T>
  10. */
  11. /**
  12. * Parse and validate a request against a Zod schema
  13. *
  14. * @template {ZodType} T
  15. * @param {Request} req - The Express request object
  16. * @param {T} schema - The Zod schema to validate against
  17. * @returns {output<T>} The validated request object
  18. */
  19. function parseReq(req, schema) {
  20. const parsed = schema.safeParse(req)
  21. if (parsed.success) {
  22. return parsed.data
  23. } else if (parsed.error.issues.some(issue => issue.path[0] === 'params')) {
  24. // Parts of the URL path failed to validate; throw a specific error
  25. throw new InvalidParamsError(parsed.error)
  26. } else {
  27. throw new InvalidRequestError(parsed.error)
  28. }
  29. }
  30. module.exports = { parseReq }