remix-project mirror
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
remix-project/libs/remix-simulator/src/server.ts

72 lines
1.7 KiB

4 years ago
import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
7 years ago
const app = express()
4 years ago
import expressWs from 'express-ws'
import { Provider } from './provider'
import { Logger } from './utils/logs'
const logger = new Logger()
7 years ago
class Server {
4 years ago
provider
rpcOnly
constructor (options) {
this.provider = new Provider(options)
this.provider.init().then(() => {
4 years ago
logger.log('Provider initiated')
}).catch((error) => {
4 years ago
logger.log(error)
})
this.rpcOnly = options.rpc
}
start (host, port) {
expressWs(app)
5 years ago
app.use(cors())
4 years ago
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.send('Welcome to remix-simulator')
})
if (this.rpcOnly) {
app.use((req, res) => {
this.provider.sendAsync(req.body, (err, jsonResponse) => {
if (err) {
return res.send(JSON.stringify({ error: err }))
}
res.send(jsonResponse)
})
})
} else {
app.ws('/', (ws, req) => {
ws.on('message', (msg) => {
this.provider.sendAsync(JSON.parse(msg), (err, jsonResponse) => {
if (err) {
return ws.send(JSON.stringify({ error: err }))
}
ws.send(JSON.stringify(jsonResponse))
})
})
this.provider.on('data', (result) => {
ws.send(JSON.stringify(result))
})
})
}
app.listen(port, host, () => {
4 years ago
logger.log('Remix Simulator listening on ws://' + host + ':' + port)
if (!this.rpcOnly) {
4 years ago
logger.log('http json-rpc is deprecated and disabled by default. To enable it use --rpc')
}
})
}
}
module.exports = Server