feat: add websocket model

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
2019-06-28 15:30:46 +08:00
parent c93c5c3fbb
commit d9e3cad8a1
23 changed files with 483 additions and 37 deletions

View File

@@ -1,8 +1,6 @@
import {
controller, response, requestBody, httpGet, httpPost, queryParam, requestParam
} from 'inversify-express-utils';
import { inject, postConstruct } from 'inversify';
import { Vaild, NotBlank, NotNull } from '@cc-server/binding'
import { inject, postConstruct } from '@cc-server/ioc';
import { Vaild, NotBlank, NotNull, controller, requestBody, httpGet, httpPost, requestParam } from '@cc-server/binding'
import { namespace, listener, interfaces, io, getSocketContext } from '@cc-server/ws'
import { DBClient } from '@cc-server/db'
import '@cc-server/db-mongo'
@@ -21,9 +19,7 @@ class ExampleModel {
email: string;
}
type Model = ExampleModel
@controller('')
@controller('/example')
export class Controller {
@inject(DBClient)
private client: DBClient
@@ -34,14 +30,14 @@ export class Controller {
}
@httpGet('/')
public async list(): Promise<Model[]> {
public async list(): Promise<ExampleModel[]> {
return this.client.find({});
}
@httpGet('/:id')
public async get(
@requestParam('id') id: string
): Promise<Model> {
): Promise<ExampleModel> {
return this.client.findOneById(id);
}
@@ -56,8 +52,40 @@ export class Controller {
@httpPost('/:id')
public async update(
@requestParam('id') id: string,
@requestBody() model: Model
@requestBody() model: ExampleModel
): Promise<boolean> {
return this.client.updateById(id, model);
}
}
@namespace('/', (socket: io.Socket, next: (err?: any) => void) => {
console.log(socket.nsp.name, socket.id, 'before connection');
next();
})
export class Namespace extends interfaces.Namespace {
private cache: { [key: string]: string } = {};
public async connection(socket: io.Socket) {
console.log(this.nsp.name, socket.id, 'connection');
return `Welcome to Websocket Chat Room Now: ${Date.now()} Your ID: ${socket.id}! \n`;
}
public async disconnect(socket: io.Socket) {
console.log(this.nsp.name, socket.id, 'disconnect');
}
@listener('message', (socket: io.Socket, packet: io.Packet, next: (err?: any) => void) => {
console.log(socket.nsp.name, socket.id, 'listener middleware', [...packet]);
next();
})
public async message(socket: io.Socket, data: any) {
console.log(this.nsp.name, socket.id, 'message', data)
this.cache[socket.id] = (this.cache[socket.id] || '') + data;
if (data == '\r' && this.cache[socket.id] !== "") {
let result = this.broadcast(this.cache[socket.id] + '\n')
this.cache[socket.id] = '';
return result;
}
return data;
}
}

View File

@@ -1,48 +1,76 @@
import 'reflect-metadata';
import * as http from 'http'
import * as express from "express";
import { InversifyExpressServer, interfaces, getRouteInfo } from 'inversify-express-utils';
import * as bodyParser from 'body-parser';
import { buildProviderModule } from '@cc-server/ioc';
import { rebuildServer } from '@cc-server/binding'
import * as prettyjson from "prettyjson";
import { Container } from 'inversify';
import * as bodyParser from 'body-parser';
import { buildWebSocket, io } from '@cc-server/ws'
import { buildProviderModule, Container } from '@cc-server/ioc';
import { InversifyExpressServer, interfaces, getRouteInfo, rebuildServer } from '@cc-server/binding'
export { io, http, express }
export class CcServerBoot {
private _container: Container;
private _server: InversifyExpressServer;
private _server: http.Server;
private _serverInstance: express.Application;
private _serverInversify: InversifyExpressServer;
private _wsServer: io.Server;
constructor(container?: Container) {
this._container = container || new Container();
this._container.load(buildProviderModule());
this._serverInstance = express();
this._server = http.createServer(this._serverInstance);
// start the server
this._server = new InversifyExpressServer(this._container);
this._server.setConfig((app) => {
this._serverInversify = new InversifyExpressServer(this._container, null, null, this._serverInstance);
this._serverInversify.setConfig((app) => {
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(bodyParser.raw());
});
this._wsServer = io(this._server, {
path: '/ws',
serveClient: false,
})
}
get server() {
return this._server;
}
get express() {
return this._serverInstance;
}
get inversify() {
return this._serverInversify;
}
get websocket() {
return this._wsServer;
}
public setConfig(fn: interfaces.ConfigFunction) {
this._server.setConfig(fn)
this._serverInversify.setConfig(fn)
}
public setErrorConfig(fn: interfaces.ConfigFunction) {
this._server.setErrorConfig(fn)
this._serverInversify.setErrorConfig(fn)
}
public build() {
this._serverInstance = this._server.build();
this._container.load(buildProviderModule());
this._serverInstance = this._serverInversify.build();
rebuildServer(this._container);
buildWebSocket(this._container, this._wsServer);
return this._serverInstance;
}
public start(port: number = 80) {
const routeInfo = getRouteInfo(this._container);
console.log(prettyjson.render({ routes: routeInfo }));
this._serverInstance.listen(port);
this._server.listen(port);
console.log(`Server started on port ${port} :)`);
}
}

View File

@@ -1,8 +1,10 @@
import { CcServerBoot } from './index'
import { CcServerBoot, express } from './index'
import './function/handle';
let server = new CcServerBoot();
server.express.use(express.static('public'));
server.build();
server.start();