Skip to content

Instantly share code, notes, and snippets.

@duncangrubbs
Created January 12, 2022 23:58
Show Gist options
  • Save duncangrubbs/d5133117fce31559576dbec97bf7832f to your computer and use it in GitHub Desktop.
Save duncangrubbs/d5133117fce31559576dbec97bf7832f to your computer and use it in GitHub Desktop.
An express middleware for hydrating dates
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