Skip to content

API Reference ​

This page lists the public exports of @meghjs/core, grouped by area. Each group links to the guide that explains it in depth. Everything here is imported from the package root:

ts
import { Megh, ApiController, Get, Results } from "@meghjs/core";

The command-line tool, @meghjs/cli, is documented separately under CLI.

Signatures are shown as TypeScript. Optional parameters end in ?, and Constructor<T> means a class that builds a T.

Application ​

Guides: Usage, Application.

Creating an application ​

ExportKindDescription
MeghclassEntry point. Megh.createApplication(options?) returns the application; Megh.createTestApplication(options) returns a test client.
MeghApplicationclassThe application object returned by Megh.createApplication(). Its methods are listed below.
ts
Megh.createApplication(options?: MeghApplicationOptions): MeghApplication
Megh.createTestApplication(options: TestAppOptions): TestApplication

Megh.createApplication() returns the same instance every time it's called in a process.

MeghApplicationOptions fields:

OptionTypeDescription
serverFastifyServerOptionsOptions passed to the Fastify instance.
requestIdRequestIdOptionsRequest ID header and generator, or false to turn request IDs off.
experimentalExperimentalOptions{ compiledValidation?: boolean }. Defaults to the MEGH_COMPILED_VALIDATION environment variable.
pluginsMeghPlugin[]Plugins to register explicitly.
autoloadPluginsbooleanFind plugins among the app's dependencies. Defaults to true.

MeghApplication methods ​

Every use*, on* and addHealthCheck method returns the application, so calls chain.

Features ​

MethodDescription
useControllers(controllers: Constructor[] | { auto: true; path?: string })Register controller classes, or scan a directory for them.
useCors(options: CorsOptions)Enable CORS through @fastify/cors.
useSecurityHeaders(options?: SecurityHeadersOptions)Send CSP, HSTS, X-Frame-Options, nosniff and other security headers on every response. Throws if called twice. See Security.
useRateLimit(options?: RateLimitOptions)Limit requests per client per window (default 100 a minute per IP, in memory) and answer 429 over it. Throws if called twice. See Security.
useMultipart(options?: any)Enable multipart bodies through @fastify/multipart. Defaults: attachFieldsToBody: true, 10 MB file size limit.
useStaticFiles(options?: any)Serve static files through @fastify/static.
useCompression(options?: CompressionOptions)Compress responses through @fastify/compress.
setGlobalPrefix(prefix: string, options?: { exclude?: (string | RegExp)[] })Serve controller and inline routes under prefix.
useVersioning(options: VersioningOptions)Version controller routes by URI (/v1/...) or header.
useEnvSchema(schema: Constructor)Validate environment variables against a DTO class at boot.
useOpenApi(options?: OpenApiUiOptions | Constructor<MeghConfig<OpenApiUiOptions>>)Generate the OpenAPI document and serve the docs page.
useMiddlewares(middlewares: Constructor<MeghMiddleware>[])Register global middleware, run before every route.
useAuthentication(authentication: Constructor<MeghAuthentication>)Register the authentication handler that sets request.user.
useAuthorization(authorization: Constructor<any> | Record<string, Constructor<any>>)Register one authorization handler, or several by name.
useExceptionFilters(filters: ExceptionFilterLike | ExceptionFilterLike[])Register global exception filters, run in order before the default error response.
useErrorHandler(handler: ErrorHandlerFunction)Register a function filter that sees every error.
useErrorLogger(logger: ErrorLogger | false)Replace how default error responses are logged, or turn logging off.
useHealth(options?: HealthOptions)Serve GET /health (liveness) and GET /ready (readiness).
addHealthCheck(name: string, check: HealthCheck)Add a readiness check reported by GET /ready.
useCache(options?: CacheOptions)Configure CacheManager and register it in the container.
useScheduler(tasks: Constructor[] | { path: string })Register @ScheduledTask classes, or scan a directory for them.
useWorker(workers: Constructor<any>[])Resolve and start @Queue and @MeghWorker classes. They close on shutdown.
useMail(options?: MailConfig | Constructor<MeghConfig<MailConfig>>)Configure Mailer over MEGH_MAIL_*, and start the mail queue's worker when queue is set. Throws when the default mailer is misconfigured. See Mail.
useSocketIo(options?: any)Enable Socket.IO through fastify-socket.io.
useGlobal(options: GlobalOptions)Call several use* methods from one object (cors, openApi, controllers, middlewares, authorization, multipart, staticFiles, securityHeaders, rateLimit).
useMeghORM(options?: DatabaseOptions | MeghConfigClass<DatabaseOptions>)Connect Megh ORM. Added by the built-in ORM plugin. See ORM.
useDatabase(db: Kysely<any>)Deprecated. Use an existing Kysely instance as the ORM connection. Use useMeghORM() instead.

Functional routes ​

MethodDescription
mapGet(path: string, fn)Register a GET route handled by a function.
mapPost(path: string, fn)Register a POST route handled by a function.
mapPut(path: string, fn)Register a PUT route handled by a function.
mapPatch(path: string, fn)Register a PATCH route handled by a function.
mapDelete(path: string, fn)Register a DELETE route handled by a function.

Each map* method returns a route builder with three chainable methods: useMiddleware(middleware | middleware[]), authorized(options?: string | { name?: string }) and useOpenApi(options: OpenApiOptions).

Lifecycle ​

MethodDescription
run(port?: number, options?: RunOptions | CallableFunction): Promise<void>Start the server. port defaults to 4000. A function as the second argument is called once the server is listening.
close(): Promise<void>Stop the server, scheduled tasks and workers, then run the onClose hooks. Calling it again returns the same promise.
onInit(hook: LifecycleHook)Run hook during run(), after the database connects and before the server listens.
onReady(hook: LifecycleHook)Run hook once the server is listening.
onClose(hook: LifecycleHook)Run hook on shutdown (close(), SIGTERM or SIGINT), in reverse registration order.

RunOptions:

OptionTypeDescription
hoststringInterface to listen on. Defaults to process.env.HOST, else 0.0.0.0.
onListenCallableFunctionCalled once the server is listening.
shutdownTimeoutnumberMilliseconds to wait for a graceful shutdown before exiting with code 1. Defaults to 10000.

Other members ​

MemberDescription
app: FastifyInstanceThe underlying Fastify instance.
getPlugins(): readonly string[]Names of the registered plugins, in registration order.
isDevelopment(): booleantrue only when NODE_ENV is exactly "development".
installErrorHandling()Internal. Installs the error and not-found handlers. run() calls it.
MeghApplication.getApp(options?)Static. Returns the shared instance, creating it on first call. Options passed to later calls are ignored, with a warning. Megh.createApplication() calls it.
MeghApplication.getInternalApp(options?)Static, deprecated, internal. Creates a new, unshared instance.

Application types ​

ExportKindDescription
MeghApplicationOptionstypeOptions for Megh.createApplication().
IMeghApplicationinterfaceThe core method set of MeghApplication.
RunOptionstypeOptions for app.run().
LifecycleHooktype() => void | Promise<void>.
ExperimentalOptionstype{ compiledValidation?: boolean }.
CorsOptionstypeOptions for useCors().
GlobalOptionstypeOptions for useGlobal().
AutoControllerOptionstype{ auto: true; path?: string } for useControllers().
CacheOptionstype{ provider: "memory" | "redis"; redisOptions?: RedisOptions } for useCache().

Controllers and routing ​

Guide: Controllers.

Decorators ​

ExportKindSignatureDescription
ApiControllerdecorator@ApiController, @ApiController(path: string, options?: ControllerOptions), @ApiController(options: ControllerOptions)Mark a class as a controller and register it for DI. Path defaults to /.
Getdecorator@Get(pathOrOptions?: string | RouteMethodOptions, options?: RouteMethodOptions)Handle GET requests. Path defaults to /.
Postdecoratorsame as GetHandle POST requests.
Putdecoratorsame as GetHandle PUT requests.
Patchdecoratorsame as GetHandle PATCH requests.
Deletedecoratorsame as GetHandle DELETE requests.
Optionsdecoratorsame as GetHandle OPTIONS requests.
Alldecoratorsame as GetHandle every HTTP method Fastify supports.
Routedecorator@Route(method: RouteMethods, pathOrOptions?, options?)Generic form of the method decorators above.
HttpCodedecorator@HttpCode(statusCode: number)Status code for a successful response. A returned Results.* or HttpResponse.* status wins. Throws for codes outside 100–599.
Redirectdecorator@Redirect(url: string, statusCode = 302)Redirect instead of sending the return value. Returning { url, statusCode } overrides both. Throws for non-3xx codes.
ResponseHeaderdecorator@ResponseHeader(name: string, value: string)Set a response header on the route. Stackable.
Versiondecorator@Version(version: string | string[])API version(s) of a controller or route, with useVersioning().
VersioningOptionstype{ type: 'uri'; prefix?; defaultVersion? } | { type: 'header'; header?; defaultVersion? }Options for useVersioning().

Types ​

ExportKindDescription
ControllerOptionstype{ name?: string; path?: string }. name is the OpenAPI tag; it defaults to the class name without Controller.
RouteMethodOptionstype{ method?: RouteMethods; path?: string; openapi?: OpenApiOptions; name?: string }.
RouteMethodstype"GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" | "ALL".

Parameters ​

Guide: Controllers.

The parameter decorators take an optional key and an optional options object, in either order of presence:

ts
(key?: string | ParameterOptions, options?: ParameterOptions) => ParameterDecorator
// ParameterOptions: { required?: boolean; validate?: boolean; type?: any }

required and validate default to true. type is only needed when the compiler doesn't emit decorator metadata (tsx, esbuild, SWC).

ExportKindDescription
ParamdecoratorA route parameter (@Param("id")), or all of them with no key.
QuerydecoratorA query string value, or the whole query (often a DTO) with no key.
BodydecoratorThe request body, usually a DTO, or one field with a key.
HeaderdecoratorA request header, or all headers with no key.
AuthUserdecoratorrequest.user, as set by the authentication handler.
MeghRequestdecorator@MeghRequest(). The request object itself.
UploadFiledecorator@UploadFile(fieldName: string). One uploaded file from a multipart field.
UploadFilesdecorator@UploadFiles(fieldName?: string). Uploaded files from a field, or from every field with no name.

Responses ​

Guide: Controllers.

Results ​

ExportKindDescription
ResultsclassStatic factories for route results (below).
HttpResultabstract classBase class for values that control status, headers and body.
Okclass200 { data }.
Createdclass201 { data }.
NoContentclass204 with an empty body.
NotFoundclass404 { code, status, message }.
OkStreamclass200 with a stream body.
RedirectResultclassA 3xx with Location; made by Results.Redirect(url, statusCode?).
OkStreamOptionstype{ contentType?: string; filename?: string }. With filename, the stream is sent as an attachment.
RouteResulttypetypeof Results.Ok<T>.
ts
Results.Ok<T>(data: T): Ok<T>
Results.Created<T>(data: T): Created<T>
Results.NoContent(): NoContent
Results.NotFound<T>(message: T): NotFound<T>
Results.Redirect(url: string, statusCode = 302): RedirectResult
Results.OkStream(stream: Readable, options?: OkStreamOptions): OkStream

HttpResponse ​

ExportKindDescription
HttpResponseclassStatic factories that return { message, data } bodies.
IHttpResponseinterface{ message: string; data: T | null }.
withStatusfunctionwithStatus(body, statusCode). Attach a status code to a plain object without changing its JSON.
HTTP_STATUS_KEYconstSymbol withStatus uses to store the status.
ts
HttpResponse.Ok<T>(obj: any, dto?: ClassConstructor<T>): IHttpResponse<T>       // 200
HttpResponse.Created<T>(obj: any, dto?: ClassConstructor<T>): IHttpResponse<T>  // 201
HttpResponse.NoContent(): IHttpResponse<null>                                   // 204

With a DTO class, Ok and Created keep only the DTO's exposed fields (class-transformer excludeExtraneousValues).

Pagination and collections ​

ExportKindDescription
paginatedfunctionpaginated(data: T[], total, page, perPage): Paginated<T>. Wrap a page of data with its meta.
Paginatedfunction and interfaceAs a type, { data: T[]; meta: PaginationMeta }. As a function, Paginated(Item) marks a page of Item for OpenAPI: @ApiResponse(200, Paginated(User)).
PaginationMetainterface{ total, page, perPage, lastPage, next, prev }.
PageRequestinterface{ page?, perPage? }, plus the deprecated limit, take and skip.
normalizePageRequestfunctionResolve a PageRequest into { page, perPage, offset }.
buildPaginationMetafunctionbuildPaginationMeta(total, page, perPage): PaginationMeta.
DEFAULT_PER_PAGEconst10.
PAGINATED_ITEMconstSymbol used by Paginated(Item).
PaginationResulttypeDeprecated alias of Paginated<T>.
ListclassSmall in-memory list with async Find and FindOne. List.from(items).
IListinterfaceThe List surface.
CollectionclassIn-memory collection: Collection.from(items) with find, findOne, their async forms and clear.
BasicCollectioninterfaceThe Collection surface.
IFindOneOptionsinterface{ where } argument for Collection.findOne.

Exceptions and error handling ​

Guide: Error handling.

HTTP exceptions ​

Every exception takes (message?: any, options?: HttpExceptionOptions). A string message is sent as message; an object is sent as data. HttpExceptionOptions is { cause?: unknown; headers?: Record<string, string | number | string[]> }.

ExportKindStatus
BaseHttpExceptionabstract classBase class. code, statusCode, payload, headers.
HttpExceptionclassAny status: new HttpException(status: number, message?, options?).
BadRequestExceptionclass400
ValidationErrorExceptionclass400. new ValidationErrorException(message?, errors?: unknown[], options?); errors is sent in the response.
UnauthorizedExceptionclass401
ForbiddenExceptionclass403
NotFoundExceptionclass404
MethodNotAllowedExceptionclass405
NotAcceptableExceptionclass406
RequestTimeoutExceptionclass408
ConflictExceptionclass409
GoneExceptionclass410
PayloadTooLargeExceptionclass413
UnsupportedMediaTypeExceptionclass415
UnprocessableEntityExceptionclass422
TooManyRequestsExceptionclass429
InternalErrorExceptionclass500
NotImplementedExceptionclass501
BadGatewayExceptionclass502
ServiceUnavailableExceptionclass503
GatewayTimeoutExceptionclass504
HttpExceptionsconstFactory shortcuts, such as HttpExceptions.notFound("User not found") and HttpExceptions.status(402, "Payment required").
HttpExceptionOptionsinterface{ cause?, headers? }.
HttpExceptionTypestypeUnion of the not-found, bad-request, unauthorized, internal-error and forbidden exceptions.

Exception filters ​

ExportKindSignature / description
Catchdecorator@Catch(...types: ErrorClass[]). Limit a filter class to these error classes and register it for DI.
UseFiltersdecorator@UseFilters(...filters: ExceptionFilterLike[]). Apply filters to a controller or route. They run before the global filters.
ExceptionFilterinterface{ catch(error: E, ctx: ErrorContext): unknown }.
ErrorHandlerFunctiontype(error: E, ctx: ErrorContext) => unknown.
ExceptionFilterLiketypeA filter class, a filter instance or an ErrorHandlerFunction.
ErrorContextinterface{ request, reply, isDevelopment, response }.
ErrorResponseinterface{ statusCode, headers?, body }.
ErrorResponseBodyinterfaceThe default JSON error body: { code, status, message, data?, errors?, error?, stack? }.
ErrorLoggertype(error, request, response) => void, for useErrorLogger().
ErrorHandlerOptionsinterface{ isDevelopment?: () => boolean; logger?: ErrorLogger | false }.
defaultErrorResponsefunctiondefaultErrorResponse(error, isDevelopment): ErrorResponse. The response Megh sends when no filter handles an error.
defaultErrorLoggerconstThe default ErrorLogger: 4xx as warnings, others as errors with the stack.
MeghErrorHandlerclassMegh's request error handler. The application creates one; you don't normally construct it.

Validation ​

Guide: Validation.

Validation decorators ​

Every decorator takes an optional last argument, options?: ValidationOptions (message, each, groups, and so on, as in class-validator).

ExportKindSignature
IsOptionaldecorator@IsOptional(options?)
ValidateIfdecorator@ValidateIf(condition: (object, value) => boolean, options?)
Allowdecorator@Allow(options?)
ValidateNesteddecorator@ValidateNested(options?)
IsDefineddecorator@IsDefined(options?)
IsNotEmptydecorator@IsNotEmpty(options?)
IsEmptydecorator@IsEmpty(options?)
IsIndecorator@IsIn(values: readonly any[], options?)
IsNotIndecorator@IsNotIn(values: readonly any[], options?)
IsStringdecorator@IsString(options?)
IsNumberdecorator@IsNumber(numberOptions?: IsNumberOptions, options?)
IsIntdecorator@IsInt(options?)
IsBooleandecorator@IsBoolean(options?)
IsDatedecorator@IsDate(options?)
IsArraydecorator@IsArray(options?)
IsObjectdecorator@IsObject(options?)
IsEnumdecorator@IsEnum(entity: object, options?)
Mindecorator@Min(minValue: number, options?)
Maxdecorator@Max(maxValue: number, options?)
IsPositivedecorator@IsPositive(options?)
IsNegativedecorator@IsNegative(options?)
MinLengthdecorator@MinLength(min: number, options?)
MaxLengthdecorator@MaxLength(max: number, options?)
Lengthdecorator@Length(min: number, max?: number, options?)
Matchesdecorator@Matches(pattern: RegExp, options?) or @Matches(pattern: string | RegExp, modifiers?: string, options?)
IsEmaildecorator@IsEmail(emailOptions?: object, options?)
IsUUIDdecorator@IsUUID(version?, options?)
IsUrldecorator@IsUrl(urlOptions?: object, options?)
ArrayMinSizedecorator@ArrayMinSize(min: number, options?)
ArrayMaxSizedecorator@ArrayMaxSize(max: number, options?)
ArrayNotEmptydecorator@ArrayNotEmpty(options?)
IsArrayNotEmptydecorator@IsArrayNotEmpty(validationOptions?). A class-validator decorator (requires class-validator). Prefer ArrayNotEmpty.

Transformation ​

ExportKindSignature / description
Typedecorator@Type(typeFunction?: (options?: TypeHelpOptions) => Function, options?: TypeOptions). The class a property's value is converted to. Needed for @ValidateNested and for query values.
Transformdecorator@Transform(transformFn: (params: TransformFnParams) => any, options?: TransformDecoratorOptions). Change a property's value while the body becomes the DTO.
TransformationTypeenumThe direction passed to a @Transform function, as in class-transformer.

Mapped types ​

ExportKindSignature
PartialTypefunctionPartialType(Base: Constructor<T>): Constructor<Partial<T>>
PickTypefunctionPickType(Base: Constructor<T>, keys: K[]): Constructor<Pick<T, K>>
OmitTypefunctionOmitType(Base: Constructor<T>, keys: K[]): Constructor<Omit<T, K>>

Running validation yourself ​

ExportKindDescription
validateDtofunctionvalidateDto(target, value): DtoValidationResult<T>. Convert and validate a value with Megh's decorators.
transformAndValidatefunctiontransformAndValidate(target, value, options?): Promise<RequestValidationResult<T>>. The same with class-validator and class-transformer.
ValidatorclassRule-based validator for plain objects: new Validator(rules: ValidationProps, options?).validate(obj) returns [issues, obj].
validateOrThrowfunctionvalidateOrThrow(obj, rules: ValidationProps, options?). Validate with Validator and throw BadRequestException on failure.
isMeghValidatorClassfunctionWhether a class uses Megh's validation decorators.

Validation types ​

