Created
April 13, 2020 13:12
-
-
Save grainrigi/0bd1ff5bdfe713c8ec2096024001f7eb to your computer and use it in GitHub Desktop.
Express JSON Body Parser With Automatic Date Parsing
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 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