zodHelpers.js 946 B

1234567891011121314151617181920212223242526272829303132
  1. const { z } = require('zod')
  2. const mongodb = require('mongodb')
  3. const { ObjectId } = mongodb
  4. const dateWithTransform = (schema, allowNull = false) => {
  5. return schema.transform(dt => {
  6. if (allowNull && !dt) return null
  7. return dt instanceof Date ? dt : new Date(dt)
  8. })
  9. }
  10. const zz = {
  11. objectId: () =>
  12. z.string().refine(ObjectId.isValid, { message: 'invalid Mongo ObjectId' }),
  13. coercedObjectId: () =>
  14. z
  15. .string()
  16. .refine(ObjectId.isValid, { message: 'invalid Mongo ObjectId' })
  17. .transform(val => new ObjectId(val)),
  18. hex: () => z.string().regex(/^[0-9a-f]*$/),
  19. datetime: () => dateWithTransform(z.union([z.iso.datetime(), z.date()])),
  20. datetimeNullable: () =>
  21. dateWithTransform(z.union([z.iso.datetime(), z.date(), z.null()]), true),
  22. datetimeNullish: () =>
  23. dateWithTransform(
  24. z.union([z.iso.datetime(), z.date(), z.null(), z.undefined()]),
  25. true
  26. ),
  27. }
  28. module.exports = { zz }