Suvidha’s Http classes simplify handling responses. The default handlers support both Http classes and plain Protocol objects.
If you write your own handlers, you must support these classes to use them effectively.
/** * @typedef {object} Protocol * @property {any} body - The response body. This can be a string, an object, or any other data you want to send in the response. * @property {number} status - The HTTP status code (e.g. 200). * @property {Headers} [headers] - Optional response headers. A record where the keys are header names and the values are their corresponding header values. * @property {Meta} [meta] - Optional metadata associated with the response. */export interface Protocol { body: any; status: number; headers?: Headers; meta?: Meta;}
import { Http } from "suvidha";// In your request handler (using Suvidha's default handlers):return Http.Ok.body({ message: "Success!" }) .header("X-Custom-Header", "some-value") .meta({ timestamp: Date.now() });// Or for errors:throw new Http.BadRequest.body({ error: "Invalid request" });// Or using the default message:throw new Http.Unauthorized(); // Sends a 401 with the default "Unauthorized" message.
Description: Represents a successful 200 OK response.
Usage:Http.Ok.body(body).
Example:return Http.Ok.body({ data: result });.
Copy
/** * Represents a 200 OK response. */export class Ok extends End { /** * @param {any} body - The response body. */ constructor(body: Protocol["body"]) { super({ body, status: StatusCodes.OK }); } /** * Creates an `Http.Ok` response with the given body. * @param {any} body - The response body. * @returns {Http.Ok} - A new `Http.Ok` instance. */ static body(body: Protocol["body"]): Ok { return new Ok(body); }}
Description: Represents a 400 Bad Request response.
Usage:throw new Http.BadRequest.body(body) or throw new Http.BadRequest() (for default message).
Example:throw new Http.BadRequest.body({ error: "Invalid input" }); or throw new Http.BadRequest(); (sends “Bad Request”).
Copy
/** * Represents a 400 Bad Request response. Includes a default body message. */export class BadRequest extends End { /** * @param {any} [body="Bad Request"] - The response body (defaults to "Bad Request"). */ constructor(body: Protocol["body"] = "Bad Request") { super({ body, status: StatusCodes.BAD_REQUEST }); } /** * Creates an `Http.BadRequest` response with the given body. * @param {any} body - The response body. * @returns {Http.BadRequest} - A new `Http.BadRequest` instance. */ static body(body: Protocol["body"]): BadRequest { return new BadRequest(body); }}