Created
August 3, 2021 04:06
-
-
Save aldy505/e349c3dd24e235351a4498bd3d9324e8 to your computer and use it in GitHub Desktop.
YAML body parser middleware for any Node.js framework
This file contains 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 type { IncomingMessage, ServerResponse } from 'http'; | |
import type { EventEmitter } from 'events'; | |
import yaml from 'yaml'; // npm install yaml | |
type Next = (err?: any) => void; | |
type RequestWithBody<T = any> = IncomingMessage & { body?: T } & EventEmitter | |
async function parseYaml(req: RequestWithBody, _: ServerResponse, next: Next) { | |
try { | |
let body = ''; | |
for await (const chunk of req) body += chunk; | |
req.body = yaml.parse(body); | |
next(); | |
} catch (error) { | |
next(error); | |
} | |
} | |
export { parseYaml }; | |
// Usage: | |
// | |
// const app = express() | |
// app.use(parseYaml()) | |
// | |
// Can also be used on Tinyhttp, Polka, and other Express-flavor frameworks. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment