Skip to content

Instantly share code, notes, and snippets.

@soulsam480
Created September 22, 2021 07:37
Show Gist options
  • Save soulsam480/89fead7fabb0cb0044e360d5bcc8eced to your computer and use it in GitHub Desktop.
Save soulsam480/89fead7fabb0cb0044e360d5bcc8eced to your computer and use it in GitHub Desktop.
A sanitizer for mongo response
const toString = Object.prototype.toString;
type MaybeObjArrStrNum =
| { [x: string]: MaybeObjArrStrNum }
| (MaybeObjArrStrNum | string | number)[]
| string
| number;
export function sanitizeResponse(data: {
[x: string]: MaybeObjArrStrNum;
}): { [x: string]: any } | { [x: string]: any }[] {
function sanitizeObject(data: { [x: string]: string | number }) {
return Object.keys(data).reduce(
(o, key) => (key.startsWith('_') ? { ...o } : { ...o, [key]: data[key] }),
{},
);
}
function sanitizeArray(dat: (MaybeObjArrStrNum | string | number)[]): any[] {
return dat.map((el) => {
if (Array.isArray(el)) return sanitizeArray(el);
if (el.toString() === '[object Object]') return sanitizeResponse(el as any);
return el;
});
}
return Object.keys(data).reduce<{ [x: string]: any }>((o, key) => {
if (!key.startsWith('_')) {
if (
toString.call(data[key]) === '[object Object]' &&
Object.values(data[key]).every(
(value) => !['[object Object]', '[object Array]'].includes(toString.call(value)),
)
) {
o[key] = sanitizeObject(data[key] as any);
} else if (
toString.call(data[key]) === '[object String]' ||
toString.call(data[key]) === '[object Number]'
) {
o[key] = data[key];
} else if (Array.isArray(data[key])) {
o[key] = sanitizeArray(data[key] as any[]);
} else if (toString.call(data[key]) === '[object Object]') {
o[key] = sanitizeResponse(data[key] as any);
} else {
o[key] = data[key];
}
}
return o;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment