基于类并通过声明的方式创建控制类并处理 websocket 请求。
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 },
});
在controller
或common
配置指定文件夹,则按照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) |
注入请求消息体内容。 |