ExportKindDescription
ValidationOptionstypeOptions every validation decorator takes.
ValidationArgumentstypeWhat a message function receives.
IsNumberOptionstype{ allowNaN?, allowInfinity?, maxDecimalPlaces? }.
TypeOptionstypeOptions for @Type. discriminator isn't supported yet.
TypeHelpOptionstypeWhat a @Type function receives.
TransformFnParamstypeWhat a @Transform function receives.
TransformDecoratorOptionstypeOptions for @Transform.
ValidationIssuetypeOne issue from validateDto.
DtoValidationResulttypeResult of validateDto.
RequestValidationIssuetypeOne issue from transformAndValidate.
RequestValidationResulttypeResult of transformAndValidate.
ValidationRuletypeA Validator rule: { type: "string" | "number" | "boolean", required?, optional?, message?, min?, max?, exact? }.
ValidationPropstypeRecord<string, ValidationRule>.
ValidateOptonstype{ location?: "header" | "queryparam" | "param" | "body" | "custom" }, for Validator.
ValidatorIssuetypeOne issue from Validator.

Dependency injection ​

Guide: Dependency injection.

ExportKindSignature / description
Injectabledecorator@Injectable(). Make a class resolvable by the container. Constructor parameters are injected from their types.
AppServicedecorator@AppService or @AppService(). Same as @Injectable(), for service classes.
UtilitydecoratorAlias of Injectable: @Utility().
HelperdecoratorAlias of Injectable: @Helper().
injectfunctioninject<T>(id: ServiceIdentifier<T>, options?: InjectOptions): T. Resolve a dependency, usually in a field initializer. With { optional: true } it returns undefined when nothing is registered.
createInjectDecoratorfunctioncreateInjectDecorator(factory: () => unknown). Build a property or parameter decorator that injects factory().
MeghContainerconstThe container: get(id), set(id, value), has(id), reset().
Tokenclassnew Token<T>(name?: string). A typed identifier for values that aren't classes.
ContainerErrorclassThrown when the container can't resolve or construct a service.
ContainerApiinterfaceThe MeghContainer surface.
ServiceIdentifiertypeA class, abstract class, Token or string.
Constructabletypenew (...args: any[]) => T.
InjectOptionstype{ optional?: boolean }.

Middleware ​

Guide: Middleware.

ExportKindSignature / description
MeghMiddlewareabstract classinvoke(req: IRequest, res?: IResponse): Promise<IRequest | HttpException>.
AppMiddlewaredecorator@AppMiddleware. Register a middleware class for DI. Throws if it has no invoke method.
UseMiddlewaredecorator@UseMiddleware(middleware | middleware[]). Apply middleware classes or instances to a controller or route.

Global middleware is registered with app.useMiddlewares([...]).

Authentication and authorization ​

Guide: Authentication.

ExportKindSignature / description
MeghAuthenticationabstract classauthenticate(request: IRequest): TUser | null | undefined | Promise<...>. The return value becomes request.user. Register with app.useAuthentication().
CanAuthorizedecorator@CanAuthorize. Mark a class with an authorize(req, options?) method as an authorization handler and register it for DI.
Authorizeddecorator@Authorized(), @Authorized(name: string) or @Authorized({ name?, ...options }). Require authorization on a controller or route. Extra options are passed to authorize().
AuthorizeClassinterface{ authorize(req: IRequest, options?: any): unknown }. Return false or throw to deny with 403.
AuthorizedOptionstypestring | { name?: string; [key: string]: any }.

Security headers and rate limiting ​

Guide: Security Hardening.

ExportKindSignature / description
SecurityHeadersOptionstype{ contentSecurityPolicy?, strictTransportSecurity?, frameOptions?, referrerPolicy?, crossOriginOpenerPolicy?, crossOriginResourcePolicy?, crossOriginEmbedderPolicy?, headers? } for useSecurityHeaders(). false leaves a header out.
ContentSecurityPolicyOptionstype{ directives?: Record<string, CspDirectiveValue>; useDefaults?: boolean; reportOnly?: boolean }.
CspDirectiveValuetypestring | string[] | boolean. true is a bare directive, false removes it.
StrictTransportSecurityOptionstype{ maxAge?: number; includeSubDomains?: boolean; preload?: boolean }.
ReferrerPolicytypeA Referrer-Policy token, such as "no-referrer".
RateLimitdecorator@RateLimit(options: RouteRateLimitOptions | false). A controller's or route's own limit and counter, or false for none. Works without useRateLimit().
RateLimitOptionstype{ max?, window?, key?, skip?, store?, redis?, headers?, message?, failOpen?, global? } for useRateLimit().
RouteRateLimitOptionstype{ max?: number; window?: RateLimitWindow; key?: (req) => string | Promise<string> }.
RateLimitWindowtypenumber | string. Milliseconds, or a duration such as '30s', '15m', '1 hour'.
RateLimitStoreinterface{ hit(key, windowMs): RateLimitHit | Promise<RateLimitHit>; reset?(key); close?() }. Where counts live.
RateLimitHittype{ count: number; resetAt: number }. resetAt is epoch milliseconds.
MemoryRateLimitStoreclassThe default store: fixed-window counts in memory, per process.
RedisRateLimitStoreclassnew RedisRateLimitStore(redis, { prefix? }). Counts in Redis, shared by replicas. Takes an ioredis client, which it does not close.
RedisEvalClientinterfaceThe part of an ioredis client the Redis store uses: eval and del.

Configuration and environment ​

Guide: Configuration.

ExportKindSignature / description
MeghConfigabstract classconfig(env: Environment): T. Base class for a config class.
AppConfigdecorator@AppConfig or @AppConfig({ schema }). Register a MeghConfig subclass for DI; with schema, its config() result is validated against that DTO class on first use and at boot.
AppConfigOptionstype{ schema?: Constructor }.
validateEnvfunctionvalidateEnv(EnvDto, source?) validates environment variables against a DTO class and returns them converted.
ConfigValidationErrorclassThrown for an invalid environment or config; source and issues say what failed.
GetConfigfunctionGetConfig(ConfigClass) returns the class's config() result; GetConfig(token: string | symbol) returns the value registered for the token.
MeghConfigClasstypeA MeghConfig subclass.
EnvironmentclassReads .env merged with process.env (which wins): get(key), getOrThrow(key), getAll(), and static reload() to re-read .env.
EnvironmentVariableNotFoundclassError thrown by getOrThrow() for a missing variable; the name is in key.

ORM ​

Guides: ORM, Models, Queries, Relations, Migrations, Seeding, Query builder.

The ORM ships inside @meghjs/core as a built-in plugin. Connect it with app.useMeghORM().

Models ​

ExportKindDescription
Modelabstract classBase class for models. Static query methods (query, find, findOrFail, where, with, create, paginate, transaction, …) and instance methods (save, fill, delete, restore, related, …).
ModelQueryclassA query on a model. Nothing runs until get(), first(), count(), paginate(), update() or delete().
HasRelationclassA hasMany / hasOne relation of one model instance: user.related("posts").
PivotRelationclassThe pivot rows of a belongsToMany relation: user.related("roles").attach([1, 2]).
ORM_CONNECTIONconstToken<Kysely<any>> holding the ORM's root Kysely instance.
modelSchemafunctionmodelSchema(cls): SchemaObject | undefined. JSON schema for a model's columns.
getModelMetadatafunctiongetModelMetadata(cls): ModelMetadata | undefined. Column and table metadata from the decorators.

Model decorators ​

ExportKindSignature
Tabledecorator@Table(name?: string). Defaults to the plural snake_case class name.
Columndecorator@Column(typeOrOptions?: ColumnType | ColumnOptions, options?: ColumnOptions)
PrimaryKeydecorator@PrimaryKey(options?: ColumnOptions)
AutoIncrementdecorator@AutoIncrement(). A generated integer column.
IdentitydecoratorAlias of AutoIncrement.
CreatedAtdecoratorSet to the current time on insert.
UpdatedAtdecoratorSet to the current time on every insert and update.
DeletedAtdecoratorSoft deletes: delete() sets this column instead of removing the row.
HasManydecorator and type@HasMany(related: () => C, options?: HasOptions). As a type, the field type of a one-to-many relation.
HasOnedecorator and type@HasOne(related: () => C, options?: HasOptions).
BelongsTodecorator and type@BelongsTo(related: () => C, options?: BelongsToOptions).
BelongsToManydecorator and type@BelongsToMany(related: () => C, options?: BelongsToManyDecoratorOptions).

Relation functions ​

For models that declare relations as fields instead of decorators.

ExportKindSignature
hasManyfunctionhasMany(related: () => C, foreignKey?: string, localKey?: string)
hasOnefunctionhasOne(related: () => C, foreignKey?: string, localKey?: string)
belongsTofunctionbelongsTo(related: () => C, foreignKey?: string, ownerKey?: string)
belongsToManyfunctionbelongsToMany(related: () => C, options?: BelongsToManyOptions)

Connection and configuration ​

ExportKindDescription
createDatabasefunctioncreateDatabase(options: ResolvedDatabaseOptions): Kysely<any>.
resolveDatabaseOptionsfunctionresolveDatabaseOptions(options?, env?). Apply environment variables and the URL to database options.
DatabaseConfigErrorclassThrown for invalid database settings.
ormPluginconstThe ORM as a Megh plugin. Registered automatically.
setNamingStrategyfunctionsetNamingStrategy("preserve" | "snake_case").
getNamingStrategyfunctionThe current naming strategy.
DatabaseOptionsinterfaceSettings for useMeghORM().
ResolvedDatabaseOptionsinterfaceSettings after the environment and URL are applied.
Dialecttype"postgres" | "mysql" | "sqlite" | "mssql".
PoolOptionsinterfaceConnection pool settings.
NamingStrategytype"preserve" | "snake_case".

Query builder ​

ExportKindDescription
DBconstTable queries without models: DB.table(name), DB.transaction(fn).
TableQueryclassA query on one table, built with DB.table().
WhereClausesclasswhere conditions shared by queries and groups.
WhereGroupclassThe conditions inside where((q) => …).
OperatortypeComparison operators accepted by TableQuery.

Schema and migrations ​

ExportKindDescription
SchemaclassCreates, changes and drops tables. Migrations defined with defineMigration receive one.
BlueprintclassThe columns and indexes of a table being created or changed.
ColumnDefinitionclassA column being added. Columns are NOT NULL unless nullable().
ForeignKeyDefinitionclassA foreign key: table.foreign("user_id").references("users.id").
SchemaErrorclassThrown for invalid schema operations.
Migrationsclassnew Migrations(db, options). Runs and rolls back migrations.
MigrationErrorclassThrown when a migration fails. Carries the migration name and those completed.
defineMigrationfunctiondefineMigration({ up, down? }). A migration written with the schema builder.
readMigrationFolderfunctionreadMigrationFolder(folder): Promise<Record<string, Migration>>.
MigrationinterfaceA migration as the runner calls it.
SchemaMigrationinterfaceA migration written with the schema builder.
MigrationsOptionsinterfaceOptions for Migrations.
MigrationStatusinterfaceOne migration's status.
ReferentialActiontypeON DELETE / ON UPDATE actions.
SchemaDialecttype"postgres" | "mysql" | "sqlite" | "mssql".

Seeders and factories ​

ExportKindDescription
Seedersclassnew Seeders(db, options?). Runs seeders.
SeedErrorclassThrown when a seeder fails.
defineSeederfunctionIdentity helper that type-checks a seeder.
readSeederFolderfunctionreadSeederFolder(folder): Promise<Record<string, Seeder>>.
seederNamefunctionA seeder's name from its file name.
ENTRY_SEEDERconst"database", the seeder run() starts from when given no name.
SeederinterfaceA seeder.
SeedContextinterfaceWhat a seeder's run() receives.
SeedersOptionsinterfaceOptions for Seeders.
FactoryclassBuilds and creates model instances from a definition.
defineFactoryfunctiondefineFactory(model, definition: (ctx: FactoryContext) => FactoryAttributes<C>): Factory<C>.
useFakerfunctionuseFaker(faker). Set the Faker instance factories use.
getFakerfunctiongetFaker(): Promise<Faker>. The Faker instance, loaded from the app on first use.
FactoryAttributestypeAttributes a factory definition returns.
FactoryContextinterfaceWhat a factory definition receives.

ORM types ​

ExportKindDescription
ColumnTypetypeColumn types, which pick the SQL type and value conversion.
ColumnOptionsinterfaceOptions for @Column.
ColumnMetadatainterfaceA column's metadata.
ModelMetadatainterfaceA model's metadata.
HasOptionsinterfaceOptions for @HasMany and @HasOne.
BelongsToOptionsinterfaceOptions for @BelongsTo.
BelongsToManyOptionsinterfaceOptions for belongsToMany().
BelongsToManyDecoratorOptionsinterfaceOptions for @BelongsToMany, including pivotColumns.
CasttypeA column cast: a built-in name or a CustomCast.
CustomCastinterface{ get, set } conversion between database and model values.
ColumnstypeA model's column fields.
ColumnKeystypeNames of a model's columns.
RelationKeystypeNames of a model's relations.
RelationPathstypeRelation paths for with(), up to three levels.
BelongsToManyKeystypeNames of belongsToMany relations.
HasRelationKeystypeNames of hasMany / hasOne relations.
PivotOftypePivot columns of a belongsToMany relation.
TimestampKeystypeTimestamp columns when timestamps = true.
RowtypeA model's row as loaded from the database.
ModelClassinterfaceThe static side of a model class.
CreateInputtypecreate() input.
UpdateInputtypeupdate() / fill() input.
PrimaryKeyValuetypeValue type of a model's primary key.
TableOftypeKysely table interface for a model.
DatabaseOftypeKysely database interface for a set of models.
ComparisonOperatortypeOperators accepted by where.
CountedtypeThe <relation>_count field withCount() adds.
CursorPageRequestinterfaceRequest for cursorPaginate().
CursorPaginatedinterfaceResult of cursorPaginate().
SimplePaginatedinterfaceResult of simplePaginate() (no total).
ModelAttypeThe model at the end of a relation path.
RelationConstrainttypeA function that narrows a related query.
ScopetypeA reusable query scope.
RelatedReftypeA related row's key, or the related model itself.

Events ​

Guide: Events.

ExportKindSignature / description
MeghEventabstract classnew MyEvent(payload). Base class for events; sets name and timestamp.
MeghEventListenerabstract classhandler(event: TEvent): void | Promise<void>. Base class for listeners.
EventDispatcherclassdispatch(event: MeghEvent, option?: DispatchOption): Promise<void>.
EventRegistryclassEventRegistry.getInstance(), then register(EventClass, listener), once, unregister, getListeners, clear.
EventQueueclassThe in-memory queue for queue: true dispatches. EventQueue.getInstance(), getFailedJobs(), clearFailed(), whenIdle().
DispatchOptiontype{ queue?, delay?, retry?, retryDelay?, broadcast? }. delay is ms or "500ms", "5s", "2m", "1h", "1d".
BroadcastOptiontypeSocketBroadcastOption | false.
SocketBroadcastOptiontype{ type: "socket"; channel: string; room?: string }.
MeghEventInterfaceinterface{ name: string; timestamp: number }.
MeghEventListenerInterfaceinterface{ handler(event): void | Promise<void> }.
FailedEventJobinterfaceA listener that kept failing after its retries.
Broadcastinterface{ to: string; private?: boolean; payload: any }.
parseDelayfunctionparseDelay(input: string | number): number. Parse a delay into milliseconds.

Queue ​

Guide: Queue.

ExportKindSignature / description
Queuedecorator@Queue(config: QueueConfig). Register a MeghQueue subclass for DI and start its worker unless worker: false.
JobHandlerdecorator@JobHandler(name: string). Mark a method as the processor for a named job.
MeghQueueabstract classProduces and consumes jobs: add, delay, dispatch, getJob, getJobs, clean, pause, resume, close, getQueue, getWorker, on, startWorker.
MeghWorkerdecorator@MeghWorker(config: WorkerConfig). Register a standalone worker class. Doesn't start it.
MeghWorkerBaseabstract classprocess(job: Job<T>): Promise<any>. Base class for standalone workers; start(), close(), getWorker().
QueueConfiginterface{ name, adapter?, worker?, handler?, driver? }.
WorkerConfiginterface{ queue, connection?, concurrency?, options?, autoStart?, driver? }.
JobtypeBullMQ's Job, re-exported.
JobsOptionstypeBullMQ's JobsOptions, re-exported.
setQueueDriverfunctionsetQueueDriver(driver: QueueDriver | undefined). Set the default driver.
resolveQueueDriverfunctionresolveQueueDriver(explicit?). The driver in effect: explicit, then setQueueDriver(), then MEGH_QUEUE_DRIVER, then "bullmq".
QueueDrivertype"bullmq" | "memory" | "sync".
waitForMemoryQueuesfunctionResolve when every in-memory queue is idle. For tests.
resetMemoryQueuesfunctionClear every in-memory queue. For tests.
MemoryJobclassA job in the in-memory driver.
MemoryJobStatetype"waiting" | "delayed" | "active" | "completed" | "failed".
getRegisteredWorkersfunctionEvery @MeghWorker class, in declaration order.
startRegisteredWorkersfunctionResolve and start every @MeghWorker whose autoStart isn't false. The application calls it at boot.
attachWorkerLoggingfunctionattachWorkerLogging(worker, queue). Log failed jobs and worker errors.
ts
add(data: T, options?: JobsOptions): Promise<Job<T>>
add(name: string, data: T, options?: JobsOptions): Promise<Job<T>>
delay(data: T, delayMs: number, options?: JobsOptions): Promise<Job<T>>
delay(name: string, data: T, delayMs: number, options?: JobsOptions): Promise<Job<T>>
dispatch(name: string, data: T, delayMs?: number, options?: JobsOptions): Promise<Job<T>>

Mail ​

Guide: Mail.

ExportKindSignature / description
Mailableabstract classOne kind of email. envelope(), content() (required), attachments(); each may be async.
MailerclassInjectable. to(), cc(), bcc(), send(), queue(), later(delay, mail), mailer(name). Static: configure(), fake(), restore(), close(), reset().
PendingMailclassReturned by mailer.to(): add recipients, then send(), queue() or later().
MailFakeclassReturned by Mailer.fake(). assertSent, assertNotSent, assertNothingSent, assertSentCount, assertQueued, assertNotQueued, assertNothingQueued, sentOf, queuedOf, sent, queued, restore.
SentMailclassA recorded message: mailer, mailable, message, delay, hasTo(), hasCc(), hasBcc(), hasFrom().
MailConfiginterface{ default?, from?, mailers?, queue? } for useMail().
MailQueueConfiginterface{ name?, adapter?, driver?, worker?, jobOptions? }.
MailerConfigtypeOne mailer's settings: { transport: "smtp" | "sendgrid" | "mailgun" | "postmark" | "resend" | "failover" | "log" | "array", ... }, or a MailTransport.
MailTransportinterface{ send(message: MailMessage): Promise<{ messageId?, response? } | void>; close?() }. Implement it for your own mailer.
MailMessageinterfaceA built message: from, to, cc, bcc, replyTo, subject, html?, text?, attachments, headers.
MailEnvelope, MailContent, MailAttachment, MailAddress, MailAddressLiketypesWhat a Mailable returns, and address forms.
SentMessage, QueuedMessagetypesWhat send() and queue()/later() resolve to.
SmtpTransport, SendGridTransport, MailgunTransport, PostmarkTransport, ResendTransport, FailoverTransport, LogTransport, ArrayTransportclassesThe built-in transports.
MailQueueclassThe MeghQueue behind queue() and later().
MailErrorclassA misconfiguration, or a mailable that cannot be built.
MailTransportErrorclassA provider refused the message: provider, status, body.
mailConfigFromEnv, resolveMailConfig, mailerProblemfunctionsRead MEGH_MAIL_*, merge options over it, and check a mailer's settings.

Scheduler ​

Guide: Scheduler.

ExportKindSignature / description
ScheduledTaskdecorator@ScheduledTask(). Mark a class as holding scheduled jobs and register it for DI.
Crondecorator@Cron(expression: string, options?: { name?, disabled?, timezone?, runOnInit? }). Run the method on a cron expression (node-cron).
Intervaldecorator@Interval(ms: number, options?: { name?, disabled? }). Run the method every ms milliseconds.
Timeoutdecorator@Timeout(ms: number, options?: { name?, disabled? }). Run the method once, ms milliseconds after start.
MeghSchedulerclassRuns the jobs of registered task classes: addTaskClasses(tasks), start(), stopAll(). The application creates one for useScheduler().

Register task classes with app.useScheduler([...]).

Cache ​

Guide: Caching.

ExportKindSignature / description
CacheManagerclassKey/value cache with tag invalidation, backed by memory or Redis. TTLs are in seconds.
CacheManagerOptionstypeCacheOptions fields plus redis? (an ioredis client) and sweepIntervalMs?.
ts
CacheManager.configure(options?: CacheManagerOptions): void   // defaults for new instances
CacheManager.close(): Promise<void>                           // static: close every instance
get<T>(key: string): Promise<T | null>
set<T>(key: string, value: T, ttl?: number, tags?: string[]): Promise<void>  // ttl defaults to 3600
delete(key: string): Promise<void>
invalidateTags(tags: string | string[]): Promise<void>
sweep(): number
close(): Promise<void>

Enable it with app.useCache(options?).

Storage and uploads ​

Guide: File uploads.

ExportKindDescription
FileStorageclassSaves uploaded files under a root directory (<cwd>/public by default) with an upload policy. Injectable.
UploadFileFromRequestfunctionUploadFileFromRequest(req: IRequest, options?). Save the request's file. Options: saveAs?, dest?, preserveFilename?, allowedExtensions?.
MultipartFiletypeAn uploaded file from @fastify/multipart.
FileStorageInterfaceinterfacetransform, save, saveAll, remove.
FileStorageOptionsinterfaceUploadPolicy plus baseDir?.
UploadPolicyinterface{ allowedExtensions?, allowedMimeTypes?, maxFileSize? }. maxFileSize defaults to 50 MB.
SaveOptionsinterfaceUploadPolicy plus overwrite?, to?, transform?.
SaveOptionsSingleinterfaceSaveOptions for save().
SavedFileInfointerface{ filename, originalFilename, size, uploadPath, staticPath }.
TransformOptionsinterfaceImage transform: { resize?, format?, quality? }.
ts
configure(options: FileStorageOptions): this
transform(options: TransformOptions): FileStorage
save(file: MultipartFile, options?: SaveOptionsSingle): Promise<SavedFileInfo>
saveAll(files: MultipartFile[], options?: SaveOptions): Promise<SavedFileInfo[]>
remove(filepath: string): Promise<void>
getUploadFile(filePath: string)
download(filepath: PathLike)
downloadAs(filepath: PathLike, filename: string)

Upload parameters are declared with @UploadFile and @UploadFiles.

Realtime ​

Guide: WebSocket.

ExportKindSignature / description
SocketIoServerconstToken<Server>. The Socket.IO server, registered by useSocketIo().
Subscribedecorator@Subscribe(event: string). Handle a Socket.IO event.
PrivateChanneldecorator@PrivateChannel(channelResolver?: (socket) => string). Mark a subscriber method as private.
DispatchNowdecorator@DispatchNow(event: string, options?: DispatchOptions). Emit the method's return value as event after it runs.
SocketEventDispatcherclassdispatch(event: string, data, options?: DispatchOptions). Emit an event over Socket.IO.
SocketContextServiceclassThe socket of the event being handled: getSocket().
DispatchOptionstype{ room?, broadcast?, transports?, retry?, retryDelay? }.

OpenAPI ​

Guide: OpenAPI.

Decorators ​

ExportKindSignature / description
OpenApidecorator@OpenApi(options: OpenApiOptions). Document a controller, route or property.
ApiResponsedecorator@ApiResponse(status: number, type?: ResponseType | ApiResponseOptions, description?: string). Document a response of a route or every route of a controller.
OpenApiPropertydecorator@OpenApiProperty(options?). Document a DTO property (ParamSchema fields plus isArray, items, nullable, readOnly, …).
OpenApiSchemadecorator@OpenApiSchema(). Add the class to components.schemas.
OpenApiResponsefunctionDeprecated. OpenApiResponse(code, model, description?). Documents a { code, status, data } wrapper Megh doesn't send. Use @ApiResponse.
OpenApiOkfunctionDeprecated. OpenApiResponse(200, model, "Success").

Functions ​

ExportKindDescription
registerSchemaProviderfunctionregisterSchemaProvider(provider: SchemaProvider). Describe classes the DTO reader doesn't.
generateClassSchemafunctiongenerateClassSchema(classType, options?: ClassSchemaOptions). JSON schema for a DTO class.
generateSwaggerSchemafunctiongenerateSwaggerSchema(classes, extraClasses?). components.schemas for @OpenApiSchema classes.
GetSchemafunctionAlias of generateSwaggerSchema.
inlineSchemaRefsfunctionReplace #/components/schemas/* refs with inline schemas.
normalizeParamsToJsonSchemafunctionnormalizeParamsToJsonSchema(params, requiredKeys?). Turn a ParamsSchemaMap into an object schema.

Options ​

ExportKindDescription
OpenApiUiOptionstypeOptions for useOpenApi(): info, routePrefix (default /swagger), provider ("default" or "scalar"), auth, servers, tags, security, components, uiConfig, scalar, logo, theme, openapi, paths.
OpenApiOptionstypeOptions for @OpenApi() on a route: summary, description, tags, params, query, headers, requestBody, response, exclude, deprecated, security, …
OpenApiAuthtype"bearer" | "apiKey" | SecuritySchemeObject.
ApiResponseOptionsinterface{ type?, description?, contentType?, example? }.
ResponseTypetypeA DTO class, [Class], Paginated(Class), a JSON schema or a $ref.
PaginatedTypeinterfaceWhat Paginated(Class) returns.
SchemaProvidertype(cls) => SchemaObject | undefined.
ClassSchemaOptionstype{ inline?, components? } for generateClassSchema.
SchemaClasstypeA DTO class.
ParamSchematypeSchema of one parameter.
ParamsSchemaMaptypeRecord<string, ParamSchema>.
RequestBodyOptionstypeOptions for requestBody.
RequestBodyMediaTypeOptionstypeA media type whose schema may be a DTO class.
ResponseBodyOptionstypeA response described as a JSON schema.
ResponsesOptionstypeResponses keyed by status code.
SwaggerUiConfiginterfaceSwagger UI settings.
SwaggerUiLogointerfaceSwagger UI top-bar logo.
SwaggerUiThemeinterfaceSwagger UI page title, CSS, scripts and favicon.
SwaggerUiThemeFileinterfaceA theme file.
SwaggerUiFaviconinterfaceA favicon file.
ScalarConfiginterfaceScalar settings.

