Skip to content

Instantly share code, notes, and snippets.

@mostrecent
Created August 26, 2022 12:40
Show Gist options
  • Save mostrecent/3cdcc36938c29a1d25defc6f381483c4 to your computer and use it in GitHub Desktop.
Save mostrecent/3cdcc36938c29a1d25defc6f381483c4 to your computer and use it in GitHub Desktop.
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