Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow coercion of numeric date formats to Date #41

Open
gregbrowndev opened this issue Mar 13, 2022 · 1 comment
Open

Allow coercion of numeric date formats to Date #41

gregbrowndev opened this issue Mar 13, 2022 · 1 comment

Comments

@gregbrowndev
Copy link

gregbrowndev commented Mar 13, 2022

Context

  • node version: v16.14.0
  • module version:
    • joi: 17.6.0
    • @joi/date: 2.1.0
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): standalone
  • any other relevant information:

What problem are you trying to solve?

I wish to validate and convert a numerical value into a proper Date object. The raw value is a number of the format YYYYMMDD. The data is received from an API which I don't control.

Additionally, I want to be able to specify the correct expected output type in my schema, i.e. using Joi.date(). I am using joi-to-typescript to generate the Typescript interface for this value (which I want to be a Date, not a number or anything else).

The problem is the number is cast into a UNIX/millisecond epoch timestamp and the format option is ignored.

Joi.date().validate(20211029)
// {value: Thu Jan 01 1970 06:36:51 GMT+0100 (Greenwich Mean Time)}

Joi.date().format("YYYYMMDD").validate(20211029)
// {value: Thu Jan 01 1970 06:36:51 GMT+0100 (Greenwich Mean Time)}

Ideally, if I could coerce the value into a Joi.string() first and then into Joi.date() that would solve my problem.

I have found a workaround using custom:

const dateNumberValidator: CustomValidator = (_: any, helpers: CustomHelpers) => {
  const dateStr = String(helpers.original);
  if (!dateStr) {
    return dateStr;
  }
  const {value, error} = Joi.date().format("YYYYMMDD").validate(dateStr)
  if (error) {
    return helpers.error(error);
  }
  return value
}

Joi.date().custom(dateNumberValidator).validate(20211029)
// {value: "2021-10-28T23:00:00.000Z"}

Do you have a new or modified API suggestion to solve the problem?

It would be great if an option was added to provide more control over how the raw value is coerced. It should allow a numeric value to be cast into a string before parsing as a Date rather than treating all numbers as epoch timestamps.

Thanks!

@hueniverse
Copy link
Contributor

What would it look like? Care to suggest a syntax?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants