Created
August 2, 2016 12:32
-
-
Save a-ludi/bf4a9e1e27df19496335c6e6445af55f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function expectStruture(object, structure, breadcrumbs) { | |
var subStructure; | |
breadcrumbs = breadcrumbs || []; | |
structure = { | |
title: true, | |
description: true, | |
gallery: [{}], | |
eventTypeMood: true, | |
eventTypeLocation: true, | |
eventTypeActivity: true, | |
price: true, | |
canParticipateAfterStart: true, | |
hasFixedContingent: true, | |
isBookable: true, | |
isForFree: true, | |
isDeactivated: true, | |
creationDate: true, | |
locationName: true, | |
locationDescription: true, | |
longitude: true, | |
latitude: true, | |
owner: true, | |
vat: true, | |
dates: [{}] | |
}; | |
try { | |
switch (typeof structure) { | |
case 'object': | |
switch (structure.constructor) { | |
case Array: | |
if (structure.length > 1) { | |
throw "array may contain at most one item"; | |
} | |
if (object.constructor !== Array) { | |
throw "expected type <Array> but got <" + object.constructor.name + ">"; | |
} | |
if (structure.length > 0) { | |
subStructure = structure[0]; | |
object.forEach(function (value, idx) { | |
expectStruture(value, subStructure, breadcrumbs.concat([idx])); | |
}); | |
} | |
break; | |
case Function: | |
if (!structure(object)) { | |
throw "custom validation failed"; | |
} | |
break; | |
case Object: | |
if (structure !== null && object === null) { | |
throw "expected value not to be null"; | |
} | |
if (typeof object !== 'object') { | |
throw "expected type <object> but got <" + (typeof object) + ">"; | |
} | |
_.forOwn(structure, function (value, key) { | |
if (!value && object.hasOwnProperty(key)) { | |
throw "expected object not to have property <" + key + ">"; | |
} | |
if (value && !object.hasOwnProperty(key)) { | |
throw "expected object to have property <" + key + ">"; | |
} | |
if (typeof value ) | |
}); | |
break; | |
default: | |
} | |
break; | |
case 'string': | |
if (typeof object !== structure) { | |
if (typeof object === 'function' && object.constructor.name !== structure) { | |
throw "expected <" + structure + "> but got <" + object.constructor.name + ">"; | |
} else if (typeof object !== 'function') { | |
throw "expected <" + structure + "> but got <" + typeof object + ">"; | |
} | |
} | |
break; | |
default: | |
throw "invalid value in structure: " + structure; | |
} | |
} catch(err) { | |
throw new Error(err + " (at " + breadcrumbs.join("->") + ")"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment