Skip to content

Server-rendered app with uploads

A deep dive into the web-app-file-upload starter: Handlebar rendering through a method interceptor, streaming multipart uploads, custom router rules, response caching and controller-level error handling.

10 min read Source

Source: web-app-file-upload

Every other starter returns JSON. This one returns HTML, serves binary files and accepts a multipart upload, which makes it the best place to see how the framework behaves outside the "serialise a return value" path.

Five concepts appear here and nowhere else in the set: template rendering as a method interceptor, a streaming upload as a request interceptor, a custom router rule, a caching request interceptor, and a controller-scoped error handler.

Project layout

views/                                # handlebars templates
├─ home_id.hbs
└─ file_upload.hbs
public/                               # static assets, uploads land in public/upload
src
├─ application.ts                     # RootModule + dynamic route rule in afterConstruct
├─ bootstrap.ts                       # pipeServer + pipeSwagger
├─ controllers
│  ├─ home.controller.ts              # GET /, GET /params/<id>/<name>   (cached)
│  └─ assets.controller.ts            # GET /favicon.ico, GET /assets/<file>
├─ components
│  ├─ templating-engine.service.ts    # compile + cache templates
│  ├─ assets-loader.service.ts        # read files from public/
│  ├─ in-memory-cache.service.ts      # TTL cache with unref'd timers
│  ├─ url-data-store.service.ts       # mock "database" of dynamic paths
│  ├─ dynamic-route.rule.ts           # custom IRoute
│  └─ interceptors
│     ├─ request/cache.interceptor.ts
│     └─ method/render.interceptor.ts
└─ modules
   ├─ admin/controllers/admin-home.controller.ts     # /admin, /admin/fire, /admin/throw
   └─ file-upload/controllers/file-upload.controller.ts  # /file/upload

The module graph

@RootModule({
  imports: [AdminModule, FileUploadModule],
  controllers: [AssetsController, HomeController],
  providers: [AssetsLoaderService],
  shared_providers: [
    InMemoryCacheService,
    UrlDataStoreService,
    TemplateEngineService,
    {provide: Logger, useFactory: () => new Logger({/* pino-pretty transport */})},
    Router
  ]
})
export class Application implements IAfterConstruct {

  @Inject() router: Router;
  @Inject() injector: Injector;

  afterConstruct() {
    this.router.addRule(DynamicRouteRule, {
      injector: this.injector,
      method: "GET",
      path: "This is ignored in dynamic router",
      handler: createRouteHandler(
        createRouteDefinition({name: "actionIndex", decorator: GET}, HomeController)
      )
    });
  }
}

Router is declared in shared_providers because the application itself injects it and registers a route rule in afterConstruct. (pipeServer adds Router to the shared list automatically when it is missing, so the entry documents the dependency rather than enabling it.) IAfterConstruct runs once, after the instance is fully resolved — the right hook for "touch the framework once the graph exists".

Module path prefixes the controllers inside them, which is why the same @Controller({path: "/"}) in three places produces /, /admin/… and /file/upload:

@Module({path: "admin", controllers: [AdminHomeController], providers: []})
export class AdminModule {}

@Module({path: "/file", providers: [], controllers: [FileUploadController]})
export class FileUploadModule {}

Rendering HTML without putting HTML in the controller

The controller returns data. A method interceptor turns it into a response:

@Render("home_id")
@GET()
@ApiOperation({summary: "Render the home page", operationId: "getHome"})
@ApiResponse({status: 200, description: "rendered html page", contentType: "text/html", schema: {type: "string"}})
async actionIndex(): Promise<Buffer> {
  return await this.engine.compileAndRender("home_id", {
    id: "NO_ID",
    name: "this is home page",
    title: "Home page example",
    href: this.route.url.href
  });
}
@Injectable()
export class RenderInterceptor implements Interceptor {
  @Inject() engine: TemplateEngineService;

  async invoke(method: Method): Promise<any> {
    const data = await method.invoke();
    const result = await this.engine.compileAndRender(method.decoratorArgs.value, data);
    return await method.transform(result);
  }
}

export function Render(value: string) {
  return createMethodInterceptor(Render, RenderInterceptor, {value});
}

The template name comes from the decorator argument, the context is the handler's return value, and method.transform() lets the next interceptor in the chain post-process the buffer. This is the same createMethodInterceptor machinery that Code-first GraphQL uses for logging — the mechanism is protocol-agnostic.

TemplateEngineService compiles each template once and caches the compiled delegate in a Map, so the second request skips disk and compilation. In this starter the controller also renders inline (compileAndRender) — both paths exist to show that rendering does not have to happen in an interceptor.

Serving binary assets

@GET("assets/<file:(.*)>")
@ApiParam({name: "file", type: String, description: "path inside the public directory", example: "logo.png"})
@ApiResponse({
  status: 200,
  description: "file content, content type derived from the file extension",
  type: Buffer,
  contentType: "application/octet-stream"
})
async fileLoadAction(@PathParam("file") file: string) {
  const loadedFile: Buffer = await this.assetLoader.load(file);
  const type = getType(AssetsLoaderService.publicPath(file));
  this.response.setHeader("Content-Type", type);
  this.response.setHeader("Content-Length", loadedFile.length);
  return loadedFile;
}
  • <file:(.*)> is a named capture with a regex — a wildcard path segment. @PathParam("file") receives the matched substring, so /assets/css/site.css gives file = "css/site.css".
  • The content type is derived at runtime from the extension (mime.getType), which is why the OpenAPI response declares application/octet-stream: the media type is not knowable at build time. That is honest documentation rather than a decorative lie.
  • @Inject() response: ServerResponse gives direct access to the raw response for header manipulation. Returning the buffer afterwards lets the framework write the body.

faviconLoader() reuses the same action by delegating to it, so the mime lookup and length header logic exists once.

Streaming upload

@GET("/upload")
@POST("/upload")
@Render("file_upload")
@addRequestInterceptor(FileUploadInterceptor, {uploadPath: "/public/upload/"})
actionUploadFile(@ResolvedRoute() route: IResolvedRoute) {
  return {
    title: "File Upload example",
    message: "Magic is here",
    isUploaded: route.url.searchParams.get("isUploaded")
  };
}

One action serves both verbs: GET renders the form, POST runs the interceptor that streams the file and answers with a redirect. The interceptor is where the interesting part happens:

@Injectable()
export class FileUploadInterceptor implements RequestInterceptor {
  @Inject() logger: Logger;

  @CreateProvider({
    provide: Busboy,
    useFactory: (request) => {
      if (request.method === "POST") {
        return Busboy({headers: request.headers});
      }
    },
    providers: [IncomingMessage]
  }) parser: NodeJS.WritableStream;

  async invoke(method: InterceptedRequest): Promise<any> {
    const request = method.request;
    if (request.method === "POST") {
      const saveDir = process.cwd() + method.args.uploadPath;
      await fse.ensureDir(saveDir);
      return new Promise(resolve => {
        this.parser.on("file", (fieldName, file, info) => {
          const savePath = path.join(saveDir, path.basename(info.filename));
          file.pipe(fs.createWriteStream(savePath));
        });
        this.parser.on("close", () => {
          const response = <ServerResponse>method.response;
          response.writeHead(303, {
            "Connection": "close",
            "Location": method.route.path + "?isUploaded=true"
          });
          response.end();
          resolve("UPLOADED");
        });
        request.pipe(this.parser);
      });
    }
  }
}

Four ideas are packed into those lines:

  1. The parser is a provider with a request dependency. @CreateProvider with providers: [IncomingMessage] builds a busboy instance per request, configured with that request's headers. The interceptor class is shared; the parser is request-scoped.
  2. Streaming, not buffering. file.pipe(fs.createWriteStream(...)) never holds the upload in memory, so a large file does not become a large heap allocation.
  3. path.basename on the client-supplied name. ${uploadPath}/${info.filename} would allow ../../ traversal and escape public/upload.
  4. Respond from the interceptor. The 303 See Other redirect is written directly and the handler is never invoked for POST. The isUploaded=true query parameter is what the GET branch renders afterwards.

Trust nothing in info.filename

