Function: coerceParameter

coerceParameter(data: string | undefined | any, spec: ParameterObject) : undefined | string | number | false | true | object

Coerce the http raw data to a JavaScript type data of a parameter according to its OpenAPI schema specification.

Parameters
Name Type Default Value Flags Description
data string | undefined | any

The raw data get from http request

spec ParameterObject

Function: getOAIPrimitiveType

getOAIPrimitiveType(type: undefined | string, format: undefined | string) : undefined | | | | | | | | | | | | | |

Return the corresponding OpenAPI data type given an OpenAPI schema

Parameters
Name Type Default Value Flags Description
type undefined | string optional

The type in an OpenAPI schema specification

format undefined | string optional

The format in an OpenAPI schema specification

Function: isEmpty

isEmpty(data: string) : boolean

Parameters
Name Type Default Value Flags Description
data string

Function: isFalse

isFalse(data: string) : boolean

A set of falsy values. A data in this set will be coerced to false.

Returns:

The corresponding coerced boolean type

Parameters
Name Type Default Value Flags Description
data string

The raw data get from http request

Function: isTrue

isTrue(data: string) : boolean

A set of truthy values. A data in this set will be coerced to true.

Returns:

The corresponding coerced boolean type

Parameters
Name Type Default Value Flags Description
data string

The raw data get from http request

Function: isValidDateTime

isValidDateTime(data: Date) : boolean

Return false for invalid date

Parameters
Name Type Default Value Flags Description
data Date

Function: matchDateFormat

matchDateFormat(date: string) : boolean

Return true when a date follows the RFC3339 standard

Parameters
Name Type Default Value Flags Description
date string

The date to verify

Class: validator = new Validator()

Validator class provides a bunch of functions that perform validations on the request parameters and request body.

Properties
Name Type Default Value Flags Description
ctx ValidationContext constructorProperty exported public

Validator class provides a bunch of functions that perform validations on the request parameters and request body.

constructor(ctx: ValidationContext) : Validator

Parameters
Name Type Default Value Flags Description
ctx ValidationContext

Validator class provides a bunch of functions that perform validations on the request parameters and request body.

isAbsent(value: any) : boolean

Return true if the value is empty, return false otherwise.

Parameters
Name Type Default Value Flags Description
value any

isRequired(opts: ValidationOptions) : boolean

Check is a parameter required or not.

Parameters
Name Type Default Value Flags Description
opts ValidationOptions optional

validateParamBeforeCoercion(value: string | any | undefined, opts: ValidationOptions) : void

The validation executed before type coercion. Like checking absence.

Parameters
Name Type Default Value Flags Description
value string | any | undefined

A parameter's raw value from http request.

opts ValidationOptions optional

options

Class: httphandler = new HttpHandler()

Properties
Name Type Default Value Flags Description
handleRequest anonymous exported public

constructor(_rootContext: Context, _routes: RoutingTable) : HttpHandler

Parameters
Name Type Default Value Flags Description
_rootContext Context
_routes RoutingTable new RoutingTable()

describeApiPaths() : PathObject

findRoute(request: Request) : ResolvedRoute

Parameters
Name Type Default Value Flags Description
request Request

getApiDefinitions() : SchemasObject

registerApiDefinitions(defs: SchemasObject) : void

Parameters
Name Type Default Value Flags Description
defs SchemasObject

registerController(spec: ControllerSpec, controllerCtor: ControllerClass<T>, controllerFactory: ControllerFactory<T>) : void

Parameters
Name Type Default Value Flags Description
spec ControllerSpec
controllerCtor ControllerClass<T>
controllerFactory ControllerFactory<T> optional

registerRoute(route: RouteEntry) : void

Parameters
Name Type Default Value Flags Description
route RouteEntry

Namespace: RestBindings

RestServer-specific bindings

Namespace: RestBindings.Http

Request-specific bindings

const RestBindings.Http.CONTEXT = BindingKey.create( 'rest.http.request.context', )

Binding key for setting and injecting the http request context

const RestBindings.Http.REQUEST = BindingKey.create('rest.http.request')

Binding key for setting and injecting the http request

const RestBindings.Http.RESPONSE = BindingKey.create('rest.http.response')

Binding key for setting and injecting the http response

Namespace: RestBindings.SequenceActions

Bindings for potential actions that could be used in a sequence

const RestBindings.SequenceActions.FIND_ROUTE = BindingKey.create( 'rest.sequence.actions.findRoute', )

Binding key for setting and injecting a route finding function

const RestBindings.SequenceActions.INVOKE_METHOD = BindingKey.create( 'rest.sequence.actions.invokeMethod', )

Binding key for setting and injecting a controller route invoking function

const RestBindings.SequenceActions.LOG_ERROR = BindingKey.create( 'rest.sequence.actions.logError', )

Binding key for setting and injecting an error logging function

const RestBindings.SequenceActions.PARSE_PARAMS = BindingKey.create( 'rest.sequence.actions.parseParams', )

Binding key for setting and injecting a parameter parsing function

const RestBindings.SequenceActions.REJECT = BindingKey.create( 'rest.sequence.actions.reject', )

Binding key for setting and injecting a bad response writing function

const RestBindings.SequenceActions.SEND = BindingKey.create('rest.sequence.actions.send')

Binding key for setting and injecting a response writing function

const RestBindings.API_SPEC = BindingKey.create('rest.apiSpec')

Binding key for setting and injecting an OpenAPI spec

const RestBindings.BIND_ELEMENT = BindingKey.create('bindElement')

Binding key for setting and injecting a wrapper function for setting values on a given context

const RestBindings.CONFIG = CoreBindings.APPLICATION_CONFIG.deepProperty('rest')

Binding key for setting and injecting RestComponentConfig

const RestBindings.ERROR_WRITER_OPTIONS = BindingKey.create( 'rest.errorWriterOptions', )

Binding key for setting and injecting Reject action's error handling options.

See https://github.com/strongloop/strong-error-handler#options for the list of available options. Please note that the flag log is not used by @loopback/rest.

const RestBindings.GET_FROM_CONTEXT = BindingKey.create( 'getFromContext', )

Binding key for setting and injecting a wrapper function for retrieving values from a given context

const RestBindings.HANDLER = BindingKey.create('rest.handler')

Internal binding key for http-handler

const RestBindings.HOST = BindingKey.create('rest.host')

Binding key for setting and injecting the host name of RestServer

const RestBindings.HTTPS_OPTIONS = BindingKey.create( 'rest.httpsOptions', )

Binding key for HTTPS options

const RestBindings.PORT = BindingKey.create('rest.port')

Binding key for setting and injecting the port number of RestServer

const RestBindings.PROTOCOL = BindingKey.create('rest.protocol')

Binding key for setting and injecting the protocol of RestServer

const RestBindings.REQUEST_BODY_PARSER_OPTIONS = BindingKey.create< RequestBodyParserOptions >('rest.requestBodyParserOptions')

RestServer-specific bindings

const RestBindings.ROUTER = BindingKey.create('rest.router')

Internal binding key for rest router

const RestBindings.SEQUENCE = BindingKey.create('rest.sequence')

Binding key for setting and injecting a Sequence

const RestBindings.URL = BindingKey.create('rest.url')

Binding key for setting and injecting the URL of RestServer

const QUERY_NOT_PARSED =

Function: loadRequestBodyIfNeeded

loadRequestBodyIfNeeded(operationSpec: OperationObject, request: Request, options: RequestBodyParserOptions) : Promise<RequestBody>

Parameters
Name Type Default Value Flags Description
operationSpec OperationObject
request Request
options RequestBodyParserOptions {}

Function: parseOperationArgs

parseOperationArgs(request: Request, route: ResolvedRoute, options: RequestBodyParserOptions) : Promise<OperationArgs>

