Last active
May 3, 2021 11:48
-
-
Save samtgarson/185231ad4e704f846bf532d0f649bf49 to your computer and use it in GitHub Desktop.
Hydrate JSON dates
This file contains hidden or 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
import { formatISO, parseISO } from "date-fns" | |
const dateRegex = /^[0-9]{4}(-[0-9]{2}){2}T[0-9]{2}(:[0-9]{2}){2}/ | |
export function hydrate <T extends unknown>(obj: T): T | |
export function hydrate (obj: unknown): unknown { | |
if (Array.isArray(obj)) return obj.map(hydrate) | |
if (typeof obj !== 'object') return obj | |
if (!obj) return obj | |
return Object.entries(obj).reduce((hsh, [k, v]) => ({ | |
...hsh, | |
[k]: obj.constructor.name === 'object' | |
? hydrate(v) | |
: typeof v === 'string' && dateRegex.exec(v) | |
? parseISO(v) | |
: v | |
}), {}) | |
} | |
const replacer = (_: string, val: unknown) => { | |
if (val instanceof Date) return formatISO(val) | |
return val | |
} | |
export const dehydrate = (obj: unknown): string => { | |
return JSON.stringify(obj, replacer) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment