Asynchronous HTTP microservices framework with built-in body parsing and error handling
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Request body parsing utilities for handling JSON, text, and binary data with size limits and encoding support. All functions cache the raw body on first call, allowing multiple parsing attempts.
Parses request body as a Buffer with configurable size limits and encoding options.
/**
* Parses request body as a Buffer with size limit protection
* @param req - Incoming HTTP request
* @param options - Configuration options for parsing
* @returns Promise resolving to Buffer containing raw body data
*/
function buffer(req: IncomingMessage, options?: BufferInfo): Promise<Buffer>;
interface BufferInfo {
/** Size limit for request body (default: '1mb') - can be number of bytes or string like '5mb' */
limit?: string | number | undefined;
/** Character encoding for text data (default: determined from Content-Type header) */
encoding?: BufferEncoding;
}Usage Examples:
import { buffer } from "micro";
const handler = async (req, res) => {
// Parse as buffer with default 1mb limit
const buf = await buffer(req);
console.log(buf); // <Buffer 7b 22 6e 61 6d 65 22 3a 20 22 4a 6f 68 6e 22 7d>
// With custom limit
const largeBuf = await buffer(req, { limit: '10mb' });
// With specific encoding
const encodedBuf = await buffer(req, {
limit: '5mb',
encoding: 'utf8'
});
return "Processed buffer data";
};Parses request body as a string, internally using the buffer function and converting to text.
/**
* Parses request body as a string with size limit protection
* @param req - Incoming HTTP request
* @param options - Configuration options for parsing
* @returns Promise resolving to string containing body text
*/
function text(req: IncomingMessage, options?: BufferInfo): Promise<string>;Usage Examples:
import { text } from "micro";
const handler = async (req, res) => {
// Parse as text with default settings
const bodyText = await text(req);
console.log(bodyText); // '{"name": "John"}'
// With custom limit and encoding
const customText = await text(req, {
limit: '2mb',
encoding: 'latin1'
});
// Process plain text data
const lines = bodyText.split('\n');
return { lineCount: lines.length, firstLine: lines[0] };
};Parses request body as JSON, internally using the text function and JSON.parse with error handling.
/**
* Parses request body as JSON with size limit protection and error handling
* @param req - Incoming HTTP request
* @param options - Configuration options for parsing
* @returns Promise resolving to parsed JSON data
* @throws HttpError with status 400 if JSON parsing fails
*/
function json(req: IncomingMessage, options?: BufferInfo): Promise<unknown>;Usage Examples:
import { json, createError } from "micro";
const handler = async (req, res) => {
try {
// Parse JSON with default settings
const data = await json(req);
console.log(data); // { name: "John", age: 30 }
// With custom limit
const largeData = await json(req, { limit: '5mb' });
// Type assertion for known structure
const user = data as { name: string; age: number };
return {
message: `Hello ${user.name}`,
processedAge: user.age + 1
};
} catch (error) {
// JSON parsing errors are automatically converted to HTTP 400 errors
throw error;
}
};
// Multiple calls to same request (cached)
const multiParseHandler = async (req, res) => {
const data1 = await json(req); // Parses from request
const data2 = await json(req); // Returns cached result
return { same: data1 === data2 }; // true
};All body parsing functions handle various error conditions:
HttpError with status 413 when body exceeds limitjson() throws HttpError with status 400 for malformed JSONHttpError with status 400 for other parsing errorsError Example:
import { json, HttpError } from "micro";
const handler = async (req, res) => {
try {
const data = await json(req, { limit: '1kb' });
return data;
} catch (error) {
if (error instanceof HttpError) {
if (error.statusCode === 413) {
return { error: "Request too large" };
}
if (error.statusCode === 400) {
return { error: "Invalid JSON format" };
}
}
throw error;
}
};