Last active
August 26, 2022 10:15
-
-
Save mostrecent/ac06952b1c204d72436eb868faa057c3 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
var ObjectId = require('bson-objectid') | |
function check_serializability(value, id, path) { | |
const type = typeof value; | |
if (type === 'string' || type === 'boolean' || type === 'number' || type === 'undefined') { | |
// primitives are fine | |
return; | |
} | |
if (type === 'object') { | |
// nulls are fine... | |
if (!value) return; | |
// ...so are plain arrays... | |
if (Array.isArray(value)) { | |
value.forEach((child, i) => { | |
check_serializability(child, id, `${path}[${i}]`); | |
}); | |
return; | |
} | |
// ...and objects | |
const tag = Object.prototype.toString.call(value); | |
if (tag === '[object Object]') { | |
if (ObjectId.isValid(value)) { | |
console.warn(`${path} returned from 'load' in ${id} is an ObjectId cannot be deserialized.`); | |
return; | |
} | |
for (const key in value) { | |
check_serializability(value[key], id, `${path}.${key}`); | |
} | |
return; | |
} | |
} | |
throw new Error(`${path} returned from 'load' in ${id} cannot be serialized as JSON`); | |
} | |
console.log(check_serializability(new ObjectId(), 'path', '_id')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment