Skip to content

Resty

The resty framework: controllers, REST decorators, interceptors, request injection and the async pipeServer bootstrap.

5 min read Source

Fast, unopinionated, minimalist REST framework for building efficient and scalable applications. It uses modern TypeScript and combines elements of OOP, Functional Programming and Reactive Programming.

Resty has unique features:

  • Dependency Injection
  • Method Interceptors
  • Modular Application Design
  • Request Interceptors
  • Routing (Dynamic & Static)
  • AWS Lambda Adapter
  • Supports MVC Structure

Requirements

Node.js ^26.0.0 (LTS only)
TypeScript 6.x, with experimentalDecorators and emitDecoratorMetadata enabled
Module system CommonJS output (target: es2019)

Decorator metadata is what makes the framework work, so emitDecoratorMetadata is required, not optional.

Bootstrapping

pipeServer initialises the module graph, registers every route on the Router and stores the module injector on the root module class under the "@typeix:moduleInjector" key, then seals that class. Feature packages read that key, so they must run after pipeServer and reuse the same server:

import {createServer} from "http";
import {pipeServer} from "@typeix/resty";

const server = createServer();
await pipeServer(server, Application);

await pipeWebSocket(server, Application);                       // @typeix/resty-ws
await pipeGraphQL(server, Application, {path: "/graphql"});     // @typeix/resty-graphql
await pipeSwagger(server, Application, {path: "/docs"});        // @typeix/resty-swagger

server.listen(3000);

Things worth knowing:

  • Calling pipeServer twice on one server does not merge applications. Each call pipes its own Router, both listen to request, and the one that does not match answers 404 — so every request fails. Put all modules in one graph and use module path for versioning.
  • The root module class is sealed, so pipeServer cannot be used to stash state on it. Feature packages keep their state in WeakMaps keyed by the class.
  • Route registration is logged at debug level, not info. Use level: "debug" on the Logger to see one line per route.

Server config

pipeServer(server, Application, config?) accepts a ServerConfig:

Option Purpose
useSyncInjector build the module graph with ModuleInjector.Sync instead of the async injector
mockProviders providers injected only into the test injector
isMockServer marks the run as a fake server, used by fakeHttpServer

The async injector is the default because it supports async factory and value providers.

Usage

In example below you can find basic application server starter:

import {
  pipeServer, Controller, Inject, ResolvedRoute, IResolvedRoute,
  GET, POST, OnError, RootModule, Logger, Router,
  addRequestInterceptor, BodyAsBufferInterceptor
} from "@typeix/resty";
import {IncomingMessage, ServerResponse, createServer} from "http";
// resty supports http, https, http2

@Controller({
  path: "/",
  interceptors: [], // controller request interceptors executed in order
  providers: []  // providers created on each request
})
class HomeController {

  @Inject()
  private request: IncomingMessage;

  @Inject()
  private response: ServerResponse;

  @ResolvedRoute()
  private route: IResolvedRoute;

  @GET()
  actionGet() {
    return this.route.method.toUpperCase() + " ACTION";
  }

  @POST()
  @addRequestInterceptor(BodyAsBufferInterceptor)
  actionAjax(body: Buffer) {
    return JSON.stringify(body.toString());
  }

  // will match all routes on this controller
  @OnError("*")
  errorCase() {
    return "FIRE ERROR CASE";
  }

  @GET("redirect")
  actionRedirect() {
    this.response.setHeader("Location", "/mypage");
    this.response.writeHead(307);
    this.response.end();
  }
}

// DEFINE MODULE
@RootModule({
  imports: [], // import other modules, created at application bootstrap
  shared_providers: [
    {
      provide: Logger,
      useFactory: () => new Logger({ options: {level: "debug"}})
    },
    Router
  ],
  providers: [], // providers created at application bootstrap
  controllers: [HomeController] // define controllers
})
class ApplicationModule {}

// START SERVER
async function bootstrap() {
  const server = createServer();
  const injector = await pipeServer(server, ApplicationModule);
  server.on("error", e => console.error(e));
  server.listen(3000);
  return injector;
}

export default bootstrap();

Controllers

A controller is a class with @Controller({path, interceptors?, providers?}). Its path is prefixed to every route it declares.

  • A new controller instance is created per request from a child injector that is destroyed on response.finish. That is what makes @Inject() private request: IncomingMessage legal, and it also means anything in @Controller({providers: [...]}) is per request.
  • Handler arguments come from the injector, not from parameter decorators. getProviders resolves them; a parameter decorated with @Inject(TOKEN) is injected, and the rest reflect their declared type.
  • The return value is written directly: an object is JSON.stringify-ed, a Buffer or string is sent as is, and undefined ends the response with no body.

Decorators

Resty re-exports everything from @typeix/di, @typeix/modules, @typeix/metadata, @typeix/logger, @typeix/router and @typeix/utils, so a single import is usually enough.

Decorator Level Purpose
@Controller({path, interceptors?, providers?}) class declare a controller and its path prefix
@RootModule({...}) class application root module
@Module({...}) class feature module
@GET(path?) @POST @PUT @DELETE @PATCH @HEAD @OPTIONS @TRACE @CONNECT method REST route, path may be a string or a RegExp
@OnError(path?) method error handler for the controller, "*" matches all routes
@PathParam(name) parameter inject the named route parameter
@ResolvedRoute() property/parameter inject the resolved route
@Inject(token?) property/parameter inject a provider
@Injectable() class register a class as a provider
@AfterConstruct() method run immediately after the instance is created
@CreateProvider() property create a fresh provider at the injection point, ignoring the parent
@AsyncInterceptor() method intercept an async method call
@Produces(contentType) method declare the response content type
@addRequestInterceptor(Class, args?) method request interceptor for one route, executed in order

Route paths support <param> and <param:(regex)>:

@GET("/users/<id:(\\d+)>")   // only digits
@GET("/files/<name>")        // any single segment
@GET("*")                    // catch-all

Interceptors

A request interceptor runs before the handler and may transform the body:

@POST()
@addRequestInterceptor(BodyAsBufferInterceptor)
action(body: Buffer) {
  return body.toString();
}

BodyAsBufferInterceptor is exported by resty. Method interceptors come from @typeix/di (@AsyncInterceptor() plus createMethodInterceptor / createInterceptors for programmatic use). See Interceptors for both patterns.

Ecosystem

Package Adds
@typeix/resty-ws websocket controllers on the same injector
@typeix/resty-socket-io Socket.IO adapter
@typeix/resty-swagger OpenAPI document and docs UI
@typeix/resty-graphql GraphQL endpoint
@typeix/resty-security identity and access rules as one guard chain
@typeix/resty-aws-lambda Lambda handler