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

ws-routing

v1.6.1

Published

Create structured, declarative and beautifully organized class-based controllers with heavy decorators usage fo websocket using TypeScript.

Downloads

10

Readme

ws-routing

基于类并通过声明的方式创建控制类并处理 websocket 请求。

20220402161833-ws-routing-arch.png

目录

安装

npm i ws-routing --save

必要条件

tsconfig.json 中需要设置以下配置项:

{
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true
}

快速开始

1.新建文件hotels/index.ts

import { Controller, Route, Ctx, Body, Context } from 'ws-routing';

@Controller('hotel')
export class HotelController {
  @Route('query')
  queryHotel(@Ctx() ctx: Context, @Body() body: string) {
    ctx.send(body);
  }
}

该类将在websocket中自动注册路由被Route装饰的路由

2.新建文件app.ts

import { WsRouting } from 'ws-routing';
import path from 'path';

const wr = new WsRouting({
  controller: path.join(process.cwd(), 'controllers'),
  common: [path.join(process.cwd(), './common')],
  ws: { port: 8080 },
});

更多用法

配置目录加载控制器

controllercommon 配置指定文件夹,则按照xx/**/*.{ts,js}可加载该目录下所有控制器:

import { WsRouting } from 'ws-routing';

const wr = new WsRouting({
  controller: [path.join(process.cwd(), './controller')], //控制器
  common: [path.join(process.cwd(), './common')], //中间件、订阅器类
  ws: { port: 8080 },
});

指定路由器前缀

向控制器装饰器传递根路由参数,控制器下的路由将添加该跟路由前缀:

@Controller('/user')
export class Controller {
  // ...
}

注入请求参数

目前只支持@Ctx(),@Body()两个参数装饰器

  @Route('query')
  queryHotel(@Ctx() ctx: Context, @Body() body:string) {

  }

使用中间件

common目录下新建middleware.ts,注册前置和后置中间件并通过order调节执行顺序

@Middleware({ type: 'before', order: 1 })
class BeforeMiddle implements MiddlewareInterface {
  use(ctx: Context, next) {
    console.log('before middleware 2 process');
    return next();
  }
}
@Middleware({ type: 'after' })
class AfterMiddle implements MiddlewareInterface {
  use(ctx: Context, next: () => Promise<any>): Promise<any> {
    console.log('after middleware process');
    return next();
  }
}

使用订阅器

common目录下新建subscribe.ts,通过@Subscribe()注册订阅类并通过@Event(name:string)注册订阅方法

@Subscribe()
export class SubscribeCenter {
  @Event('error')
  handleError(...args) {
    console.log('error');
  }
  @Event('wss:connection')
  handleWssConnection(...args) {
    console.log('wss:connection1');
  }
  @Event('ws:close')
  handleWSClose(...args) {
    console.log('ws:close');
  }
  @Event('ws:error')
  handleWSError(...args) {
    console.log('ws:error');
  }
}

装饰器参考

类-装饰器

| 名称 | 例子 | 描述 | | -------------------------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | @Controller(baseRoute: string) | @Controller("/users")``class SomeController | 被装饰的类将注册为控制层,该类下被装饰的函数将注册为路由。baseRoute 将作为该控制器所有路由的前缀。 | | @Service() | @Service()       class SomeService | 被装饰的类将注册为业务层,该类将向控制层提供复杂逻辑处理。 | | @Agent() | @Agent()            class SomeAgent | 被装饰的类将注册为数据代理层,该类将向业务逻辑层提供数据代理服务。 | | @Subscribe() | @Subscribe()class SomeSubscribe | 被装饰的类将注册为订阅层,该类将监听 ws-routing 触发的事件。 | | @Middleware(options) | @Middleware({type:'before',order:1})Class SomeMiddleware | 被装饰的类将注册为中间件,该类需要实现use方法 |

类属性-装饰器

| 名称 | 例子 | 描述 | | -------------------------- | ---------------------------------------------------- | ------------------------------------------------- | | @Route(route:string) | @Route("/users")``<br/> queryUsers() | 被装饰的函数将注册一个请求到给定路由。 | | @Event(eventname:string) | @Event("wss:connection") createConnection(...args) | 被装饰的函数将订阅一个 wss:connection  的事件。 | | @Inject() | @Inject() myservice:MyService | 被装饰的属性将引用到元信息中的类的实例。 |

类方法参数-装饰器

| 名称 | 例子 | 描述 | | -------- | ---------------------------------- | ----------------------------- | | @Ctx() | queryUsers(@Ctx() ctx: Context) | 注入请求上下文 Context 对象。 | | @Body | queryUsers(@Body() body: string) | 注入请求消息体内容。 |