Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save merelinguist/9e9ef5cd2c1f806c6f682a53e525006c to your computer and use it in GitHub Desktop.
Save merelinguist/9e9ef5cd2c1f806c6f682a53e525006c to your computer and use it in GitHub Desktop.
import { flattenObject } from 'flatten-anything';
import { nestifyObject } from 'nestify-anything';
import { JSONValue, JSONObject } from './types';
import { isSerializable, isPlainObject, serializeExtraTypes } from './utils';
export const serialize = (input: any) => {
let json: JSONValue = {};
let meta: JSONObject | string = {};
if (isSerializable(input)) {
json = input;
return { json, meta };
}
if (Array.isArray(input)) {
let output = [];
for (let i = 0, len = input.length; i < len; i++) {
const value = input[i];
if (isSerializable(value)) {
output.push(value);
} else {
output.push(serializeExtraTypes(value).value);
meta[i] = serializeExtraTypes(value).type;
}
}
json = output;
return { json, meta };
}
if (!isPlainObject(input)) {
json = serializeExtraTypes(input).value;
meta = serializeExtraTypes(input).type;
return { json, meta };
}
if (isPlainObject(input)) {
const flattened = flattenObject(input);
for (let i = 0, len = Object.keys(flattened).length; i < len; i++) {
const key = Object.keys(flattened)[i];
const value = Object.values(flattened)[i];
if (isSerializable(value)) {
json[key] = value;
} else {
json[key] = serializeExtraTypes(value).value;
meta[key] = serializeExtraTypes(value).type;
}
}
// @ts-expect-error
json = nestifyObject(json);
return { json, meta };
}
throw new Error('invalid input');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment