Created
January 12, 2022 23:58
An express middleware for hydrating 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
const dateFormat = /^-?\d+-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; | |
function hydrator(key: string, value: any) { | |
if (typeof value === 'string' && dateFormat.test(value)) { | |
return new Date(value); | |
} | |
return value; | |
} | |
export function hydrateDates(req: Request, res: Response, next: any) { | |
// if we don't pass any data, then this doesn't apply | |
if (extractRequestData(req) === undefined) { | |
next(); | |
} else { | |
const dataAsString = JSON.stringify(extractRequestData(req)); | |
const hydratedData = JSON.parse(dataAsString, hydrator); | |
req.body.data = hydratedData; | |
next(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment