Skip to content

Commit

Permalink
fix(validate): stricter nulls, number|null type, better errors (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
gadicc committed Feb 17, 2021
1 parent 631ed45 commit 93dafc6
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
9 changes: 9 additions & 0 deletions bin/schema-tweak.js
Expand Up @@ -27,6 +27,15 @@ process.stdin.on("end", () => {
} else if (schema.$ref === "#/definitions/DateInMs") {
const key = state.property.split("/").pop();
parent.properties[key] = { yahooFinanceType: "DateInMs" };
} else if (Array.isArray(schema.type)) {
if (
schema.type.length === 2 &&
schema.type.includes("number") &&
schema.type.includes("null")
) {
delete schema.type;
schema.yahooFinanceType = "number|null";
}
} else if (schema.type === "number") {
delete schema.type;
schema.yahooFinanceType = "number";
Expand Down
54 changes: 50 additions & 4 deletions src/lib/validateAndCoerceTypes.ts
Expand Up @@ -30,17 +30,54 @@ ajv.addKeyword({
return true;
}

if (schema === "number") {
if (schema === "number" || schema === "number|null") {
if (typeof data === "number") return true;

if (typeof data === "string") {
let float = Number.parseFloat(data);
if (Number.isNaN(float)) return false;
if (Number.isNaN(float)) {
validate.errors = validate.errors || [];
validate.errors.push({
keyword: "yahooFinanceType",
message: "Number.parseFloat returned NaN",
params: { schema, data },
});
return false;
}
return set(float);
}

if (data === null) {
if (schema === "number|null") {
return true;
} else {
validate.errors = validate.errors || [];
validate.errors.push({
keyword: "yahooFinanceType",
message: "Expecting number'ish but got null",
params: { schema, data },
});
return false;
}
}

if (typeof data === "object") {
if (Object.keys(data).length === 0) return set(null);
if (Object.keys(data).length === 0) {
// Value of {} becomes null
// Note, TypeScript types should be "number | null"
if (schema === "number|null") {
return set(null);
} else {
validate.errors = validate.errors || [];
validate.errors.push({
keyword: "yahooFinanceType",
message:
"Got {}->null for 'number', did you want 'number | null' ?",
params: { schema, data },
});
return false;
}
}
if (typeof data.raw === "number") return set(data.raw);
}
} else if (schema === "date") {
Expand Down Expand Up @@ -79,7 +116,16 @@ ajv.addKeyword({
return true;
if (typeof data === "string") {
const parts = data.split("-").map(parseFloat);
if (Number.isNaN(parts[0]) || Number.isNaN(parts[1])) return false;
if (Number.isNaN(parts[0]) || Number.isNaN(parts[1])) {
validate.errors = validate.errors || [];
validate.errors.push({
keyword: "yahooFinanceType",
message:
"Number.parseFloat returned NaN: [" + parts.join(",") + "]",
params: { schema, data },
});
return false;
}
return set({ low: parts[0], high: parts[1] });
}
} else {
Expand Down

0 comments on commit 93dafc6

Please sign in to comment.