@xylabs/express
v5.1.1
Published
SDK for base code for Api repos that use express and deploy on AWS ECS
Downloads
2,235
Readme
@xylabs/express
SDK for base code for Api repos that use express and deploy on AWS ECS
Install
Using npm:
npm install {{name}}Using yarn:
yarn add {{name}}Using pnpm:
pnpm add {{name}}Using bun:
bun add {{name}}License
See the LICENSE file for license rights and limitations (LGPL-3.0-only).
Reference
packages
express
### .temp-typedoc
### classes
### <a id="Counters"></a>CountersStatic counter registry for tracking named numeric metrics.
Constructors
Constructor
new Counters(): Counters;Returns
Counters
Properties
counters
static counters: Record<string, number> = {};Methods
inc()
static inc(name, count?): void;Parameters
name
string
count?
number = 1
Returns
void
max()
static max(name, count): void;Parameters
name
string
count
number
Returns
void
min()
static min(name, count): void;Parameters
name
string
count
number
Returns
void
### <a id="Profiler"></a>ProfilerMeasures and records the execution duration of async operations by name.
Constructors
Constructor
new Profiler(): Profiler;Returns
Profiler
Properties
stats
stats: Record<string, number> = {};Methods
profile()
profile<T>(name, promise): Promise<T>;Type Parameters
T
T
Parameters
name
string
promise
Promise<T>
Returns
Promise<T>
### <a id="WrappedWinstonLogger"></a>WrappedWinstonLoggerWrap Winston logger methods to adapt to familiar console logging methods
Implements
Logger
Constructors
Constructor
new WrappedWinstonLogger(winston): WrappedWinstonLogger;Parameters
winston
Logger
Returns
WrappedWinstonLogger
Properties
winston
protected readonly winston: Logger;debug
debug: LogFunction;Implementation of
Logger.debugerror
error: LogFunction;Implementation of
Logger.errorinfo
info: LogFunction;Implementation of
Logger.infolog
log: LogFunction;Implementation of
Logger.logtrace
trace: LogFunction;Implementation of
Logger.tracewarn
warn: LogFunction;Implementation of
Logger.warn ### functions
### <a id="addRouteDefinitions"></a>addRouteDefinitionsfunction addRouteDefinitions(app, routeDefinitions): void;Registers an array of route definitions on an Express application.
Parameters
app
Express
The Express application to register routes on.
routeDefinitions
RouteDefinition<RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>>[]
The route definitions to register.
Returns
void
### <a id="asyncHandler"></a>asyncHandlerfunction asyncHandler<P, ResBody, ReqBody, ReqQuery, Locals>(fn): (req, res, next) => Promise<unknown>;Wraps an async Express request handler to forward rejected promises to the error handler.
Type Parameters
P
P = ParamsDictionary
ResBody
ResBody = Empty
ReqBody
ReqBody = Empty
ReqQuery
ReqQuery = ParsedQs
Locals
Locals extends NoLocals = NoLocals
Parameters
fn
RequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>
The async request handler to wrap.
Returns
A request handler that catches async errors and passes them to next().
(req, res, next) => Promise<unknown>
### <a id="clearRawResponseFormat"></a>clearRawResponseFormatfunction clearRawResponseFormat(res): void;Clears any flags on the response, allowing the response to use the default standard response envelope
Parameters
res
Response
The response to set to the standard response format
Returns
void
### <a id="compactObject"></a>compactObjectfunction compactObject<T>(obj): T;Returns a shallow copy of the object with all null and undefined values removed.
Type Parameters
T
T extends Record<string, unknown>
Parameters
obj
T
The object to compact.
Returns
T
A new object with only defined, non-null properties.
### <a id="customPoweredByHeader"></a>customPoweredByHeaderfunction customPoweredByHeader(
req,
res,
next): void;Express middleware that sets the X-Powered-By header to 'XYO'.
Parameters
req
Request
res
Response
next
NextFunction
Returns
void
### <a id="disableCaseSensitiveRouting"></a>disableCaseSensitiveRoutingfunction disableCaseSensitiveRouting(app): void;Disable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.
Parameters
app
Express
The Express app to disable the header on.
Returns
void
### <a id="disableExpressDefaultPoweredByHeader"></a>disableExpressDefaultPoweredByHeaderfunction disableExpressDefaultPoweredByHeader(app): void;By default Express appends the X-Powered-By: Express header to
all responses. Calling this method disables that behavior.
Parameters
app
Express
The Express app to disable the header on.
Returns
void
### <a id="enableCaseSensitiveRouting"></a>enableCaseSensitiveRoutingfunction enableCaseSensitiveRouting(app): void;Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.
Parameters
app
Express
The Express app to disable the header on.
Returns
void
### <a id="enableExpressDefaultPoweredByHeader"></a>enableExpressDefaultPoweredByHeaderfunction enableExpressDefaultPoweredByHeader(app): void;By default Express appends the X-Powered-By: Express header to
all responses. Calling this method enables that behavior.
Parameters
app
Express
The Express app to disable the header on.
Returns
void
### <a id="errorToJsonHandler"></a>errorToJsonHandlerfunction errorToJsonHandler(
error,
req,
res,
next): void;Express error handler that logs the error and sends a JSON response with the error message and status code.
Parameters
error
The Express error to handle.
req
Request
The incoming request.
res
Response
The outgoing response.
next
NextFunction
The next middleware function.
Returns
void
### <a id="getDefaultLogger"></a>getDefaultLoggerfunction getDefaultLogger(): Logger;Returns the singleton default logger instance, creating one if it does not exist.
Returns
Logger
The default logger.
### <a id="getHttpHeader"></a>getHttpHeaderfunction getHttpHeader(header, req): string | undefined;Since there can be multiple of certain HTTP headers or to prevent ugliness if someone did send us multiple instances of a header we only expect one of, this method grabs the 1st/only one of the desired header
Parameters
header
string
The header to find
req
Request
The received HTTP request (with headers)
Returns
string | undefined
The first or only occurrence of the specified HTTP header
### <a id="getJsonBodyParser"></a>getJsonBodyParserfunction getJsonBodyParser(options?): NextHandleFunction;Get a JSON Body Parser connect middleware handler
Parameters
options?
OptionsJson = DefaultJsonBodyParserOptions
The options for the JSON Body Parser
Returns
NextHandleFunction
A middleware function that parses JSON bodies
### <a id="getJsonBodyParserOptions"></a>getJsonBodyParserOptionsfunction getJsonBodyParserOptions(options?): OptionsJson;Gets the default JSON Body Parser options merged with the supplied options with the supplied options taking precedence
Parameters
options?
Partial<OptionsJson>
The options to override the default JSON Body Parser options with
Returns
OptionsJson
The combined JSON Body Parser options with the supplied values taking precedence over the default
### <a id="getLogger"></a>getLoggerfunction getLogger(minVerbosity?): Logger;Returns a cached Winston-backed logger at the specified verbosity level.
Parameters
minVerbosity?
LoggerVerbosity = 'info'
The minimum log level to output. Defaults to 'info'.
Returns
Logger
A logger instance configured for the given verbosity.
### <a id="getResponseMetadata"></a>getResponseMetadatafunction getResponseMetadata(res): Record<string, unknown>;Extracts response metadata from res.locals, computing profile duration if profiling was started.
Parameters
res
Response
The Express response to extract metadata from.
Returns
Record<string, unknown>
The metadata record including any profiling information.
### <a id="isRawResponseFormatSet"></a>isRawResponseFormatSetfunction isRawResponseFormatSet(res): boolean;Checks if there are any flags on the response that would cause it to forgo the standard response envelope and return the raw response body to the client
Parameters
res
Response
Returns
boolean
True if there are any flags on the response, false otherwise
### <a id="requestHandlerValidator"></a>requestHandlerValidatorfunction requestHandlerValidator<TParams, TQuery, TBody, TResponse>(schemas?): (handler) => RequestHandler;Factory for Express middleware that validates request and response objects using Zod schemas.
Type Parameters
TParams
TParams extends
| ZodObject<{
}, $catchall<ZodUnion<readonly [ZodString, ZodArray<ZodString>]>>>
| ZodType<Record<string, string>, unknown, $ZodTypeInternals<Record<string, string>, unknown>> = ZodObject<{
}, $catchall<ZodUnion<readonly [ZodString, ZodArray<ZodString>]>>>
TQuery
TQuery extends
| ZodObject<{
}, $catchall<ZodUnion<readonly [ZodString, ZodArray<ZodString>]>>>
| ZodType<Record<string, string | string[]>, unknown, $ZodTypeInternals<Record<string, string | string[]>, unknown>> = ZodObject<{
}, $catchall<ZodUnion<readonly [ZodString, ZodArray<ZodString>]>>>
TBody
TBody extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> = ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>
TResponse
TResponse extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> = ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>
Parameters
schemas?
Partial<{
body: TBody;
params: TParams;
query: TQuery;
response: TResponse;
}>
The Zod schemas to use for validation.
Returns
A middleware function for validating requests and responses.
(handler) => RequestHandler
### <a id="responseProfiler"></a>responseProfilerfunction responseProfiler(
_req,
res,
next): void;Connect middleware to enable profiling of response lifecycle timing. To effectively profile the response timing, this middleware needs to be called first when initializing your Express App
Parameters
_req
Request
The request
res
Response
The response
next
NextFunction
The next function
Returns
void
Example
const app = express()
app.use(responseProfiler)
// other initialization ... ### <a id="setRawResponseFormat"></a>setRawResponseFormatfunction setRawResponseFormat(res): void;Flags the response to forgo the standard response envelope and return the raw response body to the client
Parameters
res
Response
The response to disable the standard response format on
Returns
void
### <a id="standardErrors"></a>standardErrorsfunction standardErrors(
err,
req,
res,
next): void;Express error handler that logs the error and sends a JSON:API-compliant error response.
Parameters
err
ExpressError | undefined
The error to handle, or undefined if no error.
req
Request
The incoming request.
res
Response
The outgoing response.
next
NextFunction
The next middleware function.
Returns
void
### <a id="tryParse"></a>tryParsefunction tryParse<T>(func, value?): T & object | undefined;Type Parameters
T
T = number
Parameters
func
ParseFunc<T>
value?
string
Returns
T & object | undefined
Deprecated
use zod instead
### <a id="useRequestCounters"></a>useRequestCountersfunction useRequestCounters(app): void;Registers middleware that increments per-path request counters and exposes a /stats endpoint.
Parameters
app
Application
The Express application to attach counters to.
Returns
void
### interfaces
### <a id="ApiDataResponse"></a>ApiDataResponseA successful JSON:API response containing primary data and optional included resources.
Extends
Type Parameters
T
T extends ApiResourceIdentifierObject
Properties
jsonapi?
optional jsonapi?: JsonApi;Inherited from
links?
optional links?: ApiLinks;Inherited from
meta?
optional meta?: Record<string, unknown>;Inherited from
data
data: T;included?
optional included?: ApiResourceObject[]; ### <a id="ApiError"></a>ApiErrorProperties
code?
optional code?: string;An application-specific error code, expressed as a string value.
detail?
optional detail?: string;A human-readable explanation specific to this occurrence of the problem. Like title, this field's value can be localized.
id?
optional id?: string;A unique identifier for this particular occurrence of the problem.
links?
optional links?: ApiLinks;A links object containing the following members: about: a link that leads to further details about this particular occurrence of the problem
meta?
optional meta?: Record<string, unknown>;A meta object containing non-standard meta-information about the error.
source?
optional source?: Source;An object containing references to the source of the error, optionally including any of the following members:
status?
optional status?: string;The HTTP status code applicable to this problem, expressed as a string value.
title?
optional title?: string;A short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization.
### <a id="ApiErrorResponse"></a>ApiErrorResponseA JSON:API error response containing one or more error objects.
Extends
Properties
jsonapi?
optional jsonapi?: JsonApi;Inherited from
links?
optional links?: ApiLinks;Inherited from
meta?
optional meta?: Record<string, unknown>;Inherited from
errors
errors: ApiError[]; ### <a id="ApiResourceIdentifierObject"></a>ApiResourceIdentifierObjectWithin a given API, each resource object's type and id pair MUST identify a single, unique resource. (The set of URIs controlled by a server, or multiple servers acting as one, constitute an API.)
Extended by
Properties
id
id: string;The id member is not required when the resource object originates at the client and represents a new resource to be created on the server.
type
type: string;The type member is used to describe resource objects that share common attributes and relationships. The values of type members MUST adhere to the same constraints as member names.
### <a id="ApiResourceObject"></a>ApiResourceObjectA JSON:API resource object with optional attributes, links, meta, and relationships.
Extends
Properties
id
id: string;The id member is not required when the resource object originates at the client and represents a new resource to be created on the server.
Inherited from
ApiResourceIdentifierObject.id
type
type: string;The type member is used to describe resource objects that share common attributes and relationships. The values of type members MUST adhere to the same constraints as member names.
Inherited from
ApiResourceIdentifierObject.type
attributes?
optional attributes?: Record<string, unknown>;An attributes object representing some of the resource's data.
links?
optional links?: ApiLinks;A links object containing links related to the resource.
meta?
optional meta?: Record<string, unknown>;A meta object containing non-standard meta-information about a resource that can not be represented as an attribute or relationship.
relationships?
optional relationships?: Record<string, Relationship>;A relationships object describing relationships between the resource and other JSON:API resources.
### <a id="ApiResponseBase"></a>ApiResponseBaseBase interface for all JSON:API responses, including optional links and metadata.
Extended by
Properties
jsonapi?
optional jsonapi?: JsonApi;links?
optional links?: ApiLinks;meta?
optional meta?: Record<string, unknown>; ### <a id="Empty"></a>EmptyEmpty object type used as a default for request/response body generics.
### <a id="ExpressError"></a>ExpressErrorAn Error with an optional HTTP status code for Express error handling.
Extends
Error
Properties
statusCode?
optional statusCode?: number; ### <a id="HrefWithMeta"></a>HrefWithMetaA link with an href and associated metadata.
Properties
href
href: string;meta
meta: Record<string, unknown>; ### <a id="IRelationshipData"></a>IRelationshipDataContains the resource linkage data for a JSON:API relationship.
Properties
data
data: ResourceLinkage; ### <a id="IRelationshipLinks"></a>IRelationshipLinksContains the links for a JSON:API relationship.
Properties
links
links:
| IRelationshipSelfLink
| IRelationshipRelatedLink; ### <a id="IRelationshipRelatedLink"></a>IRelationshipRelatedLinkA relationship link pointing to a related resource.
Properties
related
related: string;A related resource link
### <a id="IRelationshipSelfLink"></a>IRelationshipSelfLinkA relationship link pointing to the relationship itself.
Properties
self
self: string;A link for the relationship itself (a "relationship link"). This link allows the client to directly manipulate the relationship. For example, removing an author through an article’s relationship URL would disconnect the person from the article without deleting the people resource itself. When fetched successfully, this link returns the linkage for the related resources as its primary data.
### <a id="JsonApi"></a>JsonApiJSON:API version and metadata descriptor.
Properties
meta?
optional meta?: Record<string, unknown>;version?
optional version?: "1.0" | "1.1"; ### <a id="LoggerOptions"></a>LoggerOptionsConfiguration options for creating a logger instance.
Properties
defaultMeta?
optional defaultMeta?: LoggerMeta;level?
optional level?: LoggerVerbosity; ### <a id="RouteDefinition"></a>RouteDefinitionDefines an Express route with its HTTP method, path, and handler(s).
Type Parameters
H
H extends RequestHandler = RequestHandler
Properties
handlers
handlers: H | H[];method
method: HttpMethod;path
path: string | RegExp; ### <a id="Source"></a>SourceAn object containing references to the source of the error
Properties
parameter?
optional parameter?: string;A string indicating which URI query parameter caused the error.
pointer?
optional pointer?: string;A JSON Pointer [RFC6901] to the associated entity in the request document [e.g. "/data" for a primary data object, or "/data/attributes/title" for a specific attribute].
### type-aliases
### <a id="ApiLink"></a>ApiLinktype ApiLink = string | HrefWithMeta;A JSON:API link, either a simple URL string or an object with href and metadata.
### <a id="ApiLinks"></a>ApiLinkstype ApiLinks = Record<string, ApiLink>;A collection of named JSON:API links.
### <a id="ApiResponse"></a>ApiResponsetype ApiResponse<T> =
| ApiDataResponse<T>
| ApiErrorResponse;A JSON:API response, either a data response or an error response.
Type Parameters
T
T extends ApiResourceIdentifierObject
### <a id="HttpMethod"></a>HttpMethodtype HttpMethod = "get" | "post" | "put" | "patch" | "delete" | "options" | "head";Supported HTTP methods for route definitions.
### <a id="LogFunction"></a>LogFunctiontype LogFunction = XyLabsLogFunction;Deprecated
use from @xylabs/logger instead
### <a id="Logger"></a>Loggertype Logger = XyLabsLogger;Deprecated
use from @xylabs/logger instead
### <a id="LoggerMeta"></a>LoggerMetatype LoggerMeta = Record<string, string | number>;Metadata key-value pairs attached to log entries.
### <a id="LoggerVerbosity"></a>LoggerVerbositytype LoggerVerbosity = "error" | "warn" | "info" | "debug" | "all";Application-level log verbosity levels.
### <a id="NoLocals"></a>NoLocalstype NoLocals = Record<string, any>;Default type for response locals.
### <a id="NoReqBody"></a>NoReqBodytype NoReqBody = Empty;Default type for request body when none is specified.
### <a id="NoReqParams"></a>NoReqParamstype NoReqParams = ParamsDictionary;Default type for request route parameters.
### <a id="NoReqQuery"></a>NoReqQuerytype NoReqQuery = Query;Default type for request query parameters.
### <a id="NoResBody"></a>NoResBodytype NoResBody = Empty;Default type for response body when none is specified.
### <a id="ParseFunc"></a>ParseFunctype ParseFunc<T> = (value) => T;A function that parses a string value into the target type.
Type Parameters
T
T = number
Parameters
value
string
Returns
T
### <a id="Relationship"></a>Relationshiptype Relationship =
| IRelationshipLinks
| IRelationshipData
| RelationshipMeta;The value of the relationships key MUST be an object (a "relationships object"). Members of the relationships object ("relationships") represent references from the resource object in which it’s defined to other resource objects. Relationships may be to-one or to-many.
### <a id="RelationshipMeta"></a>RelationshipMetatype RelationshipMeta = Record<string, unknown>;Non-standard metadata associated with a JSON:API relationship.
### <a id="ResourceLinkage"></a>ResourceLinkagetype ResourceLinkage =
| null
| []
| ApiResourceIdentifierObject
| ApiResourceIdentifierObject[];Resource linkage in a compound document allows a client to link together all of the included resource objects without having to GET any URLs via links. Resource linkage MUST be represented as one of the following: • null for empty to-one relationships. • an empty array ([]) for empty to-many relationships. • a single resource identifier object for non-empty to-one relationships. • an array of resource identifier objects for non-empty to-many relationships.
### variables
### <a id="DefaultJsonBodyParserOptions"></a>DefaultJsonBodyParserOptionsconst DefaultJsonBodyParserOptions: OptionsJson;The default options for the JSON Body Parser
### <a id="DefaultJsonBodyParserOptionsLimit"></a>DefaultJsonBodyParserOptionsLimitconst DefaultJsonBodyParserOptionsLimit: "100kb" = '100kb';The default maximum request body size for the JSON Body Parser
### <a id="DefaultJsonBodyParserOptionsTypes"></a>DefaultJsonBodyParserOptionsTypesconst DefaultJsonBodyParserOptionsTypes: string[];The default MIME types for the JSON Body Parser
### <a id="EmptyParamsZod"></a>EmptyParamsZodconst EmptyParamsZod: ZodObject<{
}, $catchall<ZodString>>;Empty Zod schema for requests with no parameters.
### <a id="EmptyQueryParamsZod"></a>EmptyQueryParamsZodconst EmptyQueryParamsZod: ZodObject<{
}, $catchall<ZodUnion<readonly [ZodString, ZodArray<ZodString>]>>>;Empty Zod schema for requests with no query parameters.
### <a id="ValidateRequestDefaults"></a>ValidateRequestDefaultsconst ValidateRequestDefaults: object;Default validation schemas for request handler validator.
Type Declaration
params
params: ZodObject<{
}, $catchall<ZodString>> = EmptyParamsZod;query
query: ZodObject<{
}, $catchall<ZodUnion<readonly [ZodString, ZodArray<ZodString>]>>> = EmptyQueryParamsZod;body
body: ZodOptional<ZodJSONSchema>;response
response: ZodOptional<ZodJSONSchema>; ### <a id="jsonBodyParser"></a>jsonBodyParserconst jsonBodyParser: NextHandleFunction;A JSON Body Parser middleware handler initialized with the default options
### <a id="notImplemented"></a>notImplementedconst notImplemented: RequestHandler;Express request handler that responds with a 501 Not Implemented error.
### <a id="standardResponses"></a>standardResponsesconst standardResponses: RequestHandler;Connect middleware to enable the transform of all responses to match the standard response format (compatible with JSON API)
