Home > Net >  Validate both JS Date and Firestore Date with Joi
Validate both JS Date and Firestore Date with Joi

Time:12-12

I'm currently discovering Joi library and - at this time - it's a great experience.
However, I'm facing a tiny problem I can't resolve. Help or advice needed!

Consider the following schema (a bit):

const workSchema = Joi.object({ timeline_created: Joi.date().allow(null).required()) }

It works perfectly fine when I submit a JS date (or null value).
However, I'm using Firestore which convert JS Date to this kind of object:

timeline_created: Timestamp { _seconds: 1637258607, _nanoseconds: 349000000 }

Thus, I can't validate my schema (it's not a date Joi knows).
Then, my question: how to write my schema (I want it to be strict/precise) but validating at the same time a JS Date and a Firestore Date.

Thanks

EDIT: I made some progress with:

timeline_created: Joi.object().keys({_seconds: Joi.number(),_nanoseconds: Joi.number()}).required()

It validates my Firestore object.
However, how could I also validate if timeline_created is null or a JS Date? Thx.

CodePudding user response:

This is working:

Joi.alternatives([Joi.object().keys({ _seconds: Joi.number(), _nanoseconds: Joi.number() }), Joi.date(), null]).required()
  • Related