Skip to content

Request Lifecycle

The exact path an HTTP request takes through Typeix: route matching, request scoped injection, interceptors, the handler and response serialization.

5 min read Source

A request in a resty application passes through a fixed sequence. Knowing it explains where to put logic, why a provider is or is not shared, and why an error surfaces the way it does. This page follows one request through the real implementation rather than describing it abstractly.

The sequence

request
  │
  ├─ 1. Router.parseRequest        match method + path → IResolvedRoute
  │      (no match → throws RouterError 404, jumps to 8)
  │
  ├─ 2. ResolvedRoute              stored in the injector
  ├─ 3. path params                each <param> added to the injector
  │
  ├─ 4. controller instance        created from a child injector (once per request)
  ├─ 5. request interceptors       controller level, then method level, in order
  ├─ 6. handler arguments          resolved from the injector
  │
  ├─ 7. handler                    runs, returns a value
  │      └─ response serialization
  │
  └─ 8. error path                 RouterError status, then the matching @OnError route

1. Matching

The router walks the rules registered for the request method and returns the first match. <param> captures are extracted into route.params; a RegExp segment matches anything it can capture. A rule only matches its own method, so GET /users and POST /users are independent.

If nothing matches, the router throws RouterError with status 404. It does not invent an empty response — the throw is what hands control to the error path.

2–3. Preparing the injector

Before the controller exists, the framework puts the request's context into the injector used to build it:

Token Value
IncomingMessage (or Http2ServerRequest) the request
ServerResponse (or Http2ServerResponse) the response
ResolvedRoute the matched route, including params, headers, url, method
@PathParam tokens one per captured segment

That is why @Inject() private request: IncomingMessage works in a controller, and why @PathParam("id") can resolve from the injector like any other provider.

4. Controller instantiation

The controller is created per request:

const instance = await handlerInjector.createAndResolve(
  routeDefinition.controller.provider,
  shiftLeft(providers, controllerProviders)
);

Consequences you can rely on:

  • A field on the controller is not shared between requests. Storing state there is safe.
  • @Controller({providers: [...]}) entries are per request, because they are created in this child injector.
  • The child injector is destroyed when the response finishes, which cleans up request scoped providers.

Model View Controller

5. Interceptors

Request interceptors wrap the handler. Controller level interceptors run before method level, and both run in the order they were declared. Each one receives an InterceptedRequest:

interface InterceptedRequest {
  handler: () => any;          // await this to run the rest of the chain
  injector: Injector;
  route: IResolvedRoute;
  request: RestyRequest;
  response: RestyResponse;
  readonly args: any;          // arguments given to @addRequestInterceptor
}

A canonical interceptor: read the body, put it on the injector, call through.

@Injectable()
class BodyAsBufferInterceptor implements RequestInterceptor {
  @Inject() private request: IncomingMessage;

  async invoke(method: InterceptedRequest): Promise<any> {
    const body = await getRequestBody(this.request);
    method.injector.set(Buffer, body);
    return method.handler();
  }
}

If you end the response yourself, return a value

The executor treats an interceptor that returns undefined and has ended the response as a bug and throws RouterError 500. Ending the response is allowed; you must still return the result so the promise chain stays well defined. Returning a defined value without ending the response short-circuits the chain — the handler never runs.

6–7. Handler and response

Handler arguments are resolved from the injector, not passed by the router. The declared parameter list comes from design:paramtypes, with @Inject(token) tokens substituted position by position (the shared array is copied, never mutated).

The return value decides what goes over the wire:

Returned Response
a Buffer written as-is
an object or array JSON.stringify applied
a string or number written as-is
undefined the response is ended with no body
nothing, because the handler already called response.end() left alone (writableEnded is respected)

Setting headers or a status means touching the injected ServerResponse; resty does not buffer your output and write it later, so a writeHead() in the handler is final.

8. The error path

Errors do not escape to the server as an unhandled rejection:

  1. A thrown RouterError sets response.statusCode from getCode(). Anything else becomes a RouterError with status 500.
  2. The error is placed in the injector, so an @OnError handler can @Inject() it.
  3. The request is re-dispatched through the same pipeline using the internal ERROR method, which is why @OnError("*") receives the usual route argument and can return a body like any handler.
  4. If the error route itself throws, the fallback payload is JSON:
{
  "message": "…",
  "stack": ["…"],
  "request": {"method": "GET", "url": "/users", "headers": {}},
  "statusCode": 500
}

That final payload includes the stack, so it is a development aid — put an @OnError handler in front of it in production if you do not want internals in responses.

Putting it in one example

@Controller({path: "/users", providers: [UnitOfWork]})   // UnitOfWork: one per request
class UserController {
  @Inject() private request: IncomingMessage;            // from the request injector
  @Inject() private users: UserService;                  // from the module graph

  @GET("/<id:(\\d+)>")
  @addRequestInterceptor(LoggingInterceptor)             // runs before the method
  find(@PathParam("id") id: string) {                    // resolved from the injector
    return this.users.find(id);                          // object → JSON
  }

  @OnError("*")
  handle(@Inject() error: RouterError) {                 // the injected error
    return {message: error.getMessage(), statusCode: error.getCode()};
  }
}

Further reading