Skip to content

Instantly share code, notes, and snippets.

@aldy505
Created August 3, 2021 04:06
Show Gist options
  • Save aldy505/e349c3dd24e235351a4498bd3d9324e8 to your computer and use it in GitHub Desktop.
Save aldy505/e349c3dd24e235351a4498bd3d9324e8 to your computer and use it in GitHub Desktop.
YAML body parser middleware for any Node.js framework
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