Parses the request to derive arguments to be passed in for the Application controller method

Parameters
Name Type Default Value Flags Description
request Request

Incoming HTTP request

route ResolvedRoute

Resolved Route

options RequestBodyParserOptions {}

Class: bindelementprovider = new BindElementProvider()

constructor(context: Context) : BindElementProvider

Parameters
Name Type Default Value Flags Description
context Context

action(key: string) : Binding

Parameters
Name Type Default Value Flags Description
key string

value() : BindElement

Class: findrouteprovider = new FindRouteProvider()

constructor(context: Context, handler: HttpHandler) : FindRouteProvider

Parameters
Name Type Default Value Flags Description
context Context
handler HttpHandler

action(request: Request) : ResolvedRoute

Parameters
Name Type Default Value Flags Description
request Request

value() : FindRoute

Class: getfromcontextprovider = new GetFromContextProvider()

constructor(context: Context) : GetFromContextProvider

Parameters
Name Type Default Value Flags Description
context Context

action(key: string) : Promise<BoundValue>

Parameters
Name Type Default Value Flags Description
key string

value() : GetFromContext

Class: invokemethodprovider = new InvokeMethodProvider()

constructor(context: Context) : InvokeMethodProvider

Parameters
Name Type Default Value Flags Description
context Context

action(route: RouteEntry, args: OperationArgs) : Promise<OperationRetval>

Parameters
Name Type Default Value Flags Description
route RouteEntry
args OperationArgs

value() : InvokeMethod

Class: logerrorprovider = new LogErrorProvider()

action(err: Error, statusCode: number, req: Request) : void

Parameters
Name Type Default Value Flags Description
err Error
statusCode number
req Request

value() : LogError

Class: parseparamsprovider = new ParseParamsProvider()

Provides the function for parsing args in requests at runtime.

constructor(options: RequestBodyParserOptions) : ParseParamsProvider

Parameters
Name Type Default Value Flags Description
options RequestBodyParserOptions optional

Provides the function for parsing args in requests at runtime.

value() : (Anonymous function)

Class: rejectprovider = new RejectProvider()

constructor(logError: LogError, errorWriterOptions: ErrorWriterOptions) : RejectProvider

Parameters
Name Type Default Value Flags Description
logError LogError
errorWriterOptions ErrorWriterOptions optional

action(__namedParameters, error: Error) : void

Parameters
Name Type Default Value Flags Description
__namedParameters anonymous
error Error

value() : Reject

Class: sendprovider = new SendProvider()

Provides the function that populates the response object with the results of the operation.

value() : writeResultToResponse

Class: requestcontext = new RequestContext()

A per-request Context combining an IoC container with handler context (request, response, etc.).

Properties
Name Type Default Value Flags Description
request Request constructorProperty exported public

A per-request Context combining an IoC container with handler context (request, response, etc.).

response Response constructorProperty exported public

A per-request Context combining an IoC container with handler context (request, response, etc.).

constructor(request: Request, response: Response, parent: Context, name: undefined | string) : RequestContext

Parameters
Name Type Default Value Flags Description
request Request

A per-request Context combining an IoC container with handler context (request, response, etc.).

response Response

A per-request Context combining an IoC container with handler context (request, response, etc.).

parent Context

A per-request Context combining an IoC container with handler context (request, response, etc.).

name undefined | string optional

A per-request Context combining an IoC container with handler context (request, response, etc.).

Namespace: RestHttpErrors

Interface: RestHttpErrors.ValidationErrorDetails

An invalid request body error contains a details property as the machine-readable error. Each entry in error.details contains 4 attributes: path, code, info and message. ValidationErrorDetails defines the type of each entry, which is an object. The type of error.details is ValidationErrorDetails[].

Properties
Name Type Default Value Flags Description
code string exported

A single word code represents the error's type.

info object exported

Some additional details that the 3 attributes above don't cover.

message string exported

A human readable description of the error.

path string exported

A path to the invalid field.

const RestHttpErrors.INVALID_REQUEST_BODY_MESSAGE = "The request body is invalid. See error object `details` property for more info."

Function: RestHttpErrors.invalidData

RestHttpErrors.invalidData(data: T, name: string, extraProperties: Props) :

Parameters
Name Type Default Value Flags Description
data T
name string
extraProperties Props optional

Function: RestHttpErrors.invalidParamLocation

RestHttpErrors.invalidParamLocation(location: string) : HttpErrors.HttpError

Parameters
Name Type Default Value Flags Description
location string

Function: RestHttpErrors.invalidRequestBody

RestHttpErrors.invalidRequestBody() : HttpErrors.HttpError

Function: RestHttpErrors.missingRequired

RestHttpErrors.missingRequired(name: string) : HttpErrors.HttpError

Parameters
Name Type Default Value Flags Description
name string

Function: RestHttpErrors.unsupportedMediaType

RestHttpErrors.unsupportedMediaType(contentType: string, allowedTypes: string[]) :

Parameters
Name Type Default Value Flags Description
contentType string
allowedTypes string[] []

Class: restapplication = new RestApplication()

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

constructor(config: ApplicationConfig) : RestApplication

Parameters
Name Type Default Value Flags Description
config ApplicationConfig {}

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

requestHandler() : HttpRequestListener

Handle incoming HTTP(S) request by invoking the corresponding Controller method via the configured Sequence.

restServer() : RestServer

The main REST server instance providing REST API for this application.

api(spec: OpenApiSpec) : Binding

Set the OpenAPI specification that defines the REST API schema for this application. All routes, parameter definitions and return types will be defined in this way.

Note that this will override any routes defined via decorators at the controller level (this function takes precedent).

Parameters
Name Type Default Value Flags Description
spec OpenApiSpec

The OpenAPI specification, as an object.

handler(handlerFn: SequenceFunction) : void

Parameters
Name Type Default Value Flags Description
handlerFn SequenceFunction

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

route(verb: string, path: string, spec: OperationObject, controllerCtor: ControllerClass<T>, controllerFactory: ControllerFactory<T>, methodName: string) : Binding

Register a new Controller-based route.

class MyController {
  greet(name: string) {
    return `hello ${name}`;
  }
}
app.route('get', '/greet', operationSpec, MyController, 'greet');

Parameters
Name Type Default Value Flags Description
verb string

HTTP verb of the endpoint

path string

URL path of the endpoint

spec OperationObject

The OpenAPI spec describing the endpoint (operation)

controllerCtor ControllerClass<T>

Controller constructor

controllerFactory ControllerFactory<T>

A factory function to create controller instance

methodName string

The name of the controller method

route(verb: string, path: string, spec: OperationObject, handler: Function) : Binding

Register a new route invoking a handler function.

function greet(name: string) {
 return `hello ${name}`;
}
app.route('get', '/', operationSpec, greet);

Parameters
Name Type Default Value Flags Description
verb string

HTTP verb of the endpoint

path string

URL path of the endpoint

spec OperationObject

The OpenAPI spec describing the endpoint (operation)

handler Function

The function to invoke with the request parameters described in the spec.

route(route: RouteEntry) : Binding

Register a new route.

function greet(name: string) {
 return `hello ${name}`;
}
const route = new Route('get', '/', operationSpec, greet);
app.route(route);

Parameters
Name Type Default Value Flags Description
route RouteEntry

The route to add.

route(verb: string, path: string, spec: OperationObject, handler: Function) : Binding

Register a new route.

function greet(name: string) {
 return `hello ${name}`;
}
app.route('get', '/', operationSpec, greet);

Parameters
Name Type Default Value Flags Description
verb string

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

path string

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

spec OperationObject

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

handler Function

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

sequence(sequence: Constructor<SequenceHandler>) : Binding

Parameters
Name Type Default Value Flags Description
sequence Constructor<SequenceHandler>

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

server(server: Constructor<Server>, name: undefined | string) : Binding

Parameters
Name Type Default Value Flags Description
server Constructor<Server>

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

name undefined | string optional

An implementation of the Application class that automatically provides an instance of a REST server. This application class is intended to be a single-server implementation. Any attempt to bind additional servers will throw an error.

static(path: PathParams, rootDir: string, options: ServeStaticOptions) : void

Mount static assets to the REST server. See https://expressjs.com/en/4x/api.html#express.static

Parameters
Name Type Default Value Flags Description
path PathParams

The path(s) to serve the asset. See examples at https://expressjs.com/en/4x/api.html#path-examples To avoid performance penalty, / is not allowed for now.

rootDir string

The root directory from which to serve static assets

options ServeStaticOptions optional

Options for serve-static

const ERR_NO_MULTI_SERVER = format( 'RestApplication does not support multiple servers!', 'To create your own server bindings, please extend the Application class.', )

const SequenceActions = RestBindings.SequenceActions

Class: restcomponent = new RestComponent()

constructor(app: Application, config: RestComponentConfig) : RestComponent

Parameters
Name Type Default Value Flags Description
app Application
config RestComponentConfig optional

Type alias: RestComponentConfig = RestServerConfig

Class: restserver = new RestServer()

A REST API server for use with Loopback. Add this server to your application by importing the RestComponent.

const app = new MyApplication();
app.component(RestComponent);

To add additional instances of RestServer to your application, use the .server function:

app.server(RestServer, 'nameOfYourServer');

By default, one instance of RestServer will be created when the RestComponent is bootstrapped. This instance can be retrieved with app.getServer(RestServer), or by calling app.get('servers.RestServer') Note that retrieving other instances of RestServer must be done using the server's name:

const server = await app.getServer('foo')
// OR
const server = await app.get('servers.foo');

Properties
Name Type Default Value Flags Description
config RestServerConfig exported public

A REST API server for use with Loopback. Add this server to your application by importing the RestComponent.

const app = new MyApplication();
app.component(RestComponent);

To add additional instances of RestServer to your application, use the .server function:

app.server(RestServer, 'nameOfYourServer');

By default, one instance of RestServer will be created when the RestComponent is bootstrapped. This instance can be retrieved with app.getServer(RestServer), or by calling app.get('servers.RestServer') Note that retrieving other instances of RestServer must be done using the server's name:

const server = await app.getServer('foo')
// OR
const server = await app.get('servers.foo');

requestHandler HttpRequestListener exported public

Handle incoming HTTP(S) request by invoking the corresponding Controller method via the configured Sequence.

constructor(app: Application, config: RestServerConfig) : RestServer

Parameters
Name Type Default Value Flags Description
app Application

The application instance (injected via CoreBindings.APPLICATION_INSTANCE).

config RestServerConfig {}

The configuration options (injected via RestBindings.CONFIG).

listening() : boolean

url() : string | undefined

api(spec: OpenApiSpec) : Binding

Set the OpenAPI specification that defines the REST API schema for this server. All routes, parameter definitions and return types will be defined in this way.

Note that this will override any routes defined via decorators at the controller level (this function takes precedent).

Parameters
Name Type Default Value Flags Description
spec OpenApiSpec

The OpenAPI specification, as an object.

controller(controllerCtor: ControllerClass<ControllerInstance>) : Binding

Register a controller class with this server.

Returns:

The newly created binding, you can use the reference to further modify the binding, e.g. lock the value to prevent further modifications.

class MyController {
}
app.controller(MyController).lock();

Parameters
Name Type Default Value Flags Description
controllerCtor ControllerClass<ControllerInstance>

The controller class (constructor function).

getApiSpec() : OpenApiSpec

Get the OpenAPI specification describing the REST API provided by this application.

This method merges operations (HTTP endpoints) from the following sources:

  • app.api(spec)
  • app.controller(MyController)
  • app.route(route)
  • app.route('get', '/greet', operationSpec, MyController, 'greet')

handler(handlerFn: SequenceFunction) : void

Configure a custom sequence function for handling incoming requests.

app.handler(({request, response}, sequence) => {
  sequence.send(response, 'hello world');
});

Parameters
Name Type Default Value Flags Description
handlerFn SequenceFunction

The handler to invoke for each incoming request.

route(verb: string, path: string, spec: OperationObject, controllerCtor: ControllerClass<I>, controllerFactory: ControllerFactory<I>, methodName: string) : Binding

Register a new Controller-based route.

class MyController {
  greet(name: string) {
    return `hello ${name}`;
  }
}
app.route('get', '/greet', operationSpec, MyController, 'greet');

Parameters
Name Type Default Value Flags Description
verb string

HTTP verb of the endpoint

path string

URL path of the endpoint

spec OperationObject

The OpenAPI spec describing the endpoint (operation)

controllerCtor ControllerClass<I>

Controller constructor

controllerFactory ControllerFactory<I>

A factory function to create controller instance

methodName string

The name of the controller method

route(verb: string, path: string, spec: OperationObject, handler: Function) : Binding

Register a new route invoking a handler function.

function greet(name: string) {
 return `hello ${name}`;
}
app.route('get', '/', operationSpec, greet);

Parameters
Name Type Default Value Flags Description
verb string

HTTP verb of the endpoint

path string

URL path of the endpoint

spec OperationObject

The OpenAPI spec describing the endpoint (operation)

handler Function

The function to invoke with the request parameters described in the spec.

route(route: RouteEntry) : Binding

Register a new generic route.

function greet(name: string) {
 return `hello ${name}`;
}
const route = new Route('get', '/', operationSpec, greet);
app.route(route);

Parameters
Name Type Default Value Flags Description
route RouteEntry

The route to add.

sequence(value: Constructor<SequenceHandler>) : void

Configure a custom sequence class for handling incoming requests.

class MySequence implements SequenceHandler {
  constructor(
    @inject('send) public send: Send)) {
  }

  public async handle({response}: RequestContext) {
    send(response, 'hello world');
  }
}

Parameters
Name Type Default Value Flags Description
value Constructor<SequenceHandler>

The sequence to invoke for each incoming request.

start() : Promise<void>

Start this REST API's HTTP/HTTPS server.

static(path: PathParams, rootDir: string, options: ServeStaticOptions) : void

Mount static assets to the REST server. See https://expressjs.com/en/4x/api.html#express.static

Parameters
Name Type Default Value Flags Description
path PathParams

The path(s) to serve the asset. See examples at https://expressjs.com/en/4x/api.html#path-examples

rootDir string

The root directory from which to serve static assets

options ServeStaticOptions optional

Options for serve-static

stop() : Promise<void>

Stop this REST API's HTTP/HTTPS server.

Interface: ApiExplorerOptions

Properties
Name Type Default Value Flags Description
disabled undefined | true exported optional

Set this flag to disable the built-in redirect to externally hosted API Explorer UI.

httpUrl undefined | string exported optional

URL for the API explorer served over http protocol to deal with mixed content security imposed by browsers as the spec is exposed over http by default. See https://github.com/strongloop/loopback-next/issues/1603

url undefined | string exported optional

URL for the hosted API explorer UI default to https://loopback.io/api-explorer

Interface: HttpServerLike

Properties
Name Type Default Value Flags Description
requestHandler HttpRequestListener exported

Interface: OpenApiSpecForm

The form of OpenAPI specs to be served

Properties
Name Type Default Value Flags Description
format undefined | string exported optional

The form of OpenAPI specs to be served

version undefined | string exported optional

The form of OpenAPI specs to be served

Interface: OpenApiSpecOptions

Options to customize how OpenAPI specs are served

Properties
Name Type Default Value Flags Description
endpointMapping undefined | anonymous exported optional

Mapping of urls to spec forms, by default:

{
  '/openapi.json': {version: '3.0.0', format: 'json'},
  '/openapi.yaml': {version: '3.0.0', format: 'yaml'},
}

servers ServerObject[] exported optional

Configure servers for OpenAPI spec

setServersFromRequest undefined | false | true exported optional

A flag to force servers to be set from the http request for the OpenAPI spec

Interface: RestServerOptions

Options for RestServer configuration

Properties
Name Type Default Value Flags Description
apiExplorer ApiExplorerOptions exported optional

Options for RestServer configuration

cors cors.CorsOptions exported optional

Options for RestServer configuration

openApiSpec OpenApiSpecOptions exported optional

Options for RestServer configuration

sequence Constructor<SequenceHandler> exported optional

Options for RestServer configuration

Type alias: HttpRequestListener(req: IncomingMessage, res: ServerResponse): void

Arguments
Name Type Description
req IncomingMessage
res ServerResponse

Class: routingtable = new RoutingTable()

Routing table

constructor(_router: RestRouter, staticAssetsRoute: StaticAssetsRoute) : RoutingTable

Parameters
Name Type Default Value Flags Description
_router RestRouter new TrieRouter()

Routing table

staticAssetsRoute StaticAssetsRoute optional

Routing table

describeApiPaths() : PathObject

find(request: Request) : ResolvedRoute

Map a request to a route

Parameters
Name Type Default Value Flags Description
request Request

registerController(spec: ControllerSpec, controllerCtor: ControllerClass<T>, controllerFactory: ControllerFactory<T>) : void

Register a controller as the route

Parameters
Name Type Default Value Flags Description
spec ControllerSpec

controllerCtor ControllerClass<T>

controllerFactory ControllerFactory<T> optional

registerRoute(route: RouteEntry) : void

Register a route

Parameters
Name Type Default Value Flags Description
route RouteEntry

A route entry

joinPath(basePath: string, path: string) : string

Parameters
Name Type Default Value Flags Description
basePath string

Routing table

path string

Routing table

Class: defaultsequence = new DefaultSequence()

The default implementation of SequenceHandler.

This class implements default Sequence for the LoopBack framework. Default sequence is used if user hasn't defined their own Sequence for their application.

Sequence constructor() and run() methods are invoked from [[http-handler]] when the API request comes in. User defines APIs in their Application Controller class.

User can bind their own Sequence to app as shown below

app.bind(CoreBindings.SEQUENCE).toClass(MySequence);

Properties
Name Type Default Value Flags Description
reject Reject constructorProperty exported public

The action to take if the invoke returns a rejected promise result (injected via SequenceActions.REJECT).

send Send constructorProperty exported public

The action to merge the invoke result with the response (injected via SequenceActions.SEND)

constructor(findRoute: FindRoute, parseParams: ParseParams, invoke: InvokeMethod, send: Send, reject: Reject) : DefaultSequence

Constructor: Injects findRoute, invokeMethod & logError methods as promises.

Parameters
Name Type Default Value Flags Description
findRoute FindRoute

Finds the appropriate controller method, spec and args for invocation (injected via SequenceActions.FIND_ROUTE).

parseParams ParseParams

The parameter parsing function (injected via SequenceActions.PARSE_PARAMS).

invoke InvokeMethod

Invokes the method specified by the route (injected via SequenceActions.INVOKE_METHOD).

send Send

The action to merge the invoke result with the response (injected via SequenceActions.SEND)

reject Reject

The action to take if the invoke returns a rejected promise result (injected via SequenceActions.REJECT).

handle(context: RequestContext) : Promise<void>

Runs the default sequence. Given a handler context (request and response), running the sequence will produce a response or an error.

Default sequence executes these steps

