npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

quantum-flow

v1.12.3

Published

Decorator-based API framework

Downloads

1,667

Readme

Project Overview

This project is a decorator-based API framework supporting both HTTP and WebSocket servers. It is designed to simplify the creation of scalable and maintainable APIs with features such as controllers, middlewares, interceptors, error handling, and WebSocket support. Additionally, it supports AWS Lambda integration for serverless deployments.

Installation

To install dependencies and build the project, run:

yarn install
# or npm install

Usage

You can use controllers and server functionality by importing controllers and creating server instances as shown in the examples above. Use your preferred testing framework to write unit and integration tests.

Project Structure

  • quantum-flow/http - Main application source code for HTTP servers.
  • quantum-flow/aws - Main application source code for AWS Lambda.
  • quantum-flow/core - Core framework components like Controller and Endpoint.
  • quantum-flow/middlewares - Core middlewares to use within the application.
  • quantum-flow/ws - Websocket decorators.
  • quantum-flow/sse - Server side events decorators.

Defining Controllers

Use the @Controller decorator to define controllers with options such as prefix, sub-controllers, middlewares, and interceptors.

import {
  Body,
  Controller,
  Headers,
  IWebSocketService,
  Params,
  PUT,
  Query,
  Request,
  Response,
  Status,
  USE,
} from 'quantum-flow/core';
import {IsString} from  'class-validator'
import { Catch, Cors, Sanitize, Use, SANITIZER } from 'quantum-flow/middlewares';
import { InjectWS } from 'quantum-flow/ws';
// SANITIZER - prefilled Joi shema for  common data
class UserDto {
  constructor() {}
  @IsString()
  name: string;
}

@Controller({
  prefix: 'user',
  controllers: [UserMetadata, ...],
  interceptor: (data, req, res) => data,
})
@Cors({ origin: '*' })
@Catch((err) => ({ status: 500, err }))
@Use(()=>{})
@Sanitize({
  schema: Joi.object({
    name: Joi.string().trim().min(2).max(50).required(),
  }),
  action: 'both',
  options: { abortEarly: false },
  stripUnknown: true,
  type: 'body',
})
export class User {
  @Status(201)
  @PUT(':id',[(req, res)=>{} , ...middlewares])
  @Cors({ origin: '*' })
  async createUser(
    @Body(UserDto) body: UserDto,
    @Query() query: any,
    @Headers() headers: any,
    @Params(ParamDTO, 'param') params: any,
    @Request() req: any,
    @Response() resp: any,
    @InjectWS() ws: IWebSocketService,
  ) {
  }

  @USE([...middlewares])
  async any(@Response() resp: any) {
    ...
  }
}

@Controller(api, [...middlewares])
@Controller({
  prefix: 'api',
  controllers: [UserController, SocketController],
  middelwares: [...middlewares],
  interceptor: (data, req, res) => data,
})
@Catch((error) => ({ status: 400, error }))
class RootController {}

Creating a http Server

Use the @Server decorator with configuration options like port, host, controllers, and WebSocket enablement.

import { Server, Port, Host, Use, Catch, HttpServer } from 'quantum-flow/http';

@Server({ controllers: [RootController], cors: { origin: '*' } })
@Port(3000)
@Host('localhost')
@Use((data) => data)
@Catch((error) => ({ status: 400, error }))
class App {}

const server = new HttpServer(App);

server.listen().catch(console.error);

Middlewares, Interceptors, and Error Handlers

  • Use @Use to apply middlewares.
  • Use @Catch to handle errors.
  • Use @Port and @Host to configure server port and host.
  • Use @Cors to configure cors.
  • Use @Sanitize to apply sanitization to reqest.

Request decorators

  • Use @Body to handle request bodies.
  • Use @Headers to access request headers.
  • Use @Query to handle query parameters.
  • Use @Params to access route parameters.
  • Use @Multipart for handling multipart/form-data requests.
  • Use @Request to access the original request object.
  • Use @Response to access the original object.
  • Use @InjectWS to access the websocket service.
  • Use @InjectSSE() to access the server-side-event service.

AWS Lambda Support

Use LambdaAdapter to convert API Gateway events to requests and responses. Create Lambda handlers from controllers.

Example Lambda handler creation
import { LambdaAdapter } from 'quantum-flow/aws';

let dbConnection = null;

@Controller({
  prefix: 'api',
  controllers: [UserController, SocketController],
})
class RootController {
  async beforeStart(){
    if(!dbConnection){
      connection = await connect()
    }
  }
}
export const handler = LambdaAdapter.createHandler(RootController);

WebSocket Support

Enable WebSocket in the server configuration and register WebSocket controllers.

Enabling WebSocket Support in Server

To enable SSE support, configure your HTTP server with the sse: true option and register controllers that use SSE.

Example server setup:

@Server( {websocket: { enabled: true, path: '/ws' } })

Injecting WebSocket events in Controller

import { OnConnection, Subscribe, OnMessage } from 'quantum-flow/ws';
@Controller('socket')
export class Socket {
  @OnConnection()
  onConnection(event: WebSocketEvent) {
    // Send greeting ONLY to this client
    event.client.socket.send(JSON.stringify({ type: 'welcome', data: { message: 'Welcome!' } }));
  }

  /**
   * 2. @Subscribe - AUTOMATIC broadcast to all subscribers
   * No need to use WebSocketService!
   */
  @Subscribe('chat')
  onChatMessage(event: WebSocketEvent) {
    // This method is called for EACH subscriber
    // The message is ALREADY automatically broadcast to all!

    const msg = event.message?.data;
    // You can add logic, but no need to broadcast
    if (msg?.text.includes('bad')) {
      // If return empty, the message will not be sent
      return;
    }

    // That's it, the message will be sent to subscribers automatically!
  }

  /**
   * 4. @OnMessage for commands (without WebSocketService)
   */
  @OnMessage('ping')
  onPing(event: WebSocketEvent) {
    // Send response only to this client
    event.client.socket.send(
      JSON.stringify({
        type: 'pong',
        data: { time: Date.now() },
      }),
    );
  }

  /**
   * 5. @OnMessage for subscription
   */
  @OnMessage('subscribe')
  onSubscribe(event: WebSocketEvent) {
    const topic = event.message?.data.topic;

    // Server will save the subscription automatically, no need to do anything!
    // Just confirm
    event.client.socket.send(
      JSON.stringify({
        type: 'subscribed',
        topic,
        data: { success: true },
      }),
    );
  }
}

Server-Sent Events (SSE) Support

The framework supports Server-Sent Events (SSE) to enable real-time, one-way communication from the server to clients over HTTP.

Defining SSE Controllers

Use the @Controller decorator to define controllers with a prefix and optionally include sub-controllers. This allows modular organization of your API endpoints.

Example:

@Controller({
  prefix: 'user',
  controllers: [UserMetadata],
  middlewares: [function UserGlobalUse() {}],
  interceptor: (data, req, res) => {
    return { data, intercepted: true };
  },
})
export class User {}

Injecting SSE Service

Use the @InjectSSE decorator in your controller methods to create and manage SSE connections. This service allows sending events to connected clients.

Example method using SSE:

import { InjectSSE } from 'quantum-flow/sse';

@Controller('user')
export class UserMetadata {
  @GET('/subscribesse')
  async subscribesse(@InjectSSE() sse) {
    const client = sse.createConnection(res);

    sse.sendToClient(client.id, {
      event: 'welcome message',
      data: { message: 'Connected to notifications' },
    });

    return 'hellow';
  }
}

SSE Event Decorators

The framework provides decorators to handle SSE connection lifecycle events:

  • @OnSSEConnection(): Decorate a method to handle new SSE connections.
  • @OnSSEError(): Decorate a method to handle SSE errors.
  • @OnSSEClose(): Decorate a method to handle SSE connection closures.

Example usage:

import { OnSSEConnection, OnSSEError, OnSSEClose } from 'quantum-flow/sse';

@Controller('user')
export class User {
  @OnSSEConnection()
  async onsseconnection(@Request() req: any, @Response() res: any) {
    console.log('SSE connection established');
    return req.body;
  }

  @OnSSEError()
  async onsseerror(@Request() req: any, @Response() res: any) {
    console.log('SSE error occurred');
    return req.body;
  }

  @OnSSEClose()
  async onsseclose(@Request() req: any, @Response() res: any) {
    console.log('SSE connection closed');
    return req.body;
  }
}

Sending SSE Events

Use the injected SSE service to send events to clients. You can send events to all clients or specific clients by ID.

Example:

sse.sendToClient(clientId, {
  event: 'eventName',
  data: { key: 'value' },
});

Enabling SSE Support in Server

To enable SSE support, configure your HTTP server with the sse: true option and register controllers that use SSE.

Example server setup:

import { Server, HttpServer } from 'quantum-flow/http';
import { User, UserMetadata } from './controllers';

@Server({
  controllers: [User, UserMetadata],
  sse: { enabled: true },
})
class App {}

const server = new HttpServer(App);
server.listen().catch(console.error);

Enabling static files

To enable serving static files, use statics option.

Example server setup:

import { Server, HttpServer } from 'quantum-flow/http';
import { User, UserMetadata } from './controllers';

@Server({
  statics: [
    {
      path: path.join(__dirname, './public'),
      options: {
        index: 'index.html',
        extensions: ['html', 'htm', 'css', 'js'],
        maxAge: 86400,
        immutable: true,
        dotfiles: 'deny',
        fallthrough: false,
        setHeaders: (res, filePath, stats) => {
          if (filePath.endsWith('.css')) {
            res.setHeader('Content-Type', 'text/css');
          }
        },
      },
    },
  ],
})
class App {}

const server = new HttpServer(App);
server.listen().catch(console.error);

Summary

  • Use @Controller with prefix and controllers to organize your API.
  • Use @InjectSSE to create SSE connections in controller methods.
  • Use the SSE service's send method to push events to clients.
  • Use @OnSSEConnection, @OnSSEError, and @OnSSEClose decorators to handle SSE lifecycle events.
  • Enable SSE in your server configuration and register SSE controllers.

This setup allows you to build real-time, event-driven APIs using Server-Sent Events in a clean and modular way.