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

@555platform/express-decorators

v0.2.12

Published

555 Platform common Express.js decorators for Typescript

Downloads

57

Readme

Build

express-decorators

Lightweight Typescript decorator library for Express.js to provide shortcuts for common patterns.

Inspired by the following projects:

  • https://tsed.io/
  • https://github.com/StephenGrider/typescriptcasts/tree/master/server

Installation

You can get the latest release using npm:

$ npm install --save @555platform/express-decorators

Quick Start

You can create web server by extending AppServer class.

import {
  json,
  Settings,
  AppServer
} from '@555platform/express-decorators';

@Settings({ port: 5001 })
class TestServer extends AppServer {
  beforeGlobalRouteInit(): void {
    this.use(json());
  }

  onServerListens(port: number): void {
    console.log(`Test server running on port: ${port}`);
  }
}

AppServer has couple life cycle methods that can be overwritten to perform custom initializations.

beforeServerInit

This method is automatically called before web server is initialized. It can be used to execute any code that must run before web server starts.

beforeGlobalRouteInit

This method is executed after web server is initialized but before routes are created. It is meant to be customized to set up global route midleware or perform other activities before routes are defined.

onServerListens

This method is called after web server starts.

Create Controller

@Controller('/')
class SimpleRoutes {
  @Get('/api')
  getApi(req: Request, res: Response, next: NextFunction): void {
    res.send('Ok');
  }

  @Delete('/api')
  deleteApi(req: Request, res: Response, next: NextFunction): void {
    res.send('Ok');
  }

  @Post('/api')
  postApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
    }
    res.send('Ok');
  }

  @Put('/api')
  putApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
    }
    res.send('Ok');
  }

  @Patch('/api')
  patchApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.body) {
      res.status(422).send('Missing body');
      return;
    }

    if (!req.body.testValue) {
      res.status(400).send('Missing testValue');
      return;
    }
    res.send('Ok');
  }

  @Get('/params/:id')
  idApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.params.id) {
      res.status(422).send('missing param');
    }

    res.status(200).send({ id: req.params.id });
  }

  @Post('/multi/id/:id/message/:message')
  multiApi(req: Request, res: Response, next: NextFunction): void {
    if (!req.params.id || !req.params.message) {
      res.status(422).send('missing param');
    }

    res.status(200).send({ id: req.params.id, message: req.params.message });
  }
}

Create WebSocket Server Controller

You can create one or more WebSocket servers as long as they are pointing to different path.

WssBeginConnect and WssEndConnect are functions that will be called by express-decorators at the begining and end of execution of wss.on connection function.

Function deecorated with @Server will receive WebSocket.Server object when the new server is instantiated.

@WebSocketServer('/'), { enableKeepAlive: true }
class SocketGateway {
  @Authenticate
  authenticationHandler(req: Request, cb: AuthenticationCallback) {
    console.log('Authing...');
    const queryData = url.parse(req.url, true).query;

    if (queryData.access_token === 'somevalue') {
      cb(undefined, { id: 'someid' });
      return;
    }

    cb(new Error('Unauthorized'));
  }

  @WssBeginConnect
  beginConnectionHandler() {
    console.log('Begin connection');
  }

  @WssEndConnect
  endConnectionHandler() {
    console.log('End connection');
  }

  @WsOnPong
  pongHandler(ws: ExtWebSocket) {
    return function() {
      console.log('Received PONG');
      ws.isAlive = true;
    };
  }

  @WsOnMessage
  messageHandler(ws: ExtWebSocket) {
    return function(msg: string) {
      ws.send(msg);
    };
  }

  @WsOnOpen
  openHandler(ws: ExtWebSocket) {
    return function() {
      console.log('connected');
      ws.send(Date.now());
    };
  }

  @WsOnClose
  closeHandler(ws: ExtWebSocket) {
    return function() {};
  }

  @WsOnError
  errorHandler() {
    return function(error: Error) {
      console.log(`Error: ${error}`);
    };
  }

  @Server
  serverHandler(wss: WebSocket.Server) {
    console.log('serverHandler');
  }
}

Connect to Mongo via Mongoose

You can simply pass Mongo connection information to Settings for AppServer via mongoose property:

@Settings({
        port: 5001,
        mongoose: {
          databaseURI: 'localhost',
          databaseName: 'mydb',
          dbUser: '',
          dbPassword: '',
          databaseReplSet: ''
        }
      })
      class TestServer extends AppServer {
        beforeGlobalRouteInit(): void {
          this.use(json());
        }

        onServerListens(port: number): void {
          console.log(`Test server running on port: ${port}`);
        }

        onMongooseConnected(): void {
          connectSuccess();
        }

        onMongooseError(error: Error): void {
          connectFailed();
        }
      }