@foal/core

Last updated 9 days ago

Table of contents

index.ts

Functions

encryptPassword

Hash a password using the PBKDF2 algorithm.

Configured to use PBKDF2 + HMAC + SHA256. The result is a 64 byte binary string (or hex if the legacy option is true).

The random salt is 16 bytes long. The number of iterations is 150000. The length key is 32 bytes long.

function encryptPassword(plainTextPassword: string, options: { legacy?: boolean | undefined; } = {}): Promise<string>;

Parameters

Name

Type

Default value

Description

plainTextPassword

string

- The password to encrypt.

options

{ legacy?: boolean | undefined; }

{}

Return type

Promise

logIn

Save the user id in the current session.

function logIn(ctx: Context<any>, user: object, idKey: string = 'id'): void;

Parameters

Name

Type

Default value

Description

ctx

Context

- The request context.

user

object

- The user object.

idKey

string

'id'

- The name of the user's id property.

Return type

void

logOut

Remove the user id from the current session.

function logOut(ctx: Context<any>): void;

Parameters

Name

Type

Description

ctx

Context

- The request context.

Return type

void

verifyPassword

Compare a plain text password and a hash to see if they match.

function verifyPassword(plainTextPassword: string, encryptedPassword: string, options: { legacy?: boolean | undefined; } = {}): Promise<boolean>;

Parameters

Name

Type

Default value

Description

plainTextPassword

string

- The password in clear text.

encryptedPassword

string

- The password hash generated by the encryptPassword function.

options

{ legacy?: boolean | undefined; }

{}

Return type

Promise

LoginOptional

Hook factory to authenticate users using cookies and sessions.

The hook does not return any error when no user could be authenticated.

function LoginOptional(options: { user: (id: number | string) => Promise<any>; }): HookDecorator;

Parameters

Name

Type

Description

options

{ user: (id: number | string) => Promise; }

- Hook options.

Return type

HookDecorator

LoginRequired

Hook factory to authenticate users using cookies and sessions.

The hook returns a 401 error if no user could be authenticated.

function LoginRequired(options: { redirect?: string | undefined; user: (id: number | string) => Promise<any>; }): HookDecorator;

Parameters

Name

Type

Description

options

{ redirect?: string | undefined; user: (id: number | string) => Promise; }

- Hook options.

Return type

HookDecorator

isObjectDoesNotExist

Check if an error is an instance of ObjectDoesNotExist.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isObjectDoesNotExist(err: object): err is ObjectDoesNotExist;

Parameters

Name

Type

Description

err

object

- The error to check.

Return type

err is ObjectDoesNotExist

isPermissionDenied

Check if an error is an instance of PermissionDenied.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isPermissionDenied(err: object): err is PermissionDenied;

Parameters

Name

Type

Description

err

object

- The error to check.

Return type

err is PermissionDenied

isValidationError

Check if an error is an instance of ValidationError.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isValidationError(err: object): err is ValidationError;

Parameters

Name

Type

Description

err

object

- The error to check

Return type

err is ValidationError

Log

Hook logging a message with optional information on the HTTP request. Hook factory logging a message with optional information on the HTTP request.

function Log(message: string, options: LogOptions = {}): HookDecorator;

Parameters

Name

Type

Default value

Description

message

string

The message to print.

  • The message to print on each request. |

    | options | LogOptions | {} | Options to specify which information on the HTTP request should be printed.

  • Options to specify which information on the HTTP request should be printed. |

Return type

HookDecorator

ValidateBody

Hook factory validating the body of the request against a AJV schema.

function ValidateBody(schema: object): HookDecorator;

Parameters

Name

Type

Description

schema

object

- Schema used to validate the body request.

Return type

HookDecorator

ValidateHeaders

Hook factory validating the headers of the request against a AJV schema.

function ValidateHeaders(schema: object): HookDecorator;

Parameters

Name

Type

Description

schema

object

- Schema used to validate the headers request.

Return type

HookDecorator

ValidateParams

Hook factory validating the params of the request against a AJV schema.

function ValidateParams(schema: object): HookDecorator;

Parameters

Name

Type

Description

schema

object

- Schema used to validate the params request.

Return type

HookDecorator

ValidateQuery

Hook factory validating the query of the request against a AJV schema.

function ValidateQuery(schema: object): HookDecorator;

Parameters

Name

Type

Description

schema

object

- Schema used to validate the query request.

Return type

HookDecorator

controller

Define the HTTP path of a controller class. This function is usually called when adding the controller as a sub-controller.

function controller(path: string, controllerClass: Class): Class;

Parameters

Name

Type

Description

path

string

- The HTTP path.

controllerClass

Class

- The controller class.

Return type

Class

escapeProp

Escape a string property of an object following OWASP recommandations to prevent XSS attacks.

Source: https://github.com/OWASP/CheatSheetSeries/blob/master/ cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md

function escapeProp(object: object, propName: string): void;

Parameters

Name

Type

Description

object

object

- The object which contains the property to escape.

propName

string

- The property name.

Return type

void

escape

Escape a string following OWASP recommandations to prevent XSS attacks.

Source: https://github.com/OWASP/CheatSheetSeries/blob/master/ cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md

function escape(str: string): string;

Parameters

Name

Type

Description

str

string

- The string to escape.

Return type

string

getAjvInstance

Return the Ajv instance used internally by FoalTS.

It has this default configuration:

  • coerceTypes: true (Change data type of data to match type keyword.)

  • removeAdditional: true (Remove additional properties when additionalProperties keyword is false.)

  • useDefaults: true (Replace missing properties and items with the values from corresponding default keyword)

This configuration can be overrided using the file config/default.json or through environment variables: SETTINGS_AJV_COERCE_TYPES, SETTINGS_AJV_REMOVE_ADDITIONAL, SETTINGS_AJV_USE_DEFAULTS.

function getAjvInstance(): Ajv;

Return type

Ajv

isInFile

Generate a function checking if a string is included in a text file.

function isInFile(path: string): (content: string) => Promise<boolean>;

Parameters

Name

Type

Description

path

string

- The file path.

Return type

(content: string) => Promise

render

Render a template in a new HttpResponseOK object.

function render(templatePath: string, locals: object, dirname: string): HttpResponseOK;

Parameters

Name

Type

Description

templatePath

string

- The path of the template.

locals

object

- The variables used to render the template.

dirname

string

- The directory name where the templated is located.

The passed value is usually __dirname. The function then joins dirname and templatePath together. |

Return type

HttpResponseOK

validate

Validate an object against an AJV schema. If the object is not validated, the function throws a ValidationError with the failure details.

function validate(schema: object, data: any): void;

Parameters

Name

Type

Description

schema

object

- The AJV schema.

data

any

- The tested data.

Return type

void

Decorator specifying that a controller method handles HEAD requests.

function Head(path?: string | undefined): (target: any, propertyKey: string) => void;

Parameters

Name

Type

Description

path

string | undefined

- The path of the request.

Return type

(target: any, propertyKey: string) => void

Options

Decorator specifying that a controller method handles OPTIONS requests.

function Options(path?: string | undefined): (target: any, propertyKey: string) => void;

Parameters

Name

Type

Description

path

string | undefined

- The path of the request.

Return type

(target: any, propertyKey: string) => void

Get

Decorator specifying that a controller method handles GET requests.

function Get(path?: string | undefined): (target: any, propertyKey: string) => void;

Parameters

Name

Type

Description

path

string | undefined

- The path of the request.

Return type

(target: any, propertyKey: string) => void

Post

Decorator specifying that a controller method handles POST requests.

function Post(path?: string | undefined): (target: any, propertyKey: string) => void;

Parameters

Name

Type

Description

path

string | undefined

- The path of the request.

Return type

(target: any, propertyKey: string) => void

Put

Decorator specifying that a controller method handles PUT requests.

function Put(path?: string | undefined): (target: any, propertyKey: string) => void;

Parameters

Name

Type

Description

path

string | undefined

- The path of the request.

Return type

(target: any, propertyKey: string) => void

Patch

Decorator specifying that a controller method handles PATCH requests.

function Patch(path?: string | undefined): (target: any, propertyKey: string) => void;

Parameters

Name

Type

Description

path

string | undefined

- The path of the request.

Return type

(target: any, propertyKey: string) => void

Delete

Decorator specifying that a controller method handles DELETE requests.

function Delete(path?: string | undefined): (target: any, propertyKey: string) => void;

Parameters

Name

Type

Description

path

string | undefined

- The path of the request.

Return type

(target: any, propertyKey: string) => void

isHttpResponse

Check if an object is an instance of HttpResponse.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponse(obj: any): obj is HttpResponse;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponse

isHttpResponseSuccess

Check if an object is an instance of HttpResponseSuccess.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseSuccess(obj: any): obj is HttpResponseSuccess;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseSuccess

isHttpResponseOK

Check if an object is an instance of HttpResponseOK.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseOK(obj: any): obj is HttpResponseOK;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseOK

isHttpResponseCreated

Check if an object is an instance of HttpResponseCreated.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseCreated(obj: any): obj is HttpResponseCreated;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseCreated

isHttpResponseNoContent

Check if an object is an instance of HttpResponseNoContent.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseNoContent(obj: any): obj is HttpResponseNoContent;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseNoContent

isHttpResponseRedirection

Check if an object is an instance of HttpResponseRedirection.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseRedirection(obj: any): obj is HttpResponseRedirection;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseRedirection

isHttpResponseRedirect

Check if an object is an instance of HttpResponseRedirect.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseRedirect(obj: any): obj is HttpResponseRedirect;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseRedirect

isHttpResponseClientError

Check if an object is an instance of HttpResponseClientError.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseClientError(obj: any): obj is HttpResponseClientError;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseClientError

isHttpResponseBadRequest

Check if an object is an instance of HttpResponseBadRequest.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseBadRequest(obj: any): obj is HttpResponseBadRequest;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseBadRequest

isHttpResponseUnauthorized

Check if an object is an instance of HttpResponseUnauthorized.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseUnauthorized(obj: any): obj is HttpResponseUnauthorized;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseUnauthorized

isHttpResponseForbidden

Check if an object is an instance of HttpResponseForbidden.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseForbidden(obj: any): obj is HttpResponseForbidden;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseForbidden

isHttpResponseNotFound

Check if an object is an instance of HttpResponseNotFound.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseNotFound(obj: any): obj is HttpResponseNotFound;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseNotFound

isHttpResponseMethodNotAllowed

Check if an object is an instance of HttpResponseMethodNotAllowed.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseMethodNotAllowed(obj: any): obj is HttpResponseMethodNotAllowed;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseMethodNotAllowed

isHttpResponseConflict

Check if an object is an instance of HttpResponseConflict.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseConflict(obj: any): obj is HttpResponseConflict;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseConflict

isHttpResponseServerError

Check if an object is an instance of HttpResponseServerError.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseServerError(obj: any): obj is HttpResponseServerError;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseServerError

isHttpResponseInternalServerError

Check if an object is an instance of HttpResponseInternalServerError.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseInternalServerError(obj: any): obj is HttpResponseInternalServerError;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseInternalServerError

isHttpResponseNotImplemented

Check if an object is an instance of HttpResponseNotImplemented.

This function is a help when you have several packages using @foal/core. Npm can install the package several times, which leads to duplicate class definitions. If this is the case, the keyword instanceof may return false while the object is an instance of the class. This function fixes this problem.

function isHttpResponseNotImplemented(obj: any): obj is HttpResponseNotImplemented;

Parameters

Name

Type

Description

obj

any

- The object to check.

Return type

obj is HttpResponseNotImplemented

Hook

Create a hook from a function.

function Hook(hookFunction: HookFunction): HookDecorator;

Parameters

Name

Type

Description

hookFunction

HookFunction

- The function from which the hook should be created.

Return type

HookDecorator

getHookFunction

Get the function from which the hook was made.

function getHookFunction(hook: HookDecorator): HookFunction;

Parameters

Name

Type

Description

hook

HookDecorator

- The hook decorator.

Return type

HookFunction

makeControllerRoutes

Recursively create the routes of a controller and its subcontrollers from the controller class definition.

function makeControllerRoutes(parentPath: string, parentHooks: HookFunction[], controllerClass: Class, services: ServiceManager): Route[];

Parameters

Name

Type

Description

parentPath

string

- Prefix of all the route paths.

parentHooks

HookFunction[]

- First hooks of all the route hooks.

controllerClass

Class

- The controller class.

services

ServiceManager

- The application services.

Return type

Route[]

getPath

Get the path of a controller method.

function getPath(target: Class, propertyKey?: string | undefined): string | undefined;

Parameters

Name

Type

Description

target

Class

- The controller class.

propertyKey

string | undefined

- The method name.

Return type

string | undefined

getHttpMethod

Get the HTTP method of a controller method.

function getHttpMethod(target: Class, propertyKey?: string | undefined): string | undefined;

Parameters

Name

Type

Description

target

Class

- The controller class.

propertyKey

string | undefined

- The method name.

Return type

string | undefined

createController

Create a new controller with its dependencies.

function createController<Controller>(controllerClass: Class<Controller>, dependencies?: object | ServiceManager): Controller;

Type parameters

Name

Controller

Parameters

Name

Type

Description

controllerClass

Class

- The controller class.

dependencies

object | ServiceManager

- Either a ServiceManager or an

object which key/values are the controller properties/instances. |

Return type

Controller

createService

Create a new service with its dependencies.

function createService<Service>(serviceClass: Class<Service>, dependencies?: object | ServiceManager): Service;

Type parameters

Name

Service

Parameters

Name

Type

Description

serviceClass

Class

- The service class.

dependencies

object | ServiceManager

- Either a ServiceManager or an

object which key/values are the service properties/instances. |

Return type

Service

dependency

Decorator injecting a service inside a controller or another service.

function dependency(target: any, propertyKey: string): void;

Parameters

Name

Type

target

any

propertyKey

string

Return type

void

createApp

Create an express application from the root controller of the Foal project.

function createApp(rootControllerClass: Class, options: CreateAppOptions = {}, expressInstance?: any): any;

Parameters

Name

Type

Default value

Description

rootControllerClass

Class

- The root controller, usually called AppController and located in src/app.

options

CreateAppOptions

{}

- Optional options to specify the session store (default is MemoryStore).

expressInstance

any

- Optional express instance to be used as base.

Return type

any

Interfaces

LogOptions

Options of the Log hook.

interface LogOptions {
body?: boolean | undefined;
params?: boolean | undefined;
headers?: string[] | boolean;
query?: boolean | undefined;
logFn?: ((message?: any, ...optionalParams: any[]) => void) | undefined;
}

Properties

Name

Type

Optional

body

boolean | undefined

true

params

boolean | undefined

true

headers

string[] | boolean

true

query

boolean | undefined

true

logFn

((message?: any, ...optionalParams: any[]) => void) | undefined

true

HTTPRequest

Interface of the express request object. It also includes a session property and a csrfToken method.

interface HTTPRequest extends Request {
session: any;
csrfToken: () => string;
}

Extends

Request

Properties

Name

Type

Optional

session

any

false

csrfToken

() => string

false

CookieOptions

Cookie options of the HttpResponse.setCookie method.

interface CookieOptions {
domain?: string | undefined;
expires?: Date | undefined;
httpOnly?: boolean | undefined;
maxAge?: number | undefined;
path?: string | undefined;
secure?: boolean | undefined;
sameSite?: "strict" | "lax";
}

Properties

Name

Type

Optional

domain

string | undefined

true

expires

Date | undefined

true

httpOnly

boolean | undefined

true

maxAge

number | undefined

true

path

string | undefined

true

secure

boolean | undefined

true

sameSite

"strict" | "lax"

true

Route

Represent a Foal route with its controller handler and hooks.

interface Route {
httpMethod: HttpMethod;
path: string;
hooks: HookFunction[];
controller: any;
propertyKey: string;
}

Properties

Name

Type

Optional

httpMethod

HttpMethod

false

path

string

false

hooks

HookFunction[]

false

controller

any

false

propertyKey

string

false

CreateAppOptions

Options of the createApp function.

interface CreateAppOptions {
store(session: any)?: any;
}

Method

store(session: any)?: any;

Parameters

Name

Type

session

any

Return type

any

Types

Class

Interface of a class from its class definition.

type Class<T = any> = new (args: any[]) => T;

Type parameters

Name

Default

T

any

Type

new (args: any[]) => T

HttpMethod

HTTP methods available.

type HttpMethod = "POST" | "GET" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";

Type

"POST" | "GET" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"

HookPostFunction

Interface of a function that can be returned in a hook function. This function is then executed after the controller method execution.

type HookPostFunction = (ctx: Context<any>, services: ServiceManager, response: HttpResponse) => void | Promise<void>;

Type

(ctx: Context, services: ServiceManager, response: HttpResponse) => void | Promise

HookFunction

Interface of a function from which a hook can be created.

type HookFunction = (ctx: Context<any>, services: ServiceManager) => void | HttpResponse | HookPostFunction | Promise<void | HttpResponse | HookPostFunction>;

Type

(ctx: Context, services: ServiceManager) => void | HttpResponse | HookPostFunction | Promise

HookDecorator

Interface of a hook. It is actually the interface of a decorator.

type HookDecorator = (target: any, propertyKey?: string | undefined) => any;

Type

(target: any, propertyKey?: string | undefined) => any

Classes

Represent an object that was expected to be found but that does not exist.

Represent the prohibition to perform an action that was expected to be accessible.

Represent an incorrect data format.

Context

Class instantiated on each request. It includes:

  • the express request object,

  • the user object if available,

  • and a state object that can be used to pass data across several hooks.

Reprensent an HTTP response. This class must be extended. Instances of HttpResponse are returned in hooks and controller methods.

Represent an HTTP response with a success status 2xx.

Represent an HTTP response with the status 200 - OK.

Represent an HTTP response with the status 201 - CREATED.

Represent an HTTP response with the status 204 - NO CONTENT.

Represent an HTTP response with a redirection status 3xx.

Represent an HTTP response with the status 302 - FOUND.

Represent an HTTP response with a client error status 4xx.

Represent an HTTP response with the status 400 - BAD REQUEST.

Represent an HTTP response with the status 401 - UNAUTHORIZED.

Represent an HTTP response with the status 403 - FORBIDDEN.

Represent an HTTP response with the status 404 - NOT FOUND.

Represent an HTTP response with the status 405 - METHOD NOT ALLOWED.

Represent an HTTP response with the status 409 - CONFLICT.

Represent an HTTP response with a server error status 5xx.

Represent an HTTP response with the status 500 - INTERNAL SERVER ERROR.

Represent an HTTP response with the status 501 - NOT IMPLEMENTED.

Config

Static class to access environment variables and configuration files.

This class can also be used as a service.

Identity Mapper that instantiates and returns service singletons.

ClassDeclaration-21: index/servicemanager.md#servicemanager