OpenAPI document types ​

Types for the OpenAPI 3 document: InfoObject, ContactObject, LicenseObject, ServerObject, ServerVariableObject, PathsObject, PathItemObject, OperationObject, ExternalDocumentationObject, ParameterObject, ParameterBaseObject, HeaderObject, SchemaObject, ArraySchemaObject, NonArraySchemaObject, BaseSchemaObject, ArraySchemaObjectType, NonArraySchemaObjectType, DiscriminatorObject, XMLObject, ReferenceObject, ExampleObject, MediaTypeObject, EncodingObject, RequestBodyObject, ResponsesObject, ResponseObject, LinkObject, CallbackObject, SecurityRequirementObject, ComponentsObject, SecuritySchemeObject, HttpSecurityScheme, ApiKeySecurityScheme, OAuth2SecurityScheme, OpenIdSecurityScheme and TagObject.

Logging ​

Guide: Logging.

ExportKindSignature / description
LoggerServiceclassApplication logger backed by one shared pino instance. Injectable. info, error, warn, debug, fatal, trace take (message: string, obj?: any); getLogger() returns the pino logger.
LoggerConfiginterface{ level?, pretty?, destination? }.
buildLoggerOptionsfunctionbuildLoggerOptions(config?, env?): pino.LoggerOptions. The pino options Megh uses.
getRequestIdfunctiongetRequestId(): string | undefined. The ID of the request being handled.
DEFAULT_REQUEST_ID_HEADERconst"x-request-id".
RequestIdOptionstypefalse | { header?, generate? }, for the requestId application option.
ts
LoggerService.getPino(): pino.Logger                       // the shared instance
LoggerService.configure(config?: LoggerConfig): pino.Logger // replace it
LoggerService.child(bindings: pino.Bindings): pino.Logger

Health ​

Guide: Health checks.

ExportKindDescription
HealthChecktype() => unknown | Promise<unknown>. Passes unless it throws, rejects or returns false.
HealthOptionsinterface{ path?, readyPath?, checks?, timeout? }. Defaults: /health, /ready, 5000 ms.
HealthCheckResultinterface{ status: "up" | "down"; durationMs; error? }.
ReadinessReportinterface{ status: "ok" | "error"; checks }.
HealthRegistryclassRuns readiness checks and serves the health routes. The application creates one.
SKIP_GLOBAL_MIDDLEWAREconstRoute config flag that makes useMiddlewares skip a route.

Enable with app.useHealth(options?) and add checks with app.addHealthCheck(name, check).

Plugins ​

Guide: Plugins.

ExportKindDescription
definePluginfunctiondefinePlugin(plugin: MeghPlugin): MeghPlugin. Identity helper that type-checks a plugin.
MeghPlugininterface{ name: string; dependsOn?: string[]; register(ctx: PluginContext): void }.
PluginContextinterface{ app, container, http, logger, extend(name, method), onInit, onReady, onClose, addHealthCheck }.
PluginOptionstype{ plugins?: MeghPlugin[]; autoloadPlugins?: boolean }, part of MeghApplicationOptions.

Testing ​

Guide: Testing.

ExportKindDescription
MeghTestclassStatic test helpers (below).
TestApplicationinterfaceTest client: get, post, put, patch, delete, options take (url, options?: InjectOptions); plus getController(controller, deps?).
TestAppOptionstype{ controllers: Constructor[] }.
TestResponsetypeThe Fastify inject response, or a promise of it.
ts
MeghTest.createTestApplication(options: TestAppOptions): TestApplication
MeghTest.from(app: MeghApplication): TestApplication
MeghTest.getController<T>(controller: Constructor<T>, deps?: any[]): T
MeghTest.getProvider<T>(service: Constructor<T>, deps?: any[]): T
MeghTest.clean(): void   // reset the container

getController and getProvider register deps in place of the class's constructor dependencies, in order. Megh.createTestApplication(options) is the same as MeghTest.createTestApplication(options).

Types ​

ExportKindDescription
IRequestinterfaceThe request type handlers and middleware receive: Fastify's request with Megh's additions.
IResponseinterfaceFastify's reply.
Constructortypenew (...args: any[]) => T.

Other exports ​

These are exported but are mostly used by Megh itself. They may change or be removed in a minor release, so prefer the APIs above.

Metadata keys ​

ExportKind
ROUTE_META_KEY, CONTROLLER_META_KEY, PARAM_META_KEY, QUERY_META_KEY, REQUEST_BODY_META_KEY, REQUEST_BODY_FILE_KEY, REQUEST_BODY_FILES_KEY, REQUEST_USER_META_KEY, REQUEST_HEADER_META_KEY, DATASOURCE_META_KEY, AUTHORIZATION_META_KEY, API_CONTROLLER_METADATA_KEYconst (symbols)
REQUEST_METADATA_KEY, HTTP_CODE_META_KEYconst (symbols)
CATCH_META_KEY, FILTERS_META_KEYconst (strings)

Registries and internals ​

ExportKindDescription
registerController, getRegisteredControllers, isApiControllerfunctionThe controller registry.
registerService, getRegisteredServicesfunctionA service registry.
createControllerDecoratorfunctionFactory behind @ApiController.
getDeclaredFiltersfunctionFilters declared with @UseFilters for a route.
registerSocketSubscriber, getSocketSubscribers, isPrivate, getPrivateChannelResolverfunctionSocket subscriber registry.
EventSubscriberRegistryclassWires @Subscribe methods to a socket.
checkHelpers, stringLength, isLengthconst / functionHelpers called by compiled validation code.
ParamMetaOptions, ParamMetaFilesOptions, MethodParamMeta, IRoute, FuncRoute, StaticFileOptionstypeRouter metadata shapes.

Utility functions ​

ExportKindDescription
loadPackageFromClientfunctionLoad an optional dependency from the app's node_modules.
PackageLoadertypeType of loadPackageFromClient.
isConstructorfunctionWhether a value is a class.
formatUrl, parsedPath, normalizePathfunctionPath helpers used by the router.
sleepfunctionsleep(ms): a promise that resolves after ms.
pick, excludefunctionCopy an object with only, or without, the given paths.
autoCast, normalizeQueryDeepfunctionConvert query and parameter strings to typed values.
transformObjectByInstanceToObject, jsonToJs, jsonToInstancefunctionclass-transformer and JSON helpers.
getDataType, isValidType, isValidJsonStringfunctionType checks used for parameters.
isClassValidatorClass, validateObjectByInstancefunctionclass-validator helpers.
REQUEST_VALIDATION_OPTIONSconstclass-validator options Megh uses for request DTOs.
formatValidationMessagefunctionOne-line summary of validation issues.

Released under the MIT License.