ETMX Typescritp Server Framework
Typescript node.js 服务器开发框架
声明
本人英文不好,莫笑。
Install(安装)
npm install -g etmx
Use ETMX(使用ETMX)
etmx create [project name]
Description(描述)
ETMX is a typescript server framework, base on express framework.
ETMX contains:
1、 Server(use this class to create a server)
2、 Router(use this class to create a router)
3、 RouterManager(use this class to manage routers)
4、 Database(use this class to handle database)
Configurations(配置)
ETMX use a .json file or a object like to configure server, configurations contains:
Create Route(创建路由)
use Router class to create a router, example:
import {Router} from 'etmx';
let router = new Router();
router
.name('/main')
.get('/test', (req, res, next) => {
res.end('Hello world');
})
.get('/user/:number/:name', (req, res, next) => {
router.mysql.easy(async mysql => {
try {
let data = await mysql.query('select * from ??', 'user');
res.json(data);
} catch (e) {
console.log(e);
}
});
});
export default router;
Create server(创建服务器)
Now, let's create a server and start it
import {Server, RouterManager} from 'etmx';
import * as path from 'path';
Server.confdir = path.join(__dirname, './');
Server.rootdir = __dirname;
let server = new Server('etmx');
server.routers = app => {
let manager = new RouterManager(__dirname);
[
'./Main',
].forEach(_r => manager.router = _r);
return manager.routers;
};
server.create();
How to use websocket (websocket使用)
Etmx provide a easy way to create and manage websocket, to use websocket you should do:
- open serverconfig set websocket field a true value
- create a websocet handler
- open your webserver entry file and add websocket handler
:::notice:if your webserver use https websocket is wss://, if http websocket is ws://
webscket setting like:
{
"server": {
"websocket":true
}
}
websocket handler like:
import {WSHandler, WSManager} from './';
interface Props {
uid:string,
uname:string,
}
export class HandlerName extends WSHandler<Props> {
onConnect() {
console.log(this.params.uid);
this.send({type:'welcome', message:'Welcome to join this room'});
}
onClose() {
WSManager.handlers.forEach(handler=>{
if(handler.params.uid == this.params.uid) return;
handler.send({type:'leave', message:`[${this.params.uname}] left this room`})
})
}
onMessage(message) {
WSManager.handlers.forEach(handler=>{
if(handler.params.uid == this.params.uid) return;
handler.send({type:'text', message:message});
})
}
}
the end, in entry file set
server.wsHandler = HandlerName;