diff --git a/lib/modifiers/type.js b/lib/modifiers/type.js index ea55e2e..665bcf4 100644 --- a/lib/modifiers/type.js +++ b/lib/modifiers/type.js @@ -7,9 +7,7 @@ */ function modify(data, model) { - if (!model.type) { - return data; - } else if(model.typeStrict == true) { + if (!model.type || !data || model.typeStrict == true) { return data; } @@ -17,23 +15,29 @@ function modify(data, model) { switch (model.type.toLowerCase()) { case 'string': - parsed = (data) ? String(data) : ''; + if (typeof data === 'object') { + parsed = JSON.stringify(data); + } else { + parsed = String(data); + } break; case 'number': if (!isNaN(Number(data))) { parsed = Number(data); - } else { - parsed = undefined; } break; case 'boolean': parsed = String(data).toLowerCase() === 'true'; break; case 'object': - parsed = (typeof data === 'object') ? data : undefined; - break; case 'array': - parsed = (Array.isArray(data)) ? data : undefined; + if(typeof data === 'string') { + try { + data = JSON.parse(data) + } catch (e) { + console.error('Tried to parse invalid json string to ' + model.type.toLowerCase()); + } + } break; } diff --git a/package.json b/package.json index 9760d90..96f11e8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "modelate", - "version": "0.2.8", + "version": "0.2.10", "description": "A simple data modeling tool for NodeJS", "main": "index.js", "scripts": { diff --git a/spec/modifiers/type.spec.js b/spec/modifiers/type.spec.js index 2d857d8..2c05e64 100644 --- a/spec/modifiers/type.spec.js +++ b/spec/modifiers/type.spec.js @@ -1,6 +1,6 @@ var valid = require('../../lib/modifiers/type'); -const str = 'Hello world'; +const str = '42'; const obj = {hello: 'world'}; const num = 42; const bool = true; @@ -29,20 +29,23 @@ describe(' - Type modifier', () => { for (let validType in typesKeys) { let model = {type: typesKeys[validType]}; for (let check in typesKeys) { + + // ToDo: ReWrite tests to clarify the behaviour in each use-case + it('shall only validate '+ typesKeys[validType] +' when model set, and '+ typesKeys[check] +' given', () => { const modelated = valid(types[typesKeys[check]], model); let shallBeValid = (typeof modelated === typesKeys[validType]); - if (typesKeys[validType] === 'object' && typeof modelated === 'undefined') { + if (typesKeys[validType] === 'object') { // && typeof modelated === 'undefined') { shallBeValid = true; } if ((typesKeys[validType] === 'array' && Array.isArray(modelated)) - || (typesKeys[validType] === 'array' && typeof modelated === 'undefined')) { + || (typesKeys[validType] === 'array')) { // && typeof modelated === 'undefined')) { shallBeValid = true; } - if (typesKeys[validType] === 'number' && typeof modelated === 'undefined') { + if (typesKeys[validType] === 'number') { // && typeof modelated === 'undefined') { shallBeValid = true; }