UNPKG

@foxify/http

Version:
342 lines 11.2 kB
/// <reference types="node" /> /// <reference types="node" /> import { OutgoingHttpHeaders, ServerResponse } from "http"; import Request from "./Request"; import { JsonT, StatusT, StringifyT } from "./constants"; import { CallbackT as EngineCallbackT, Engine } from "./view"; export declare const DEFAULT_SETTINGS: SettingsI; interface Response extends ServerResponse { /** * Get value for header `header`. * * @alias getHeader */ get<T extends keyof HeadersI>(header: T): HeadersI[T]; getHeader<T extends keyof HeadersI>(header: T): HeadersI[T]; /** * @alias header */ set<T extends string>(header: T, value: HeadersI[T] | number[]): this; set(headers: { [Header in string]: HeadersI[Header] | number[]; }): this; /** * @alias contentType */ type(type: string): this; } declare class Response extends ServerResponse<Request> { next: (error?: Error) => void; readonly req: Request; statusCode: StatusT; stringify: { [statusCode in StatusT]?: StringifyT; }; constructor(req: Request); /** * Check if the request is fresh, aka * Last-Modified and/or the ETag * still match. */ get fresh(): boolean; /** * Check if the request is stale, aka * "Last-Modified" and / or the "ETag" for the * resource has changed. */ get stale(): boolean; /** * Append additional header `field` with value `val`. * * @returns for chaining * @example * res.append("Link", ["<http://localhost/>", "<http://localhost:3000/>"]); * @example * res.append("Set-Cookie", "foo=bar; Path=/; HttpOnly"); * @example * res.append("Warning", "199 Miscellaneous warning"); */ append(field: string, value: string[] | string): this; /** * Set _Content-Disposition_ header to _attachment_ with optional `filename`. */ attachment(filename?: string): this; /** * Clear cookie `name`. * * @returns for chaining */ clearCookie(name: string, options?: Record<string, unknown>): this; /** * Set _Content-Type_ response header with `type` through `mime.lookup()` * when it does not contain "/", or set the Content-Type to `type` otherwise. * * @returns for chaining * @example * res.type(".html"); * @example * res.type("html"); * @example * res.type("json"); * @example * res.type("application/json"); * @example * res.type("png"); */ contentType(type: string): this; /** * Set cookie `name` to `value`, with the given `options`. * * Options: * - `maxAge` max-age in milliseconds, converted to `expires` * - `signed` sign the cookie * - `path` defaults to "/" * * @returns for chaining * @example * // "Remember Me" for 15 minutes * res.cookie("rememberme", "1", { expires: new Date(Date.now() + 900000), httpOnly: true }); * @example * // save as above * res.cookie("rememberme", "1", { maxAge: 900000, httpOnly: true }) */ cookie(name: string, value: Record<string, unknown> | number | string, options?: { [option: string]: any; maxAge?: number; path?: string; signed?: boolean; }): this; /** * Transfer the file at the given `path` as an attachment. * * Optionally providing an alternate attachment `filename`, * and optional callback `callback(err)`. The callback is invoked * when the data transfer is complete, or when an error has * ocurred. Be sure to check `res.headersSent` if you plan to respond. * * Optionally providing an `options` object to use with `res.sendFile()`. * This function will set the `Content-Disposition` header, overriding * any `Content-Disposition` header passed as header options in order * to set the attachment and filename. * * This method uses `res.sendFile()`. */ download(path: string, callback?: (...args: any[]) => void): void; download(path: string, filename: string, callback?: (...args: any[]) => void): void; download(path: string, filename: string, options: Record<string, unknown>, callback?: (...args: any[]) => void): void; /** * Respond to the Acceptable formats using an `obj` * of mime-type callbacks. * * This method uses `req.accepted`, an array of * acceptable types ordered by their quality values. * When "Accept" is not present the _first_ callback * is invoked, otherwise the first match is used. When * no match is performed the server responds with * 406 "Not Acceptable". * * By default Foxify passes an `Error` * with a `.status` of 406 to `next(err)` * if a match is not made. If you provide * a `.default` callback it will be invoked * instead. * * Content-Type is set for you, however if you choose * you may alter this within the callback using `res.type()` * or `res.set("Content-Type", ...)`. * * @returns for chaining * @example * res.format({ * "text/plain": function() { * res.send("hey"); * }, * "text/html": function() { * res.send("<p>hey</p>"); * }, * "appliation/json": function() { * res.send({ message: "hey" }); * } * }); * @example * // In addition to canonicalized MIME types you may * // also use extnames mapped to these types: * * res.format({ * text: function() { * res.send("hey"); * }, * html: function() { * res.send("<p>hey</p>"); * }, * json: function() { * res.send({ message: "hey" }); * } * }); */ format(types: Record<string, ((req: Request, res: Response, next: () => void) => void) | undefined>): this; /** * Set header `field` to `val`, or pass * an object of header fields. * * @returns for chaining * @example * res.set("Foo", ["bar", "baz"]); * @example * res.set("Accept", "application/json"); * @example * res.set({ Accept: "text/plain", "X-API-Key": "tobi" }); */ header<T extends string>(header: T, value: HeadersI[T] | number[]): this; header(headers: { [Header in string]: HeadersI[Header] | number[]; }): this; /** * Send JSON response. * * @example * res.json({ user: "tj" }); */ json(body: JsonT): this; /** * Send JSON response with JSONP callback support. * * @example * res.jsonp({ user: "tj" }); */ jsonp(body: JsonT): this; /** * Set Link header field with the given links. * * @example * res.links({ * next: "http://api.example.com/users?page=2", * last: "http://api.example.com/users?page=5" * }); */ links(links: Record<string, string>): this; /** * Set the location header to `url`. * * The given `url` can also be "back", which redirects * to the _Referrer_ or _Referer_ headers or "/". * * @returns for chaining * @example * res.location("back").; * @example * res.location("/foo/bar").; * @example * res.location("http://example.com"); * @example * res.location("../login"); */ location(url: string): this; /** * Redirect to the given `url` with optional response `status` * defaulting to 302. * * The resulting `url` is determined by `res.location()`, so * it will play nicely with mounted apps, relative paths, * `"back"` etc. * * @example * res.redirect("/foo/bar"); * @example * res.redirect("http://example.com"); * @example * res.redirect("http://example.com", 301); * @example * res.redirect("../login"); // /blog/post/1 -> /blog/login */ redirect(url: string, status?: StatusT): void; render(view: string, data?: EngineCallbackT | Record<string, unknown>, callback?: EngineCallbackT): void; /** * Send a response. * * @example * res.send(Buffer.from("wahoo")); * @example * res.send({ some: "json" }); * @example * res.send("<p>some html</p>"); */ send(body?: Buffer | JsonT | string): this; /** * Transfer the file at the given `path`. * * Automatically sets the _Content-Type_ response header field. * The callback `callback(err)` is invoked when the transfer is complete * or when an error occurs. Be sure to check `res.sentHeader` * if you wish to attempt responding, as the header and some data * may have already been transferred. * * Options: * - `maxAge` defaulting to 0 (can be string converted by `ms`) * - `root` root directory for relative filenames * - `headers` object of headers to serve with file * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them * * Other options are passed along to `send`. * * @example * // The following example illustrates how `res.sendFile()` may * // be used as an alternative for the `static()` middleware for * // dynamic situations. The code backing `res.sendFile()` is actually * // the same code, so HTTP cache support etc is identical. * * app.get("/user/:uid/photos/:file", function(req, res) { * let uid = req.params.uid; * let file = req.params.file; * * req.user.mayViewFilesFrom(uid, function(yes) { * if (yes) { * res.sendFile("/uploads/" + uid + "/" + file); * } else { * res.send(403, "Sorry! you cant see that."); * } * }); * }); */ sendFile(path: string, callback?: (...args: any[]) => void): void; sendFile(path: string, options: Record<string, unknown>, callback?: (...args: any[]) => void): void; /** * Send given HTTP status code. * * Sets the response status to `statusCode` and the body of the * response to the standard description from node's http.STATUS_CODES * or the statusCode number if no description. * * @example * res.sendStatus(200); */ sendStatus(statusCode: StatusT): this; /** * Set response status code. * * @example * res.status(500); */ status(statusCode: StatusT): this; /** * Add `field` to Vary. If already present in the Vary set, then * this call is simply ignored. * * @returns for chaining */ vary(field?: string[] | string): this; } export default Response; export declare function settings(settings?: Partial<SettingsI>): void; export interface HeadersI extends OutgoingHttpHeaders { "Content-Type"?: string; } export interface SettingsI { "json.escape": boolean; "json.spaces"?: number; "jsonp.callback": string; view?: Engine; etag?(body: Buffer | string, encoding?: BufferEncoding): string | undefined; "json.replacer"?(key: string, value: any): any; } //# sourceMappingURL=Response.d.ts.map