Created
August 26, 2022 12:40
-
-
Save mostrecent/3cdcc36938c29a1d25defc6f381483c4 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 checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); | |
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 ( | |
typeof value.toHexString === 'function' && | |
(value.id instanceof Buffer || typeof value.id === 'string') | |
) { | |
return (value.id.length === 12 || (value.id.length === 24 && checkForHexRegExp.test(value.id))) && undefined; | |
} | |
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`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment