Skip to content

Commit

Permalink
fix(validation): correctly handle null dates + coverage (#264)
Browse files Browse the repository at this point in the history
  • Loading branch information
gadicc committed Oct 24, 2021
1 parent 52ea8e4 commit 68378d5
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/lib/validateAndCoerceTypes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ ajv.addSchema({
$schema: "http://json-schema.org/draft-07/schema#",
properties: {
date: { yahooFinanceType: "date" },
dateNull: { yahooFinanceType: "date|null" },
dateInMs: { yahooFinanceType: "DateInMs" },
twoNumberRange: { yahooFinanceType: "TwoNumberRange" },
number: { yahooFinanceType: "number" },
Expand Down Expand Up @@ -166,6 +167,46 @@ describe("validateAndCoerceTypes", () => {
validateAndCoerceTypes({ ...defLogParams, object });
expect(object.date).toBe(date);
});

it("passes if data is null and type IS date|null", () => {
const object = { dateNull: null };
expect(() =>
validateAndCoerceTypes({ ...defLogParams, object })
).not.toThrow();
});

it("fails if data is null and type IS NOT date|null", () => {
const object = { date: null };
let error: FailedYahooValidationError | any;
try {
validateAndCoerceTypes({ ...defNoLogParams, object });
} catch (e) {
error = e;
}
// @ts-ignore
expect(error).toBeDefined();
expect(error.errors[0].message).toMatch(/Expecting date/);
});

it("passes and coerces {} to null if type IS Date|null", () => {
const object = { dateNull: {} };
expect(() =>
validateAndCoerceTypes({ ...defLogParams, object })
).not.toThrow();
expect(object.dateNull).toBe(null);
});

it("fails when receiving {} if type IS NOT date|null", () => {
const object = { date: {} };
let error: FailedYahooValidationError | any;
try {
validateAndCoerceTypes({ ...defNoLogParams, object });
} catch (e) {
error = e;
}
expect(error).toBeDefined();
expect(error.errors[0].message).toMatch(/date \| null/);
});
});

describe("DateInMs", () => {
Expand Down
14 changes: 13 additions & 1 deletion src/lib/validateAndCoerceTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,19 @@ ajv.addKeyword({

if (typeof data === "number") return set(new Date(data * 1000));

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

if (typeof data === "object") {
if (Object.keys(data).length === 0) {
Expand Down

0 comments on commit 68378d5

Please sign in to comment.