From b7c66cb41f8c513016c9a25b422c1f235ca2a0b5 Mon Sep 17 00:00:00 2001 From: Nick Schot Date: Wed, 18 Jan 2017 00:07:25 +0100 Subject: [PATCH] fix: make sure dates are correctly validated & parsed (#639) * fix: make sure dates are correctly validated fix: make sure transform-keys doesn't recurse into a Date object * Check date last * Add test case --- .../route/params/test/parameter.test.js | 35 +++++++++++++++++++ .../route/params/utils/validate-type.js | 4 +++ src/utils/transform-keys.js | 3 +- 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/packages/router/route/params/test/parameter.test.js b/src/packages/router/route/params/test/parameter.test.js index 1b9875dd..422e45b8 100644 --- a/src/packages/router/route/params/test/parameter.test.js +++ b/src/packages/router/route/params/test/parameter.test.js @@ -139,6 +139,41 @@ describe('module "router/route/params"', () => { }); }); + describe('- type "date"', () => { + [true, false].forEach(required => { + describe(`- ${required ? 'required' : 'optional'}`, () => { + let value; + + beforeEach(() => { + value = new Date(); + subject = new Parameter({ + required, + type: 'date', + path: 'meta.test' + }); + }); + + if (required) { + it('fails when the value is null', () => { + expect(() => subject.validate(null)).to.throw(TypeError); + }); + } else { + it('passes when the value is null', () => { + expect(subject.validate(null)).to.be.null; + }); + } + + it('fails when there is a type mismatch', () => { + expect(() => subject.validate('test')).to.throw(TypeError); + }); + + it('returns the value when the type and value match', () => { + expect(subject.validate(value)).to.equal(value); + }); + }); + }); + }); + primitives.forEach(({ type, valid, falsy, invalid }) => { describe(`- type "${type}"`, () => { [true, false].forEach(required => { diff --git a/src/packages/router/route/params/utils/validate-type.js b/src/packages/router/route/params/utils/validate-type.js index 3227ca7c..796da867 100644 --- a/src/packages/router/route/params/utils/validate-type.js +++ b/src/packages/router/route/params/utils/validate-type.js @@ -38,6 +38,10 @@ export default function validateType( isValid = isObject(value) || isNull(value); break; + case 'date': + isValid = value instanceof Date; + break; + default: isValid = type === valueType; } diff --git a/src/utils/transform-keys.js b/src/utils/transform-keys.js index d292b582..dc72961b 100644 --- a/src/utils/transform-keys.js +++ b/src/utils/transform-keys.js @@ -21,7 +21,8 @@ export function transformKeys>( const recurse = deep && value && typeof value === 'object' - && !Array.isArray(value); + && !Array.isArray(value) + && !(value instanceof Date); if (recurse) { return {