Möhre
Möhre
Aarktype
Created by Möhre on 9/12/2024 in #questions
Is there a way to parse Dates and date iso strings without losing toJsonSchema capabilities.
I'm trying to parse dates and also allow for date objects, but I also require toJsonSchema to work without exceptions.
const dateParse = type("string.date.iso.parse");
const date = new Date();
dateParse(date) // error
dateParse(date.toISOString()) // works
dateParse.in.toJsonSchema() // works

const dateParse2 = type("string.date.iso.parse | Date");
const date = new Date();
dateParse2(date) // works
dateParse2(date.toISOString()) // works
dateParse.in.toJsonSchema() // errors
const dateParse = type("string.date.iso.parse");
const date = new Date();
dateParse(date) // error
dateParse(date.toISOString()) // works
dateParse.in.toJsonSchema() // works

const dateParse2 = type("string.date.iso.parse | Date");
const date = new Date();
dateParse2(date) // works
dateParse2(date.toISOString()) // works
dateParse.in.toJsonSchema() // errors
Is there a way to have all three functionalities combined? It is fine if the json schema only shows the string input. I don't want to convert date -> string -> date if possible and also keep only one schema.
19 replies
Aarktype
Created by Möhre on 9/11/2024 in #questions
ToJsonSchema fails with narrow
Hi short question, i might be missing something obvious. If I try to convert a type to jsonschema with a narrow function it fails every time, even if I use the .in property.
const url = type("string")
.narrow((s, ctx) => {
if (isValidHttpUrl(s)) {
return true;
}

return ctx.mustBe("a valid URL");
});

// FAILS:
url.in.toJsonSchema()

// EXPECTED:
{ type: 'string' }
const url = type("string")
.narrow((s, ctx) => {
if (isValidHttpUrl(s)) {
return true;
}

return ctx.mustBe("a valid URL");
});

// FAILS:
url.in.toJsonSchema()

// EXPECTED:
{ type: 'string' }
36 replies