UNPKG

1.7 kBJavaScriptView Raw
1const express = require('express')
2const cors = require('cors')
3const bodyParser = require('body-parser')
4const app = express()
5const expressWs = require('express-ws')
6const Provider = require('./provider')
7const log = require('./utils/logs.js')
8
9class Server {
10 constructor (options) {
11 this.provider = new Provider(options)
12 this.provider.init().then(() => {
13 log('Provider initiated')
14 }).catch((error) => {
15 log(error)
16 })
17 this.rpcOnly = options.rpc
18 }
19
20 start (host, port) {
21 expressWs(app)
22
23 app.use(cors())
24 app.use(bodyParser.urlencoded({extended: true}))
25 app.use(bodyParser.json())
26
27 app.get('/', (req, res) => {
28 res.send('Welcome to remix-simulator')
29 })
30
31 if (this.rpcOnly) {
32 app.use((req, res) => {
33 this.provider.sendAsync(req.body, (err, jsonResponse) => {
34 if (err) {
35 return res.send(JSON.stringify({ error: err }))
36 }
37 res.send(jsonResponse)
38 })
39 })
40 } else {
41 app.ws('/', (ws, req) => {
42 ws.on('message', (msg) => {
43 this.provider.sendAsync(JSON.parse(msg), (err, jsonResponse) => {
44 if (err) {
45 return ws.send(JSON.stringify({ error: err }))
46 }
47 ws.send(JSON.stringify(jsonResponse))
48 })
49 })
50
51 this.provider.on('data', (result) => {
52 ws.send(JSON.stringify(result))
53 })
54 })
55 }
56
57 app.listen(port, host, () => {
58 log('Remix Simulator listening on ws://' + host + ':' + port)
59 if (!this.rpcOnly) {
60 log('http json-rpc is deprecated and disabled by default. To enable it use --rpc')
61 }
62 })
63 }
64}
65
66module.exports = Server