Skip to content

Instantly share code, notes, and snippets.

@mostrecent
Last active August 30, 2022 18:07
Show Gist options
  • Save mostrecent/2fcb650bb881b608484533fdc656e582 to your computer and use it in GitHub Desktop.
Save mostrecent/2fcb650bb881b608484533fdc656e582 to your computer and use it in GitHub Desktop.
import { isArray, isObject, mapValues } from 'lodash-es'
import type { Document } from 'mongodb'
const mapValuesDeep = <T>(obj: T, cb: any): unknown => {
if (isArray(obj)) {
return obj.map(innerObj => mapValuesDeep(innerObj, cb))
} else if (isObject(obj)) {
if (!('toHexString' in obj || 'getDay' in obj)) {
return mapValues(obj, val => mapValuesDeep(val, cb))
} else {
return cb(obj)
}
} else {
return cb(obj)
}
}
const sanetizeMongo = <T extends Document | Document[] | null>(
document: T,
): T => {
return mapValuesDeep(document, (e: any) =>
e.toHexString ? e.toString() : e,
) as T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment