zodHelpers.js 1.1 KB

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