path.basename stops traversal but not collisions, nor executable content, nor an empty name. Production code also needs a size limit (busboy's limits), an allowed-mime check and a generated storage name. The starter keeps the shape and leaves the policy to you.

A custom router rule

/dynamic, /dynamic-simulation and /dynamic-db-simulation are not declared by any controller. They are resolved at request time by a rule:

@Injectable()
export class DynamicRouteRule implements IRoute {

  @Inject() cache: InMemoryCacheService;
  @Inject() datastore: UrlDataStoreService;
  @Inject() injector: Injector;
  @RouteConfig() config: IRouteConfig;

  async parseRequest(uri: URL, method: string, headers: {[key: string]: any}): Promise<IResolvedRoute> {
    if (await this.datastore.isValid(uri.pathname) && this.config.method === method) {
      return {
        injector: this.injector,
        method,
        headers,
        url: uri,
        params: {},
        path: uri.pathname,
        handler: this.config.handler
      };
    }
    return null;
  }
}
  • The router walks its rules in registration order and takes the first rule that returns an object. Returning null means "not mine, try the next".
  • The rule can be asynchronous, so the list of valid paths could come from a database — that is the point of UrlDataStoreService, a mock standing in for exactly that.
  • A rule is a normal provider, so it injects services. @RouteConfig() receives the config passed to router.addRule.
  • The handler is a pre-bound route definition (createRouteHandler(createRouteDefinition(...))), which is why the rule can dispatch to a controller action by name.

Rules registered by pipeServer come first, so a custom rule only sees paths no controller matched. That is what makes this safe: / keeps its controller behaviour, and /dynamic falls through to the rule.

Caching responses

@Injectable()
export class CacheInterceptor implements RequestInterceptor {
  @Inject() cacheProvider: InMemoryCacheService;

  async invoke(method: InterceptedRequest): Promise<any> {
    if (await this.cacheProvider.has(method.route.path)) {
      return await this.cacheProvider.get(method.route.path);
    } else {
      this.cacheProvider.set(method.route.path, await method.handler(), 120);
    }
  }
}

HomeController declares interceptors: [CacheInterceptor], so both of its routes cache their rendered buffer under the request path for 120 seconds. On a hit the handler and the @Render interceptor do not run at all; the stored buffer is returned directly.

InMemoryCacheService keeps a timer per key and calls unref() on it:

const timer = setTimeout(() => this.delete(key), 1000 * timeoutInSec);
// expiration is housekeeping only, it must not keep the process alive
if (typeof timer === "object" && typeof timer.unref === "function") {
  timer.unref();
}

Without unref() a pending TTL keeps the event loop alive, so Jest hangs after the run and graceful shutdown waits for the timer. Any in-process cache in a test-covered codebase has this problem.

Error handling per controller

@OnError("(.*)")
actionError(@Inject(RouterError) error: RouterError) {
  return "ADMIN -> ERROR -> " + error.getCode() + " : " + error.getMessage();
}

@GET("fire")
actionThrowError() {
  throw new RouterError("FIRE", 500);
}

@OnError with a regex matches error codes; the handler receives the RouterError and returns a body. GET /admin/fire therefore answers ADMIN -> ERROR -> 500 : FIRE instead of a stack trace, and the handler is scoped to that controller — a second controller can choose a different format without global middleware.

Tests

Fourteen tests, no e2e directory, no database:

File Kind Covers
controllers/assets.controller.unit-spec.ts unit fileLoadAction, faviconLoader
controllers/home.controller.unit-spec.ts unit the render path
controllers/home.controller.integration-spec.ts integration / and /params/:id/:name through the real router
modules/admin/controllers/admin-home.controller.integration-spec.ts integration index, and both error actions
modules/file-upload/controllers/file-upload.controller.unit-spec.ts unit render and upload branches
swagger-spec.ts build-time the document still lists every expressible route

The swagger spec is explicit about what is not in the document:

it("should document the routes of the root and imported modules", () => {
  expect(Object.keys(document.paths).sort()).toEqual([
    "/", "/admin", "/admin/fire", "/admin/throw",
    "/assets/{file}", "/favicon.ico", "/file/upload", "/params/{id}/{name}"
  ]);
});

Pitfalls

  • Dynamic routes are invisible to OpenAPI. /dynamic* are produced by a rule, not a controller, so they are not route definitions and cannot be documented. This is documented in the page and in the starter README rather than papered over.
  • multipart/form-data cannot be documented either. ApiBodyOptions has no contentType, and the media type is derived from the schema, so a body would have to claim application/json. The upload body is described in @ApiOperation.description instead.
  • contentType alone is dropped. @ApiResponse({status: 200, contentType: "text/html"}) produces a response with no content object; pass a schema too (schema: {type: "string"}) to get a media type in the document.
  • Cached responses skip the render interceptor. The cached value is the rendered buffer, so per-request data (route.url.href) freezes for the TTL. Cache only routes whose output is genuinely request-independent, or vary the key.
  • process.cwd() drives every path (views/, public/). Start the app from the project root.

Next: WebSockets.