  • Finds the appropriate controller method, swagger spec and args for invocation
  • Parses HTTP request to get API argument list
  • Invokes the API which is defined in the Application Controller
  • Writes the result from API into the HTTP response
  • Error is caught and logged using 'logError' if any of the above steps in the sequence fails with an error.

Parameters
Name Type Default Value Flags Description
context RequestContext

The request context: HTTP request and response objects, per-request IoC container and more.

Interface: SequenceHandler

A sequence handler is a class implementing sequence of actions required to handle an incoming request.

handle(context: RequestContext) : Promise<void>

Handle the request by running the configured sequence of actions.

Parameters
Name Type Default Value Flags Description
context RequestContext

The request context: HTTP request and response objects, per-request IoC container and more.

Type alias: SequenceFunction(context: RequestContext, sequence: DefaultSequence):

A sequence function is a function implementing a custom sequence of actions to handle an incoming request.

Arguments
Name Type Description
context RequestContext
sequence DefaultSequence

Interface: HandlerContext

An object holding HTTP request, response and other data needed to handle an incoming HTTP request.

Properties
Name Type Default Value Flags Description
request Request exported

An object holding HTTP request, response and other data needed to handle an incoming HTTP request.

response Response exported

An object holding HTTP request, response and other data needed to handle an incoming HTTP request.

Type alias: BindElement(key: string): Binding

Arguments
Name Type Description
key string

Type alias: FindRoute(request: Request): ResolvedRoute

Find a route matching the incoming request. Throw an error when no route was found.

Arguments
Name Type Description
request Request

Type alias: GetFromContext(key: string): Promise<BoundValue>

Arguments
Name Type Description
key string

Type alias: InvokeMethod(route: RouteEntry, args: OperationArgs): Promise<OperationRetval>

Invokes a method defined in the Application Controller

Returns:

OperationRetval Result from method invocation

Arguments
Name Type Description
route RouteEntry

args OperationArgs

Operation arguments for the method

Type alias: LogError(err: Error, statusCode: number, request: Request): void

Log information about a failed request.

Returns:

Arguments
Name Type Description
err Error

The error reported by request handling code.

statusCode number

Status code of the HTTP response

request Request

The request that failed.

Type alias: OperationArgs = any[]

Type alias: OperationRetval = any

Type alias: ParseParams(request: Request, route: ResolvedRoute): Promise<OperationArgs>

Arguments
Name Type Description
request Request
route ResolvedRoute

Type alias: PathParameterValues(key: string): any

Arguments
Name Type Description
key string

Type alias: Reject(handlerContext: HandlerContext, err: Error): void

Reject the request with an error.

Returns:

Arguments
Name Type Description
handlerContext HandlerContext

The context object holding HTTP request, response and other data needed to handle an incoming HTTP request.

err Error

The error.

Type alias: RequestBodyParserOptions(property: string): any

Options for request body parsing See https://github.com/Raynos/body

Arguments
Name Type Description
property string

Type alias: Send(response: Response, result: OperationRetval): void

Send the operation response back to the client.

Returns:

Arguments
Name Type Description
response Response

The response the response to send to.

result OperationRetval

The operation result to send.

Type alias: RequestBodyValidationOptions = AJV.Options

Function: validateRequestBody

validateRequestBody(body: RequestBody, requestBodySpec: RequestBodyObject, globalSchemas: SchemasObject, options: RequestBodyValidationOptions) : void

Check whether the request body is valid according to the provided OpenAPI schema. The JSON schema is generated from the OpenAPI schema which is typically defined by @requestBody(). The validation leverages AJS schema validator.

Parameters
Name Type Default Value Flags Description
body RequestBody

The request body parsed from an HTTP request.

requestBodySpec RequestBodyObject optional

The OpenAPI requestBody specification defined in @requestBody().

globalSchemas SchemasObject {}

The referenced schemas generated from OpenAPISpec.components.schemas.

options RequestBodyValidationOptions {}

Function: writeResultToResponse

writeResultToResponse(response: Response, result: OperationRetval) : void

Writes the result from Application controller method into the HTTP response

Parameters
Name Type Default Value Flags Description
response Response

HTTP Response

result OperationRetval

Result from the API to write into HTTP Response