express-template/rpc/server.ts

41 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

2021-08-29 10:31:21 +00:00
// json-rpc-engine
// rpc-websockets
import { Server as RpcWebsocketServer } from 'rpc-websockets'
import { isFinite } from 'underscore'
import { event } from '../event'
import SysConf from '../utils/sys_conf'
// const rpc_token = SysConf.get('WS_JSON_RPC_SERVER_TOKEN')
// if(!rpc_token) {
// throw new Error('缺少参数WS_JSON_RPC_SERVER_TOKEN')
// }
function register (server:RpcWebsocketServer) {
server.setAuth(params=>params.token === SysConf.get('WS_JSON_RPC_SERVER_TOKEN'))
// server.register('snowflake',()=>snowflake.create().toString(10)).protected()
// server.register('shortid',()=>shortid.create().toString(10)).protected()
}
const host = process.env.WS_JSON_RPC_SERVER_HOST || '0.0.0.0'
const port = process.env.WS_JSON_RPC_SERVER_PORT || ''
if(!isFinite(port)) {
throw new Error('缺少参数json-rpc服务端口 [WS_JSON_RPC_SERVER_PORT]')
}
// {"method":"shortid","id":"abcd","jsonrpc":"2.0"}
// {"method":"rpc.login","id":"abcde","jsonrpc":"2.0","params":{"token":"zcj"}}
event.on('http-server-started',function () {
const server = new RpcWebsocketServer({ port,host })
register(server)
console.log(`启动json-rpc服务正在监听${host}:${port}`)
})