Skip to content

Instantly share code, notes, and snippets.

@grainrigi
Created April 13, 2020 13:12
Show Gist options
  • Save grainrigi/0bd1ff5bdfe713c8ec2096024001f7eb to your computer and use it in GitHub Desktop.
Save grainrigi/0bd1ff5bdfe713c8ec2096024001f7eb to your computer and use it in GitHub Desktop.
Express JSON Body Parser With Automatic Date Parsing
import expressBodyParser from 'body-parser';
const reISO = /^(?:[+-]\d{6}|\d{4})-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
function dateReviver(key: string, value: any): any {
if(typeof value === 'string') {
// ざっくりチェック
if((value.length === 24 || value.length === 27) && value.endsWith('Z')) {
if(reISO.exec(value)) return new Date(value);
}
}
return value;
}
export default expressBodyParser.json({
reviver: dateReviver,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment