encore.dev/api
Enumerations
ErrCode
Enumeration Members
Aborted
Aborted: "aborted"
Aborted indicates the operation was aborted, typically due to a concurrency issue like sequencer check failures, transaction aborts, etc.
See litmus test above for deciding between FailedPrecondition, Aborted, and Unavailable.
AlreadyExists
AlreadyExists: "already_exists"
AlreadyExists means an attempt to create an entity failed because one already exists.
This error code will not be generated by the gRPC framework.
Canceled
Canceled: "canceled"
Canceled indicates the operation was canceled (typically by the caller).
Encore will generate this error code when cancellation is requested.
DataLoss
DataLoss: "data_loss"
DataLoss indicates unrecoverable data loss or corruption.
This error code will not be generated by the gRPC framework.
DeadlineExceeded
DeadlineExceeded: "deadline_exceeded"
DeadlineExceeded means operation expired before completion. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire.
The gRPC framework will generate this error code when the deadline is exceeded.
FailedPrecondition
FailedPrecondition: "failed_precondition"
FailedPrecondition indicates operation was rejected because the system is not in a state required for the operation's execution. For example, directory to be deleted may be non-empty, an rmdir operation is applied to a non-directory, etc.
A litmus test that may help a service implementor in deciding between FailedPrecondition, Aborted, and Unavailable: (a) Use Unavailable if the client can retry just the failing call. (b) Use Aborted if the client should retry at a higher-level (e.g., restarting a read-modify-write sequence). (c) Use FailedPrecondition if the client should not retry until the system state has been explicitly fixed. E.g., if an "rmdir" fails because the directory is non-empty, FailedPrecondition should be returned since the client should not retry unless they have first fixed up the directory by deleting files from it. (d) Use FailedPrecondition if the client performs conditional REST Get/Update/Delete on a resource and the resource on the server does not match the condition. E.g., conflicting read-modify-write on the same resource.
This error code will not be generated by the gRPC framework.
Internal
Internal: "internal"
Internal errors. Means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken.
This error code will be generated by the gRPC framework in several internal error conditions.
InvalidArgument
InvalidArgument: "invalid_argument"
InvalidArgument indicates client specified an invalid argument. Note that this differs from FailedPrecondition. It indicates arguments that are problematic regardless of the state of the system (e.g., a malformed file name).
This error code will not be generated by the gRPC framework.
NotFound
NotFound: "not_found"
NotFound means some requested entity (e.g., file or directory) was not found.
This error code will not be generated by the gRPC framework.
OK
OK: "ok"
OK indicates the operation was successful.
OutOfRange
OutOfRange: "out_of_range"
OutOfRange means operation was attempted past the valid range. E.g., seeking or reading past end of file.
Unlike InvalidArgument, this error indicates a problem that may be fixed if the system state changes. For example, a 32-bit file system will generate InvalidArgument if asked to read at an offset that is not in the range [0,2^32-1], but it will generate OutOfRange if asked to read from an offset past the current file size.
There is a fair bit of overlap between FailedPrecondition and OutOfRange. We recommend using OutOfRange (the more specific error) when it applies so that callers who are iterating through a space can easily look for an OutOfRange error to detect when they are done.
This error code will not be generated by the gRPC framework.
PermissionDenied
PermissionDenied: "permission_denied"
PermissionDenied indicates the caller does not have permission to execute the specified operation. It must not be used for rejections caused by exhausting some resource (use ResourceExhausted instead for those errors). It must not be used if the caller cannot be identified (use Unauthenticated instead for those errors).
This error code will not be generated by the gRPC core framework, but expect authentication middleware to use it.
ResourceExhausted
ResourceExhausted: "resource_exhausted"
ResourceExhausted indicates some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space.
This error code will be generated by the gRPC framework in out-of-memory and server overload situations, or when a message is larger than the configured maximum size.
Unauthenticated
Unauthenticated: "unauthenticated"
Unauthenticated indicates the request does not have valid authentication credentials for the operation.
The gRPC framework will generate this error code when the authentication metadata is invalid or a Credentials callback fails, but also expect authentication middleware to generate it.
Unavailable
Unavailable: "unavailable"
Unavailable indicates the service is currently unavailable. This is a most likely a transient condition and may be corrected by retrying with a backoff. Note that it is not always safe to retry non-idempotent operations.
See litmus test above for deciding between FailedPrecondition, Aborted, and Unavailable.
This error code will be generated by the gRPC framework during abrupt shutdown of a server process or network connection.
Unimplemented
Unimplemented: "unimplemented"
Unimplemented indicates operation is not implemented or not supported/enabled in this service.
This error code will be generated by the gRPC framework. Most commonly, you will see this error code when a method implementation is missing on the server. It can also be generated for unknown compression algorithms or a disagreement as to whether an RPC should be streaming.
Unknown
Unknown: "unknown"
Unknown error. An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known in this address space. Also errors raised by APIs that do not return enough error information may be converted to this error.
Encore will generate this error code in the above two mentioned cases.
Classes
APIError
Extends
Error
Constructors
Constructor
new APIError(
code,
msg,
cause?,
details?): APIError;
Constructs an APIError with the given error code, message, and (optionally) cause.
Parameters
code
msg
string
cause?
Error
details?
Returns
Overrides
Error.constructor
Properties
code
readonly code: ErrCode
The error code.
details?
readonly optional details?: ErrDetails
Methods
withDetails()
withDetails(details): APIError
Constructs a new APIError from the previous one with the provided details
Parameters
details
Returns
aborted()
static aborted(msg, cause?): APIError
Constructs an APIError with the Aborted error code.
Parameters
msg
string
cause?
Error
Returns
alreadyExists()
static alreadyExists(msg, cause?): APIError
Constructs an APIError with the AlreadyExists error code.
Parameters
msg
string
cause?
Error
Returns
canceled()
static canceled(msg, cause?): APIError
Constructs an APIError with the Canceled error code.
Parameters
msg
string
cause?
Error
Returns
dataLoss()
static dataLoss(msg, cause?): APIError
Constructs an APIError with the DataLoss error code.
Parameters
msg
string
cause?
Error
Returns
deadlineExceeded()
static deadlineExceeded(msg, cause?): APIError
Constructs an APIError with the DeadlineExceeded error code.
Parameters
msg
string
cause?
Error
Returns
failedPrecondition()
static failedPrecondition(msg, cause?): APIError
Constructs an APIError with the FailedPrecondition error code.
Parameters
msg
string
cause?
Error
Returns
internal()
static internal(msg, cause?): APIError
Constructs an APIError with the Internal error code.
Parameters
msg
string
cause?
Error
Returns
invalidArgument()
static invalidArgument(msg, cause?): APIError
Constructs an APIError with the InvalidArgument error code.
Parameters
msg
string
cause?
Error
Returns
notFound()
static notFound(msg, cause?): APIError
Constructs an APIError with the NotFound error code.
Parameters
msg
string
cause?
Error
Returns
outOfRange()
static outOfRange(msg, cause?): APIError
Constructs an APIError with the OutOfRange error code.
Parameters
msg
string
cause?
Error
Returns
permissionDenied()
static permissionDenied(msg, cause?): APIError
Constructs an APIError with the PermissionDenied error code.
Parameters
msg
string
cause?
Error
Returns
resourceExhausted()
static resourceExhausted(msg, cause?): APIError
Constructs an APIError with the ResourceExhausted error code.
Parameters
msg
string
cause?
Error
Returns
unauthenticated()
static unauthenticated(msg, cause?): APIError
Constructs an APIError with the Unauthenticated error code.
Parameters
msg
string
cause?
Error
Returns
unavailable()
static unavailable(msg, cause?): APIError
Constructs an APIError with the Unavailable error code.
Parameters
msg
string
cause?
Error
Returns
unimplemented()
static unimplemented(msg, cause?): APIError
Constructs an APIError with the Unimplemented error code.
Parameters
msg
string
cause?
Error
Returns
unknown()
static unknown(msg, cause?): APIError
Constructs an APIError with the Unknown error code.
Parameters
msg
string
cause?
Error
Returns
Gateway
Constructors
Constructor
new Gateway(cfg): Gateway
Parameters
cfg
Returns
Properties
cfg
readonly cfg: GatewayConfig
name
readonly name: string
HandlerResponse
Constructors
Constructor
new HandlerResponse(payload): HandlerResponse
Parameters
payload
any
Returns
Properties
payload
payload: any
The payload returned by the handler when the handler is either a typed handler or stream handler.
Accessors
header
Get Signature
get header(): ResponseHeader
header can be used by middlewares to set headers to the response. This only works for typed handler. For raw handlers see MiddlewareRequest.rawResponse.
Returns
status
Set Signature
set status(s): void
Override the http status code for successful requests for typed endpoints.
Parameters
s
number
Returns
void
IterableSocket
Constructors
Constructor
new IterableSocket(socket): IterableSocket
Parameters
socket
Socket
Returns
Methods
[asyncIterator]()
asyncIterator: AsyncGenerator<any, void, unknown>
Returns
AsyncGenerator\<any, void, unknown>
close()
close(): void
Returns
void
recv()
recv(): Promise<Record<string, any>>
Returns
Promise\<Record\<string, any>>
send()
send(msg): void
Parameters
msg
Record\<string, any>
Returns
void
IterableStream
Constructors
Constructor
new IterableStream(stream): IterableStream
Parameters
stream
Stream
Returns
Methods
[asyncIterator]()
asyncIterator: AsyncGenerator<any, void, unknown>
Returns
AsyncGenerator\<any, void, unknown>
recv()
recv(): Promise<Record<string, any>>
Returns
Promise\<Record\<string, any>>
MiddlewareRequest
Constructors
Constructor
new MiddlewareRequest(
stream?,
rawReq?,
rawResp?): MiddlewareRequest;
Parameters
stream?
| IterableStream
| IterableSocket
| Sink
rawReq?
rawResp?
Returns
Accessors
data
Get Signature
get data(): Record<string, any>
data can be used to pass data from middlewares to the handler.
The data will be available via currentRequest()
Returns
Record\<string, any>
rawRequest
Get Signature
get rawRequest(): RawRequest | undefined
rawRequest is set when the handler is a raw request handler.
The returned value is a Node.js http.IncomingMessage.
Returns
RawRequest | undefined
rawResponse
Get Signature
get rawResponse(): RawResponse | undefined
rawResponse is set when the handler is a raw request handler.
The returned value is a Node.js http.ServerResponse.
Returns
RawResponse | undefined
requestMeta
Get Signature
get requestMeta(): RequestMeta | undefined
requestMeta is set when the handler is a typed handler or a stream handler. for raw handlers, see rawRequest and rawResponse.
Returns
RequestMeta | undefined
stream
Get Signature
get stream():
| IterableStream
| IterableSocket
| Sink
| undefined;
stream is set when the handler is a stream handler.
Returns
| IterableStream
| IterableSocket
| Sink
| undefined
RawRequest
Extends
Readable
Constructors
Constructor
new RawRequest(req, body): RawRequest
Parameters
req
Request
body
BodyReader
Returns
Overrides
stream.Readable.constructor
Properties
_headersDistinct
_headersDistinct: Dict<string[]> | undefined
_rawHeaders
_rawHeaders: string[] | undefined
_url
_url: string | undefined
complete
complete: boolean
connection
readonly connection: Socket | null
rawTrailers
rawTrailers: string[]
socket
readonly socket: Socket | null
trailers
trailers: Dict<string>
trailersDistinct
trailersDistinct: Dict<string[]>
Accessors
headers
Get Signature
get headers(): IncomingHttpHeaders
Returns
IncomingHttpHeaders
headersDistinct
Get Signature
get headersDistinct(): Dict<string[]>
Returns
Dict\<string[]>
method
Get Signature
get method(): string
Returns
string
rawHeaders
Get Signature
get rawHeaders(): string[]
Returns
string[]
url
Get Signature
get url(): string
Returns
string
Set Signature
set url(value): void
Parameters
value
string
Returns
void
Methods
_read()
_read(size): void
Parameters
size
number
Returns
void
Overrides
stream.Readable._read
setTimeout()
setTimeout(msecs, callback?): this
Parameters
msecs
number
callback?
() => void
Returns
this
RawResponse
Extends
Writable
Constructors
Constructor
new RawResponse(req, w): RawResponse
Parameters
req
w
ResponseWriter
Returns
Overrides
stream.Writable.constructor
Properties
chunkedEncoding
chunkedEncoding: boolean
connection
readonly connection: Socket | null
finished
finished: boolean
headersSent
headersSent: boolean
req
readonly req: RawRequest
sendDate
sendDate: boolean
shouldKeepAlive
shouldKeepAlive: boolean
socket
readonly socket: Socket | null
statusCode
statusCode: number
statusMessage
statusMessage: string | undefined
strictContentLength
strictContentLength: boolean
Methods
_final()
_final(callback): void
Parameters
callback
(error?) => void
Returns
void
Overrides
stream.Writable._final
_implicitHeader()
_implicitHeader(): void
Returns
void
_write()
_write(
chunk,
_encoding,
callback): void;
Parameters
chunk
Buffer
_encoding
BufferEncoding
callback
(error?) => void
Returns
void
Overrides
stream.Writable._write
_writeHeaderIfNeeded()
_writeHeaderIfNeeded(): void
Returns
void
_writev()
_writev(chunks, callback): void
Parameters
chunks
{
chunk: Buffer;
}[]
callback
(error?) => void
Returns
void
Overrides
stream.Writable._writev
addTrailers()
addTrailers(headers): void
Parameters
headers
OutgoingHttpHeaders | readonly [string, string][]
Returns
void
appendHeader()
appendHeader(name, value): this
Parameters
name
string
value
string | number | string[]
Returns
this
flushHeaders()
flushHeaders(): void
Returns
void
getHeader()
getHeader(name): string | number | string[] | undefined
Parameters
name
string
Returns
string | number | string[] | undefined
getHeaderNames()
getHeaderNames(): string[]
Returns
string[]
getHeaders()
getHeaders(): OutgoingHttpHeaders
Returns
OutgoingHttpHeaders
hasHeader()
hasHeader(name): boolean
Parameters
name
string
Returns
boolean
removeHeader()
removeHeader(name): void
Parameters
name
string
Returns
void
setHeader()
setHeader(name, value): this
Parameters
name
string
value
string | number | string[]
Returns
this
setTimeout()
setTimeout(msecs, callback?): this
Parameters
msecs
number
callback?
() => void
Returns
this
write()
Call Signature
write(chunk, callback?): boolean
The writable.write() method writes some data to the stream, and calls the
supplied callback once the data has been fully handled. If an error
occurs, the callback will be called with the error as its
first argument. The callback is called asynchronously and before 'error' is
emitted.
The return value is true if the internal buffer is less than thehighWaterMark configured when the stream was created after admitting chunk.
If false is returned, further attempts to write data to the stream should
stop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and
return false. Once all currently buffered chunks are drained (accepted for
delivery by the operating system), the 'drain' event will be emitted.
Once write() returns false, do not write more chunks
until the 'drain' event is emitted. While calling write() on a stream that
is not draining is allowed, Node.js will buffer all written chunks until
maximum memory usage occurs, at which point it will abort unconditionally.
Even before it aborts, high memory usage will cause poor garbage collector
performance and high RSS (which is not typically released back to the system,
even after the memory is no longer required). Since TCP sockets may never
drain if the remote peer does not read the data, writing a socket that is
not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
problematic for a Transform, because the Transform streams are paused
by default until they are piped or a 'data' or 'readable' event handler
is added.
If the data to be written can be generated or fetched on demand, it is
recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is
possible to respect backpressure and avoid memory issues using the 'drain' event:
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
A Writable stream in object mode will always ignore the encoding argument.
Parameters
chunk
any
Optional data to write. For streams not operating in object mode, chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
JavaScript value other than null.
callback?
(error) => void
Callback for when this chunk of data is flushed.
Returns
boolean
false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.
Since
v0.9.4
Overrides
stream.Writable.write
Call Signature
write(
chunk,
encoding,
callback?): boolean;
Parameters
chunk
any
encoding
BufferEncoding
callback?
(error) => void
Returns
boolean
Overrides
stream.Writable.write
writeHead()
Call Signature
writeHead(statusCode, headers?): this
Parameters
statusCode
number
headers?
OutgoingHttpHeaders | OutgoingHttpHeader[]
Returns
this
Call Signature
writeHead(
statusCode,
statusMessage?,
headers?): this;
Parameters
statusCode
number
statusMessage?
string
headers?
OutgoingHttpHeaders | OutgoingHttpHeader[]
Returns
this
ResponseHeader
Constructors
Constructor
new ResponseHeader(): ResponseHeader
Returns
Properties
headers
headers: Record<string, string | string[]>
Methods
add()
add(key, value): void
add adds a header value to a key, if a previous middleware has already set a value, they will be appended.
Parameters
key
string
value
string | string[]
Returns
void
set()
set(key, value): void
set will set a header value for a key, if a previous middleware has already set a value, it will be overridden.
Parameters
key
string
value
string | string[]
Returns
void
Sink
Constructors
Constructor
new Sink(sink): Sink
Parameters
sink
Sink
Returns
Methods
close()
close(): void
Returns
void
send()
send(msg): void
Parameters
msg
Record\<string, any>
Returns
void
StaticAssets
Constructors
Constructor
new StaticAssets(options): StaticAssets
Parameters
options
Returns
Properties
options
readonly options: StaticOptions
Interfaces
APIOptions
Properties
auth?
optional auth?: boolean
Whether or not the request must contain valid authentication credentials. If set to true and the request is not authenticated, Encore returns a 401 Unauthorized error.
Defaults to false if not specified.
bodyLimit?
optional bodyLimit?: number | null
The maximum body size, in bytes. If the request body exceeds this value, Encore stops request processing and returns an error.
If left unspecified it defaults to a reasonable default (currently 2MiB).
If set to null, the body size is unlimited.
expose?
optional expose?: boolean
Whether or not to make this endpoint publicly accessible. If false, the endpoint is only accessible from the internal network.
Defaults to false if not specified.
method?
optional method?: Method | Method[] | "*"
The HTTP method(s) to match for this endpoint. Use "*" to match any method.
path?
optional path?: string
The request path to match for this endpoint.
Use : to define single-segment parameters, e.g. /users/:id.
Use * to match any number of segments, e.g. /files/*path.
If not specified, it defaults to /<service-name>.<endpoint-name>.
sensitive?
optional sensitive?: boolean
When set to true, request information such as payloads and headers will be excluded from traces.
tags?
optional tags?: string[]
Tags to filter endpoints when generating clients and in middlewares.
CallOpts
Options when making api calls.
This interface will be extended with additional fields from app's generated code.
GatewayConfig
Properties
authHandler?
optional authHandler?: AuthHandlerBrand
Middleware()
Extends
Middleware(req, next): Promise<HandlerResponse>
Parameters
req
next
Returns
Promise\<HandlerResponse>
Properties
options?
optional options?: MiddlewareOptions
MiddlewareOptions
Properties
target?
optional target?: {
auth?: boolean;
expose?: boolean;
isRaw?: boolean;
isStream?: boolean;
tags?: string[];
};
Configuration for what endpoints that should be targeted by the middleware
auth?
optional auth?: boolean
If set, only run middleware on endpoints that either require or not requires auth.
expose?
optional expose?: boolean
If set, only run middleware on endpoints that are either exposed or not exposed.
isRaw?
optional isRaw?: boolean
If set, only run middleware on endpoints that are raw endpoints.
isStream?
optional isStream?: boolean
If set, only run middleware on endpoints that are stream endpoints.
tags?
optional tags?: string[]
If set, only run middleware on endpoints that have specific tags. These tags are evaluated with OR, meaning the middleware applies to an API if the API has at least one of those tags.
StaticOptions
Properties
auth?
optional auth?: boolean
Whether or not the request must contain valid authentication credentials. If set to true and the request is not authenticated, Encore returns a 401 Unauthorized error.
Defaults to false if not specified.
dir
dir: string
The relative path to the directory containing the static files to serve.
The provided path must be a subdirectory from the calling file's directory.
expose?
optional expose?: boolean
Whether or not to make this endpoint publicly accessible. If false, the endpoint is only accessible from the internal network.
Defaults to false if not specified.
headers?
optional headers?: Record<string, string | string[]>
Custom HTTP headers to apply to all static files served.
Example
headers: {
"Cache-Control": "public, max-age=3600",
"X-Content-Type-Options": "nosniff",
}
notFound?
optional notFound?: string
Path to the file to serve when the requested file is not found. The path must be a relative path to within the calling file's directory.
notFoundStatus?
optional notFoundStatus?: number
Http Status code used when serving notFound fallback. Defaults to 404.
path?
optional path?: string
The request path to match for this endpoint.
Use : to define single-segment parameters, e.g. /users/:id.
Use * to match any number of segments, e.g. /files/*path.
If not specified, it defaults to /<service-name>.<endpoint-name>.
StreamIn
Extends
AsyncIterable\<Request>
Type Parameters
Request
Request
Properties
recv
recv: () => Promise<Request>
Returns
Promise\<Request>
StreamOptions
Properties
auth?
optional auth?: boolean
Whether or not the request must contain valid authentication credentials. If set to true and the request is not authenticated, Encore returns a 401 Unauthorized error.
Defaults to false if not specified.
expose?
optional expose?: boolean
Whether or not to make this endpoint publicly accessible. If false, the endpoint is only accessible from the internal network.
Defaults to false if not specified.
path?
optional path?: string
The request path to match for this endpoint.
Use : to define single-segment parameters, e.g. /users/:id.
Use * to match any number of segments, e.g. /files/*path.
If not specified, it defaults to /<service-name>.<endpoint-name>.
sensitive?
optional sensitive?: boolean
When set to true, request information such as payloads and headers will be excluded from traces.
tags?
optional tags?: string[]
Tags to filter endpoints when generating clients and in middlewares.
StreamOut
Extended by
Type Parameters
Response
Response
Properties
close
close: () => Promise<void>
Returns
Promise\<void>
send
send: (msg) => Promise<void>
Parameters
msg
Response
Returns
Promise\<void>
StreamOutWithResponse
Extends
StreamOut\<Request>
Type Parameters
Request
Request
Response
Response
Properties
close
close: () => Promise<void>
Returns
Promise\<void>
Inherited from
response
response: () => Promise<Response>
Returns
Promise\<Response>
send
send: (msg) => Promise<void>
Parameters
msg
Request
Returns
Promise\<void>
Inherited from
Type Aliases
Cookie
type Cookie<TypeOrName, Name> = TypeOrName extends string ? CookieWithOptions<string> : CookieWithOptions<TypeOrName>
Type Parameters
TypeOrName
TypeOrName extends string | number | boolean | Date = string
Name
Name extends string = ""
CookieWithOptions
type CookieWithOptions<T> = {
domain?: string;
expires?: Date;
httpOnly?: boolean;
maxAge?: number;
partitioned?: boolean;
path?: string;
sameSite?: "Strict" | "Lax" | "None";
secure?: boolean;
value: T;
};
Type Parameters
T
T
Properties
domain?
optional domain?: string
expires?
optional expires?: Date
httpOnly?
optional httpOnly?: boolean
maxAge?
optional maxAge?: number
partitioned?
optional partitioned?: boolean
path?
optional path?: string
sameSite?
optional sameSite?: "Strict" | "Lax" | "None"
secure?
optional secure?: boolean
value
value: T
ErrDetails
type ErrDetails = Record<string, any>
Additional structured error details that can be attached to an APIError.
Header
type Header<TypeOrName, Name> = TypeOrName extends string ? string : TypeOrName
Type Parameters
TypeOrName
TypeOrName extends string | number | boolean | Date = string
Name
Name extends string = ""
HttpStatus
type HttpStatus = typeof HttpStatusValues[keyof typeof HttpStatusValues]
The union of all HTTP status code numeric values.
Method
type Method =
| "GET"
| "POST"
| "PUT"
| "DELETE"
| "PATCH"
| "HEAD"
| "OPTIONS"
| "TRACE"
| "CONNECT";
MiddlewareFn
type MiddlewareFn = (req, next) => Promise<HandlerResponse>
Parameters
req
next
Returns
Promise\<HandlerResponse>
Next
type Next = (req) => Promise<HandlerResponse>
Parameters
req
Returns
Promise\<HandlerResponse>
Query
type Query<TypeOrName, Name> = TypeOrName extends string ? string : TypeOrName
Type Parameters
TypeOrName
TypeOrName extends string | string[] | number | number[] | boolean | boolean[] | Date | Date[] = string
Name
Name extends string = ""
RawHandler
type RawHandler = (req, resp) => void
Parameters
req
IncomingMessage
resp
ServerResponse
Returns
void
StreamInHandlerFn
type StreamInHandlerFn<HandshakeData, Request, Response> = HandshakeData extends void ? (stream) => Promise<Response> : (data, stream) => Promise<Response>
Type Parameters
HandshakeData
HandshakeData
Request
Request
Response
Response
StreamInOut
type StreamInOut<Request, Response> = StreamIn<Request> & StreamOut<Response>
Type Parameters
Request
Request
Response
Response
StreamInOutHandlerFn
type StreamInOutHandlerFn<HandshakeData, Request, Response> = HandshakeData extends void ? (stream) => Promise<void> : (data, stream) => Promise<void>
Type Parameters
HandshakeData
HandshakeData
Request
Request
Response
Response
StreamOutHandlerFn
type StreamOutHandlerFn<HandshakeData, Response> = HandshakeData extends void ? (stream) => Promise<void> : (data, stream) => Promise<void>
Type Parameters
HandshakeData
HandshakeData
Response
Response
Variables
HttpStatus
const HttpStatus: {
Accepted: 202;
AlreadyReported: 208;
BadGateway: 502;
BadRequest: 400;
Conflict: 409;
Continue: 100;
Created: 201;
EarlyHints: 103;
ExpectationFailed: 417;
FailedDependency: 424;
Forbidden: 403;
Found: 302;
GatewayTimeout: 504;
Gone: 410;
HTTPVersionNotSupported: 505;
ImATeapot: 418;
IMUsed: 226;
InsufficientStorage: 507;
InternalServerError: 500;
LengthRequired: 411;
Locked: 423;
LoopDetected: 508;
MethodNotAllowed: 405;
MisdirectedRequest: 421;
MovedPermanently: 301;
MultipleChoices: 300;
MultiStatus: 207;
NetworkAuthenticationRequired: 511;
NoContent: 204;
NonAuthoritativeInformation: 203;
NotAcceptable: 406;
NotExtended: 510;
NotFound: 404;
NotImplemented: 501;
NotModified: 304;
OK: 200;
PartialContent: 206;
PayloadTooLarge: 413;
PaymentRequired: 402;
PermanentRedirect: 308;
PreconditionFailed: 412;
PreconditionRequired: 428;
Processing: 102;
ProxyAuthenticationRequired: 407;
RangeNotSatisfiable: 416;
RequestHeaderFieldsTooLarge: 431;
RequestTimeout: 408;
ResetContent: 205;
SeeOther: 303;
ServiceUnavailable: 503;
SwitchingProtocols: 101;
SwitchProxy: 306;
TemporaryRedirect: 307;
TooEarly: 425;
TooManyRequests: 429;
Unauthorized: 401;
UnavailableForLegalReasons: 451;
UnprocessableEntity: 422;
UnsupportedMediaType: 415;
UpgradeRequired: 426;
URITooLong: 414;
UseProxy: 305;
VariantAlsoNegotiates: 506;
} = HttpStatusValues;
A map of HTTP status code names to their numeric values.
Type Declaration
Accepted
readonly Accepted: 202 = 202
AlreadyReported
readonly AlreadyReported: 208 = 208
BadGateway
readonly BadGateway: 502 = 502
BadRequest
readonly BadRequest: 400 = 400
Conflict
readonly Conflict: 409 = 409
Continue
readonly Continue: 100 = 100
Created
readonly Created: 201 = 201
EarlyHints
readonly EarlyHints: 103 = 103
ExpectationFailed
readonly ExpectationFailed: 417 = 417
FailedDependency
readonly FailedDependency: 424 = 424
Forbidden
readonly Forbidden: 403 = 403
Found
readonly Found: 302 = 302
GatewayTimeout
readonly GatewayTimeout: 504 = 504
Gone
readonly Gone: 410 = 410
HTTPVersionNotSupported
readonly HTTPVersionNotSupported: 505 = 505
ImATeapot
readonly ImATeapot: 418 = 418
IMUsed
readonly IMUsed: 226 = 226
InsufficientStorage
readonly InsufficientStorage: 507 = 507
InternalServerError
readonly InternalServerError: 500 = 500
LengthRequired
readonly LengthRequired: 411 = 411
Locked
readonly Locked: 423 = 423
LoopDetected
readonly LoopDetected: 508 = 508
MethodNotAllowed
readonly MethodNotAllowed: 405 = 405
MisdirectedRequest
readonly MisdirectedRequest: 421 = 421
MovedPermanently
readonly MovedPermanently: 301 = 301
MultipleChoices
readonly MultipleChoices: 300 = 300
MultiStatus
readonly MultiStatus: 207 = 207
NetworkAuthenticationRequired
readonly NetworkAuthenticationRequired: 511 = 511
NoContent
readonly NoContent: 204 = 204
NonAuthoritativeInformation
readonly NonAuthoritativeInformation: 203 = 203
NotAcceptable
readonly NotAcceptable: 406 = 406
NotExtended
readonly NotExtended: 510 = 510
NotFound
readonly NotFound: 404 = 404
NotImplemented
readonly NotImplemented: 501 = 501
NotModified
readonly NotModified: 304 = 304
OK
readonly OK: 200 = 200
PartialContent
readonly PartialContent: 206 = 206
PayloadTooLarge
readonly PayloadTooLarge: 413 = 413
PaymentRequired
readonly PaymentRequired: 402 = 402
PermanentRedirect
readonly PermanentRedirect: 308 = 308
PreconditionFailed
readonly PreconditionFailed: 412 = 412
PreconditionRequired
readonly PreconditionRequired: 428 = 428
Processing
readonly Processing: 102 = 102
ProxyAuthenticationRequired
readonly ProxyAuthenticationRequired: 407 = 407
RangeNotSatisfiable
readonly RangeNotSatisfiable: 416 = 416
RequestHeaderFieldsTooLarge
readonly RequestHeaderFieldsTooLarge: 431 = 431
RequestTimeout
readonly RequestTimeout: 408 = 408
ResetContent
readonly ResetContent: 205 = 205
SeeOther
readonly SeeOther: 303 = 303
ServiceUnavailable
readonly ServiceUnavailable: 503 = 503
SwitchingProtocols
readonly SwitchingProtocols: 101 = 101
SwitchProxy
readonly SwitchProxy: 306 = 306
TemporaryRedirect
readonly TemporaryRedirect: 307 = 307
TooEarly
readonly TooEarly: 425 = 425
TooManyRequests
readonly TooManyRequests: 429 = 429
Unauthorized
readonly Unauthorized: 401 = 401
UnavailableForLegalReasons
readonly UnavailableForLegalReasons: 451 = 451
UnprocessableEntity
readonly UnprocessableEntity: 422 = 422
UnsupportedMediaType
readonly UnsupportedMediaType: 415 = 415
UpgradeRequired
readonly UpgradeRequired: 426 = 426
URITooLong
readonly URITooLong: 414 = 414
UseProxy
readonly UseProxy: 305 = 305
VariantAlsoNegotiates
readonly VariantAlsoNegotiates: 506 = 506
HttpStatusValues
const HttpStatusValues: {
Accepted: 202;
AlreadyReported: 208;
BadGateway: 502;
BadRequest: 400;
Conflict: 409;
Continue: 100;
Created: 201;
EarlyHints: 103;
ExpectationFailed: 417;
FailedDependency: 424;
Forbidden: 403;
Found: 302;
GatewayTimeout: 504;
Gone: 410;
HTTPVersionNotSupported: 505;
ImATeapot: 418;
IMUsed: 226;
InsufficientStorage: 507;
InternalServerError: 500;
LengthRequired: 411;
Locked: 423;
LoopDetected: 508;
MethodNotAllowed: 405;
MisdirectedRequest: 421;
MovedPermanently: 301;
MultipleChoices: 300;
MultiStatus: 207;
NetworkAuthenticationRequired: 511;
NoContent: 204;
NonAuthoritativeInformation: 203;
NotAcceptable: 406;
NotExtended: 510;
NotFound: 404;
NotImplemented: 501;
NotModified: 304;
OK: 200;
PartialContent: 206;
PayloadTooLarge: 413;
PaymentRequired: 402;
PermanentRedirect: 308;
PreconditionFailed: 412;
PreconditionRequired: 428;
Processing: 102;
ProxyAuthenticationRequired: 407;
RangeNotSatisfiable: 416;
RequestHeaderFieldsTooLarge: 431;
RequestTimeout: 408;
ResetContent: 205;
SeeOther: 303;
ServiceUnavailable: 503;
SwitchingProtocols: 101;
SwitchProxy: 306;
TemporaryRedirect: 307;
TooEarly: 425;
TooManyRequests: 429;
Unauthorized: 401;
UnavailableForLegalReasons: 451;
UnprocessableEntity: 422;
UnsupportedMediaType: 415;
UpgradeRequired: 426;
URITooLong: 414;
UseProxy: 305;
VariantAlsoNegotiates: 506;
};
Type Declaration
Accepted
readonly Accepted: 202 = 202
AlreadyReported
readonly AlreadyReported: 208 = 208
BadGateway
readonly BadGateway: 502 = 502
BadRequest
readonly BadRequest: 400 = 400
Conflict
readonly Conflict: 409 = 409
Continue
readonly Continue: 100 = 100
Created
readonly Created: 201 = 201
EarlyHints
readonly EarlyHints: 103 = 103
ExpectationFailed
readonly ExpectationFailed: 417 = 417
FailedDependency
readonly FailedDependency: 424 = 424
Forbidden
readonly Forbidden: 403 = 403
Found
readonly Found: 302 = 302
GatewayTimeout
readonly GatewayTimeout: 504 = 504
Gone
readonly Gone: 410 = 410
HTTPVersionNotSupported
readonly HTTPVersionNotSupported: 505 = 505
ImATeapot
readonly ImATeapot: 418 = 418
IMUsed
readonly IMUsed: 226 = 226
InsufficientStorage
readonly InsufficientStorage: 507 = 507
InternalServerError
readonly InternalServerError: 500 = 500
LengthRequired
readonly LengthRequired: 411 = 411
Locked
readonly Locked: 423 = 423
LoopDetected
readonly LoopDetected: 508 = 508
MethodNotAllowed
readonly MethodNotAllowed: 405 = 405
MisdirectedRequest
readonly MisdirectedRequest: 421 = 421
MovedPermanently
readonly MovedPermanently: 301 = 301
MultipleChoices
readonly MultipleChoices: 300 = 300
MultiStatus
readonly MultiStatus: 207 = 207
NetworkAuthenticationRequired
readonly NetworkAuthenticationRequired: 511 = 511
NoContent
readonly NoContent: 204 = 204
NonAuthoritativeInformation
readonly NonAuthoritativeInformation: 203 = 203
NotAcceptable
readonly NotAcceptable: 406 = 406
NotExtended
readonly NotExtended: 510 = 510
NotFound
readonly NotFound: 404 = 404
NotImplemented
readonly NotImplemented: 501 = 501
NotModified
readonly NotModified: 304 = 304
OK
readonly OK: 200 = 200
PartialContent
readonly PartialContent: 206 = 206
PayloadTooLarge
readonly PayloadTooLarge: 413 = 413
PaymentRequired
readonly PaymentRequired: 402 = 402
PermanentRedirect
readonly PermanentRedirect: 308 = 308
PreconditionFailed
readonly PreconditionFailed: 412 = 412
PreconditionRequired
readonly PreconditionRequired: 428 = 428
Processing
readonly Processing: 102 = 102
ProxyAuthenticationRequired
readonly ProxyAuthenticationRequired: 407 = 407
RangeNotSatisfiable
readonly RangeNotSatisfiable: 416 = 416
RequestHeaderFieldsTooLarge
readonly RequestHeaderFieldsTooLarge: 431 = 431
RequestTimeout
readonly RequestTimeout: 408 = 408
ResetContent
readonly ResetContent: 205 = 205
SeeOther
readonly SeeOther: 303 = 303
ServiceUnavailable
readonly ServiceUnavailable: 503 = 503
SwitchingProtocols
readonly SwitchingProtocols: 101 = 101
SwitchProxy
readonly SwitchProxy: 306 = 306
TemporaryRedirect
readonly TemporaryRedirect: 307 = 307
TooEarly
readonly TooEarly: 425 = 425
TooManyRequests
readonly TooManyRequests: 429 = 429
Unauthorized
readonly Unauthorized: 401 = 401
UnavailableForLegalReasons
readonly UnavailableForLegalReasons: 451 = 451
UnprocessableEntity
readonly UnprocessableEntity: 422 = 422
UnsupportedMediaType
readonly UnsupportedMediaType: 415 = 415
UpgradeRequired
readonly UpgradeRequired: 426 = 426
URITooLong
readonly URITooLong: 414 = 414
UseProxy
readonly UseProxy: 305 = 305
VariantAlsoNegotiates
readonly VariantAlsoNegotiates: 506 = 506
Functions
api()
Call Signature
function api<Params, Response>(options, fn): HandlerFn<Params, Response>
Type Parameters
Params
Params extends void | object = void
Response
Response extends void | object = void
Parameters
options
fn
(params) => Promise\<Response>
Returns
HandlerFn\<Params, Response>
Call Signature
function api<Params, Response>(options, fn): HandlerFn<Params, Response>
Type Parameters
Params
Params extends void | object = void
Response
Response extends void | object = void
Parameters
options
fn
(params) => Response
Returns
HandlerFn\<Params, Response>
middleware()
Call Signature
function middleware(m): Middleware
Parameters
m
Returns
Call Signature
function middleware(options, fn): Middleware