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 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-mcs

v1.3.2

Published

Decorator based Module-Controller-Service system for Express

Downloads

10

Readme

express-mcs

Express-mcs is a decorator-based mini-framework that brings module-controller-service architecture to your express application.

Project is inspired by NestJS.

Numbers:

Installation

Npm

npm i express-mcs

Yarn

yarn add express-mcs

Quick guide

Create service

export class AppService {
  public status() {
    return { status: 'ok' };
  }
}

Create controller

import { Controller, Get, Inject } from 'express-mcs';

@Controller('/api')
export class AppController {
  constructor (
    @Inject(AppService)
    private readonly service: AppService,
  ) {}

  @Get('/status')
  public status() {
    return this.service.status();
  }
}

Create app module

import { Module } from 'express-mcs';
import { AppService } from './app.service';
import { AppController } from './app.controller';

@Module({
  providers: [AppService],
  controllers: [AppController],
})
export class AppModule {}

Initialize app module

// ...

initAppModule({
  Module: AppModule,
  app
});

// ...

app.listen(environment.PORT, () => {
  // ...
});

Usage

Controllers

import { Controller, Get } from 'express-mcs';

@Controller('/api/v1/users')
export class UsersController {
  @Get('/all')
  public async find() {
    return { status: 'ok', users: [] }
  }
}

Controller decorator accepts root path.

Methods

You can use Get, Post, Put, Patch, Delete method decorators, which accept path as a parameter

Method params

Req

Injects request to controller method.

import { Request } from 'express';
import { Controller, Get, Req } from 'express-mcs';

@Controller('/api/v1/users')
export class UsersController {
  @Get('/all')
  public async find(@Req request: Request) {
    ...
  }
}

Res

Injects response to controller method.

import { Response } from 'express';
import { Controller, Get, Res } from 'express-mcs';

@Controller('/api/v1/users')
export class UsersController {
  @Get('/all')
  public async find(@Res response: Response) {
    res.status(401).send();
  }
}

Headers

Injects request headers to controller method.

import { Response } from 'express';
import { Controller, Get, Headers } from 'express-mcs';

@Controller('/api/v1/users')
export class UsersController {
  @Get('/all')
  public async find(@Headers headers: unknown) {
    ...
  }
}

Body

Injects request body to controller method.

import { Response } from 'express';
import { Controller, Post, Body } from 'express-mcs';

@Controller('/api/v1/users')
export class UsersController {
  @Post('/create')
  public async create(@Body() data: UserCreateDto) {
    ...
  }
}

Query

Injects request query params to controller method.

import { Response } from 'express';
import { Controller, Get, Query } from 'express-mcs';

@Controller('/api/v1/users')
export class UsersController {
  @Get('/find')
  public async find(@Query() pagination: UserFindRequestQuery) {
    ...
  }
}

Params

Injects request query params to controller method.

import { Response } from 'express';
import { Controller, Get, Params } from 'express-mcs';

@Controller('/api/v1/users')
export class UsersController {
  @Get('/:id')
  public async findOne(@Params() {id}: UserFindOneRequestParams) {
    ...
  }
}

Data validation

Create validation func

import { validate } from 'class-validator';
import { Response } from 'express';

export async function getValidatedData(data: any, res: Response): Promise<unknown> {
  const errors = await validate(data);
  if (!errors.length) return data;
  res.status(400).json(errors).send();
  return undefined;
}

Pass validation function to module init

export const appModule = initAppModule({
  Module: AppModule,
  app,
  getValidatedData,
});

Pass DTO class to Query/Body/Params

import { IsString } from 'class-validator';
import { Response } from 'express';
import { Controller, Post, Body } from 'express-mcs';

class UserCreateDto {
  @IsString()
  login!: string
}

@Controller('/api/v1/users')
export class UsersController {
  @Post('/create')
  public async create(@Body(UserCreateDto) data: UserCreateDto) {
    ...
  }
}

Custom middleware

ApiKey auth middleware

import { getMiddleware, AuthorizationError } from 'express-mcs';
import { environment } from '../../environment';

export const AppApiGuard = getMiddleware(async (req) => {
  if (req.headers.apikey !== environment.API_KEY) {
    throw new AuthorizationError();
  }
});
import { Controller, Post } from 'express-mcs';
import { AppApiGuard } from './api-key.strategy';

@Controller('/api/v1/data-sync')
export class DataSyncController {
  @Post('/sync')
  @AppApiGuard
  public async syncItems() {
    // ...
  }
}

Handling errors

import { Response } from 'express';
import { HandleError, handleError as handleErrorDefault } from 'express-mcs';
import { CustomError } from './custom-error';

export const handleError: HandleError = async (res: Response, error: unknown) => {
  if (error instanceof CustomError) {
    res.status(400).json({ message: error.message });
  } else {
    await handleErrorDefault(res, error);
  }
};
// ...
import { handleError } from './errors/handle-error';
// ...

export const appModule = initAppModule({
  Module: AppModule,
  app,
  getValidatedData,
  handleError,
});

Examples