declarations
Version:
[](https://www.npmjs.com/package/declarations)
632 lines (599 loc) • 132 kB
TypeScript
// Type definitions for hapi 8.2.0
// Project: http://github.com/spumko/hapi
// Definitions by: Jason Swearingen <http://github.com/jasonswearingen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//This is a total rewrite of Hakubo's original hapi.d.ts, as it was out of date/incomplete.
/// <reference path="../node/node.d.ts" />
declare module "hapi" {
import http = require("http");
import stream = require("stream");
import Events = require("events");
interface IDictionary<T> {
[key: string]: T;
}
/** Boom Module for errors. https://github.com/hapijs/boom
* boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */
export interface IBoom extends Error {
/** if true, indicates this is a Boom object instance. */
isBoom: boolean;
/** convenience bool indicating status code >= 500. */
isServer: boolean;
/** the error message. */
message: string;
/** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */
output: {
/** the HTTP status code (typically 4xx or 5xx). */
statusCode: number;
/** an object containing any HTTP headers where each key is a header name and value is the header content. */
headers: IDictionary<string>;
/** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */
payload: {
/** the HTTP status code, derived from error.output.statusCode. */
statusCode: number;
/** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */
error: string;
/** the error message derived from error.message. */
message: string;
};
};
/** reformat()rebuilds error.output using the other object properties. */
reformat(): void;
}
/** cache functionality via the "CatBox" module. */
export interface ICatBoxCacheOptions {
/** a prototype function or catbox engine object. */
engine: any;
/** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */
name?: string;
/** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */
shared?: boolean;
}
/** Any connections configuration server defaults can be included to override and customize the individual connection. */
export interface ISeverConnectionOptions extends IConnectionConfigurationServerDefaults {
/** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/
host?: string;
/** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/
address?: string;
/** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/
port?: string|number;
/** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/
uri?: string;
/** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/
listener?: any;
/** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/
autoListen?: boolean;
/** caching headers configuration: */
cache?: {
/** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */
statuses: number[];
};
/** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/
labels?: string|string[];
/** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */
tls?: boolean;
}
export interface IConnectionConfigurationServerDefaults {
/** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */
app?: any;
/** connection load limits configuration where: */
load?: {
/** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxHeapUsedBytes: number;
/** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxRssBytes: number;
/** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxEventLoopDelay: number;
};
/** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */
plugins?: any;
/** controls how incoming request URIs are matched against the routing table: */
router?: {
/** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */
isCaseSensitive: boolean;
/** removes trailing slashes on incoming paths. Defaults to false. */
stripTrailingSlash: boolean;
};
/** a route options object used to set the default configuration for every route. */
routes?: IRouteAdditionalConfigurationOptions;
state?: IServerState;
}
/** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/
export interface IServerOptions {
/** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */
app?: any;
/** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned:
a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')).
a configuration object with the following options:
enginea prototype function or catbox engine object.
namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well.
sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false.
other options passed to the catbox strategy used.
an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */
cache?: string|ICatBoxCacheOptions|Array<ICatBoxCacheOptions>|any;
/** sets the default connections configuration which can be overridden by each connection where: */
connections?: IConnectionConfigurationServerDefaults;
/** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/
debug?: boolean|{
/** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */
log: string[];
/** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/
request: string[];
};
/** file system related settings*/
files?: {
/** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/
etagsCacheMaxSize?: number;
};
/** process load monitoring*/
load?: {
/** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/
sampleInterval?: number;
};
/** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/
mime?: any;
/** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */
minimal?: boolean;
/** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/
plugins?: IDictionary<any>;
}
export interface IServerViewCompile {
(template: string, options: any): void;
(template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void;
}
export interface IServerViewsAdditionalOptions {
/** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/
path?: string;
/**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path).
*/
partialsPath?: string;
/**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/
helpersPath?: string;
/**relativeTo - a base path used as prefix for path and partialsPath.No default.*/
relativeTo?: string;
/**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/
layout?: boolean;
/**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/
layoutPath?: string;
/**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/
layoutKeywork?: string;
/**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/
encoding?: string;
/**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/
isCached?: boolean;
/**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/
allowAbsolutePaths?: boolean;
/**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/
allowInsecureAccess?: boolean;
/**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/
compileOptions?: any;
/**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/
runtimeOptions?: any;
/**contentType - the content type of the engine results.Defaults to 'text/html'.*/
contentType?: string;
/**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/
compileMode?: string;
/**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/
context?: any;
}
export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions {
/**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings.
* If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/
module: {
compile? (template: any, options: any): (context: any, options: any) => void;
compile? (template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void;
};
}
/**Initializes the server views manager
var Hapi = require('hapi');
var server = new Hapi.Server();
server.views({
engines: {
html: require('handlebars'),
jade: require('jade')
},
path: '/static/templates'
});
When server.views() is called within a plugin, the views manager is only available to plugins methods.
*/
export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions {
/** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/
engines: IDictionary<any>|IServerViewsEnginesOptions;
/** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/
defaultExtension?: string;
}
interface IReplyMethods {
/** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200.
* The data argument is only used for passing back authentication data and is ignored elsewhere. */
continue(credentialData?: any): void;
/** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */
file(
/** the file path. */
path: string,
/** optional settings: */
options?: {
/** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/
filename?: string;
/** specifies whether to include the 'Content-Disposition' header with the response. Available values:
false - header is not included. This is the default value.
'attachment'
'inline'*/
mode?: boolean|string;
/** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */
lookupCompressed: boolean;
}): void;
/** Concludes the handler activity by returning control over to the router with a templatized view response.
the response flow control rules apply. */
view(
/** the template filename and path, relative to the templates path configured via the server views manager. */
template: string,
/** optional object used by the template to render context-specific result. Defaults to no context {}. */
context?: {},
/** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */
options?: any): Response;
/** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed
The response flow control rules do not apply. */
close(options?: {
/** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */
end?: boolean;
}): void;
/** Proxies the request to an upstream endpoint.
the response flow control rules do not apply. */
proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */
options: IProxyHandlerConfig): void;
/** Redirects the client to the specified uri. Same as calling reply().redirect(uri).
he response flow control rules apply. */
redirect(uri: string): Response;
}
/** Concludes the handler activity by setting a response and returning control over to the framework where:
erran optional error response.
resultan optional response payload.
Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first.
FLOW CONTROL:
When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */
export interface IReply extends IReplyMethods{
<T>(err: Error,
result?: string|number|boolean|Buffer|stream.Stream | Promise<T> | T,
/** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */
credentialData?: any
): IBoom;
/** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */
<T>(result?: string|number|boolean|Buffer|stream.Stream | Promise<T> | T): Response;
}
/** Concludes the handler activity by setting a response and returning control over to the framework where:
erran optional error response.
result an optional response payload.
Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first.
FLOW CONTROL:
When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */
export interface IStrictReply<T> extends IReplyMethods {
(err: Error,
result?: Promise<T> | T,
/** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */
credentialData?: any): IBoom;
/** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */
(result: Promise<T> | T): Response;
}
export interface ISessionHandler {
(request: Request, reply: IReply): void;
<T>(request: Request, reply: IStrictReply<T>): void;
}
export interface IRequestHandler<T> {
(request: Request): T;
}
export interface IFailAction {
(source: string, error: any, next: () => void): void
}
/** generates a reverse proxy handler */
export interface IProxyHandlerConfig {
/** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/
host?: string;
/** the upstream service port. */
port?: number;
/** The protocol to use when making a request to the proxied host:
'http'
'https'*/
protocol?: string;
/** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/
uri?: string;
/** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/
passThrough?: boolean;
/** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/
localStatePassThrough?: boolean;
/**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/
acceptEncoding?: boolean;
/** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/
rejectUnauthorized?: boolean;
/**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/
xforward?: boolean;
/** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/
redirects?: boolean|number;
/**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/
timeout?: number;
/** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where:
request - is the incoming request object.
callback - is function(err, uri, headers) where:
err - internal error condition.
uri - the absolute proxy URI.
headers - optional object where each key is an HTTP request header and the value is the header content.*/
mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void;
/** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/
onResponse?: (
err: any,
res: http.ServerResponse,
req: Request,
reply: () => void,
settings: IProxyHandlerConfig,
ttl: number
) => void;
/** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/
ttl?: number;
/** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */
agent?: http.Agent;
/** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/
maxSockets?: boolean|number;
}
/** TODO: fill in joi definition */
export interface IJoi {
}
/** a validation function using the signature function(value, options, next) */
export interface IValidationFunction {
(/** the object containing the path parameters. */
value: any,
/** the server validation options. */
options: any,
/** the callback function called when validation is completed. */
next: (err: any, value: any) => void): void;
}
/** a custom error handler function with the signature 'function(request, reply, source, error)` */
export interface IRouteFailFunction {
/** a custom error handler function with the signature 'function(request, reply, source, error)` */
(
/** - the [request object]. */
request: Request,
/** the continuation reply interface. */
reply: IReply,
/** the source of the invalid field (e.g. 'path', 'query', 'payload'). */
source: string,
/** the error object prepared for the client response (including the validation function error under error.data). */
error: any): void;
}
/** Each route can be customize to change the default behavior of the request lifecycle using the following options: */
export interface IRouteAdditionalConfigurationOptions {
/** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */
app?: any;
/** authentication configuration.Value can be: false to disable authentication if a default strategy is set.
a string with the name of an authentication strategy registered with server.auth.strategy().
an object */
auth?: boolean|string|
{
/** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values:
'required'authentication is required.
'optional'authentication is optional (must be valid if present).
'try'same as 'optional' but allows for invalid authentication. */
mode: string;
/** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */
strategies?: string | Array<string>;
strategy?: string;
/** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values:
falseno payload authentication.This is the default value.
'required'payload authentication required.This is the default value when the scheme sets options.payload to true.
'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */
payload?: string;
/** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */
scope?: string|Array<string>|boolean;
/** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values:
anythe authentication can be on behalf of a user or application.This is the default value.
userthe authentication must be on behalf of a user.
appthe authentication must be on behalf of an application. */
entity?: string;
};
/** an object passed back to the provided handler (via this) when called. */
bind?: any;
/** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */
cache?: {
/** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are:
fault'no privacy flag.This is the default setting.
'public'mark the response as suitable for public caching.
'private'mark the response as suitable only for private caching. */
privacy: string;
/** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */
expiresIn: number;
/** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */
expiresAt: string;
};
/** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */
cors?: {
/** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */
origin?: Array<string>;
/** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */
matchOrigin?: boolean;
/** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */
isOriginExposed?: boolean;
/** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */
maxAge?: number;
/** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */
headers?: string[];
/** a strings array of additional headers to headers.Use this to keep the default headers in place. */
additionalHeaders?: string[];
/** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */
methods?: string[];
/** a strings array of additional methods to methods.Use this to keep the default methods in place. */
additionalMethods?: string[];
/** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */
exposedHeaders?: string[];
/** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */
additionalExposedHeaders?: string[];
/** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */
credentials?: boolean;
/** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */
override?: boolean;
};
/** defines the behavior for serving static resources using the built-in route handlers for files and directories: */
files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */
relativeTo: string;
};
/** an alternative location for the route handler option. */
handler?: ISessionHandler | string | IRouteHandlerConfig;
/** an optional unique identifier used to look up the route using server.lookup(). */
id?: number;
/** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */
json?: {
/** the replacer function or array.Defaults to no action. */
replacer?: Function | string[];
/** number of spaces to indent nested object keys.Defaults to no indentation. */
space?: number|string;
/** string suffix added after conversion to JSON string.Defaults to no suffix. */
suffix?: string;
};
/** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */
jsonp?: string;
/** determines how the request payload is processed: */
payload?: {
/** the type of payload representation requested. The value must be one of:
'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used.
'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties.
'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */
output?: string;
/** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are:
'application/json'
'application/x-www-form-urlencoded'
'application/octet-stream'
'text/ *'
'multipart/form-data' */
parse?: string | boolean;
/** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */
allow?: string | string[];
/** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */
override?: string;
/** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */
maxBytes?: number;
/** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */
timeout?: number;
/** the directory used for writing file uploads.Defaults to os.tmpDir(). */
uploads?: string;
/** determines how to handle payload parsing errors. Allowed values are:
'error'return a Bad Request (400) error response. This is the default value.
'log'report the error but continue processing the request.
'ignore'take no action and continue processing the request. */
failAction?: string;
};
/** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */
plugins?: IDictionary<any>;
/** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */
pre?: any[];
/** validation rules for the outgoing response payload (response body).Can only validate object response: */
response?: {
/** the default response object validation rules (for all non-error responses) expressed as one of:
trueany payload allowed (no validation performed). This is the default.
falseno payload allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the response object.
optionsthe server validation options.
next(err)the callback function called when validation is completed. */
schema: boolean|any;
/** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */
status: number;
/** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */
sample: number;
/** defines what to do when a response fails validation.Options are:
errorreturn an Internal Server Error (500) error response.This is the default value.
loglog the error but send the response. */
failAction: string;
/** if true, applies the validation rule changes to the response.Defaults to false. */
modify: boolean;
/** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */
options: any;
};
/** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */
security?: boolean| {
/** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */
hsts: boolean|number|{
/** the max- age portion of the header, as a number.Default is 15768000. */
maxAge?: number;
/** a boolean specifying whether to add the includeSubdomains flag to the header. */
includeSubdomains?: boolean;
};
/** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */
xframe: {
/** either 'deny', 'sameorigin', or 'allow-from' */
rule: string;
/** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */
source: string;
};
/** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */
xss: boolean;
/** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */
noOpen: boolean;
/** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */
noSniff: boolean;
};
/** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */
state?: {
/** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */
parse: boolean;
/** determines how to handle cookie parsing errors.Allowed values are:
'error'return a Bad Request (400) error response.This is the default value.
'log'report the error but continue processing the request.
'ignore'take no action. */
failAction: string;
};
/** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */
validate?: {
/** validation rules for incoming request headers.Values allowed:
* trueany headers allowed (no validation performed).This is the default.
falseno headers allowed (this will cause all valid HTTP requests to fail).
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the request headers.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed.
*/
headers?: boolean | IJoi | IValidationFunction;
/** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed:
trueany path parameters allowed (no validation performed).This is the default.
falseno path variables allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the path parameters.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
params?: boolean | IJoi | IValidationFunction;
/** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed:
trueany query parameters allowed (no validation performed).This is the default.
falseno query parameters allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the query parameters.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
query?: boolean | IJoi | IValidationFunction;
/** validation rules for an incoming request payload (request body).Values allowed:
trueany payload allowed (no validation performed).This is the default.
falseno payload allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the payload object.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
payload?: boolean | IJoi | IValidationFunction;
/** an optional object with error fields copied into every validation error response. */
errorFields?: any;
/** determines how to handle invalid requests.Allowed values are:
'error'return a Bad Request (400) error response.This is the default value.
'log'log the error but continue processing the request.
'ignore'take no action.
OR a custom error handler function with the signature 'function(request, reply, source, error)` where:
requestthe request object.
replythe continuation reply interface.
sourcethe source of the invalid field (e.g. 'path', 'query', 'payload').
errorthe error object prepared for the client response (including the validation function error under error.data). */
failAction?: string | IRouteFailFunction;
/** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */
options?: any;
};
/** define timeouts for processing durations: */
timeout?: {
/** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */
server: boolean|number;
/** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves