Files
bch-dex/bin/server.js
T

147 lines
4.4 KiB
JavaScript
Raw Normal View History

2022-02-23 05:51:12 -08:00
/*
This Koa server has two interfaces:
- REST API over HTTP
- JSON RPC over IPFS
The architecture of the code follows the Clean Architecture pattern:
https://troutsblog.com/blog/clean-architecture
*/
// npm libraries
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
const convert = require('koa-convert')
const logger = require('koa-logger')
const mongoose = require('mongoose')
const session = require('koa-generic-session')
const passport = require('koa-passport')
const mount = require('koa-mount')
const serve = require('koa-static')
const cors = require('kcors')
// Local libraries
const config = require('../config') // this first.
const AdminLib = require('../src/adapters/admin')
// const adminLib = new AdminLib()
const WebHookLib = require('../src/adapters/webhook')
const webhookLib = new WebHookLib()
// const JSONRPC = require('../src/rpc')
// const rpc = new JSONRPC()
const errorMiddleware = require('../src/controllers/rest-api/middleware/error')
// const { wlogger } = require('../src/adapters/wlogger')
class Server {
constructor () {
this.adminLib = new AdminLib()
}
async startServer () {
try {
// Create a Koa instance.
const app = new Koa()
app.keys = [config.session]
// Connect to the Mongo Database.
mongoose.Promise = global.Promise
mongoose.set('useCreateIndex', true) // Stop deprecation warning.
console.log(
`Connecting to MongoDB with this connection string: ${config.database}`
)
await mongoose.connect(config.database, {
useUnifiedTopology: true,
useNewUrlParser: true
})
console.log(`Starting environment: ${config.env}`)
console.log(`Debug level: ${config.debugLevel}\n`)
console.log(`Using this web3 CashStack service: ${config.consumerUrl}`)
console.log('Alternative web services listed here: https://gist.github.com/christroutner/63c5513782181f8b8ea3eb89f7cadeb6')
console.log('This app is built on top of the CashStack. Find out more: https://CashStack.info\n')
2022-02-23 05:51:12 -08:00
// MIDDLEWARE START
app.use(convert(logger()))
app.use(bodyParser())
app.use(session())
app.use(errorMiddleware())
// Used to generate the docs.
app.use(mount('/', serve(`${process.cwd()}/docs`)))
// Mount the page for displaying logs.
app.use(mount('/logs', serve(`${process.cwd()}/config/logs`)))
// User Authentication
require('../config/passport')
app.use(passport.initialize())
app.use(passport.session())
2022-01-12 15:33:04 -08:00
// Enable CORS for testing
// THIS IS A SECURITY RISK. COMMENT OUT FOR PRODUCTION
// Dev Note: This line must come BEFORE controllers.attachRESTControllers()
app.use(cors({ origin: '*' }))
2022-02-23 05:51:12 -08:00
// Attach REST API and JSON RPC controllers to the app.
const Controllers = require('../src/controllers')
const controllers = new Controllers()
await controllers.attachRESTControllers(app)
app.controllers = controllers
// MIDDLEWARE END
// Delay startup to give the P2WDB time to start first, so that it accepts the webook call
2022-05-08 13:45:01 -07:00
await sleep(20000)
2022-02-23 05:51:12 -08:00
// Create webhook
try {
try {
// Delete an old webhook if it exists.
2022-03-26 07:32:00 -07:00
await webhookLib.deleteWebhook(config.webhookTarget)
2022-02-23 05:51:12 -08:00
} catch (err) {
/* exit quietly */
// console.log('err deleting webhook: ', err)
}
2022-03-26 07:32:00 -07:00
await webhookLib.createWebhook(config.webhookTarget)
2022-02-23 05:51:12 -08:00
console.log('Webhook created')
} catch (error) {
console.log('Webhook cant be created')
}
// startServer()
await app.listen(config.port)
console.log(`Server started on ${config.port}`)
// Create the system admin user.
const success = await this.adminLib.createSystemUser()
if (success) console.log('System admin user created.')
// Attach the other IPFS controllers.
// Skip if this is a test environment.
if (config.env !== 'test') {
await controllers.attachControllers(app)
}
2022-02-23 05:51:12 -08:00
return app
} catch (err) {
console.error('Could not start server. Error: ', err)
2021-12-29 17:46:05 -08:00
console.log(
'Exiting after 5 seconds. Depending on process manager to restart.'
)
await sleep(5000)
process.exit(1)
2022-02-23 05:51:12 -08:00
}
}
}
2021-12-29 17:46:05 -08:00
function sleep (ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
2022-02-23 05:51:12 -08:00
module.exports = Server