araera111 / mysql-to-zod

convert mysql schemas into Zod Schemas
https://mysql-to-zod.pages.dev/
2 stars 1 forks source link

Option to get a string type instead of a Date type #7

Closed araera111 closed 1 year ago

araera111 commented 1 year ago

reason Error occurs when trying to convert to Date type in MySQL when 0000-00-00 00:00:00 is entered.

araera111 commented 1 year ago

option isDateToString boolean

araera111 commented 1 year ago

If knex is used and a value of type Date is obtained, Invalid Date is returned when the value is 0000-00-00. For example, if a Date type value is 0000-00-00 and you want to correct it to 1000-01-01, you can do so as follows

import { z } from "zod";
const main = async () => {
  const toValidDatetimeSchema = z.preprocess((val) => {
    const isDate = val instanceof Date;
    if (isDate)
      return Number.isNaN(val.getTime())
        ? new Date("1000-01-01 00:00:00")
        : val;
    return new Date("1000-01-01 00:00:00");
  }, z.date());

  const dateObjSchema = z.object({
    date: toValidDatetimeSchema,
  });
  const dateObj1 = dateObjSchema.parse({
    date: new Date("2021-01-01 00:00:00"),
  });
  const dateObj2 = dateObjSchema.parse({ date: new Date("ABC") });

  const dateObj3 = dateObjSchema.parse({ date: "0000-00-00 00:00:00" });
  console.log({ dateObj1, dateObj2, dateObj3 });
  /* 
    {
      dateObj1: { date: 2020-12-31T15:00:00.000Z },
      dateObj2: { date: 0999-12-31T14:41:01.000Z },
      dateObj3: { date: 0999-12-31T14:41:01.000Z }
    }
  */
};
main();

Or sometimes we want 0000-00-00 00:00 as a string. 2023-07-13 00:00 can also be a string. If a strange value comes in, we want 1000-00-00 00:00:00. In such a case, do like this

import { format } from "date-fns";
import { z } from "zod";

const main = async () => {
  const toValidDatetimeSchema = z.preprocess((val) => {
    const isDate = val instanceof Date;
    if (isDate)
      return Number.isNaN(val.getTime())
        ? format(new Date("1000-01-01 00:00:00"), "yyyy-MM-dd HH:mm:ss")
        : format(new Date(val), "yyyy-MM-dd HH:mm:ss");
    return val;
  }, z.string());

  const dateObjSchema = z.object({
    date: toValidDatetimeSchema,
  });
  const dateObj1 = dateObjSchema.parse({
    date: new Date("2021-01-01 00:00:00"),
  });
  const dateObj2 = dateObjSchema.parse({ date: new Date("ABC") });

  const dateObj3 = dateObjSchema.parse({ date: "0000-00-00 00:00:00" });
  console.log({ dateObj1, dateObj2, dateObj3 });
  /* 
    {
      dateObj1: { date: '2021-01-01 00:00:00' },
      dateObj2: { date: '1000-01-01 00:00:00' },
      dateObj3: { date: '0000-00-00 00:00:00' }
    }
  */
};
main();

Which is the appropriate option for mtz (mysql-to-zod)? Basically, since mtz is supposed to be used with kysely and knex, 0000-00-00 is correct to be treated as an invalid Date. Would it be correct to correct it and use new Date(1000-00-00 00:00:00);?

umm