Files
bch-dex/bin/server.js
T

169 lines
5.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
2022-09-08 08:58:39 -07:00
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import convert from 'koa-convert'
import logger from 'koa-logger'
import mongoose from 'mongoose'
import session from 'koa-generic-session'
import passport from 'koa-passport'
import mount from 'koa-mount'
import serve from 'koa-static'
import cors from 'kcors'
2022-02-23 05:51:12 -08:00
// Local libraries
2022-09-08 08:58:39 -07:00
import config from '../config/index.js' // this first.
2022-02-23 05:51:12 -08:00
2022-09-08 08:58:39 -07:00
import AdminLib from '../src/adapters/admin.js'
import errorMiddleware from '../src/controllers/rest-api/middleware/error.js'
2024-04-26 14:38:03 -07:00
import { usageMiddleware } from '../src/use-cases/usage-use-cases.js'
// import wlogger from '../src/adapters/wlogger.js'
2022-09-08 08:58:39 -07:00
import Controllers from '../src/controllers/index.js'
import { applyPassportMods } from '../config/passport.js'
2022-02-23 05:51:12 -08:00
class Server {
constructor () {
2022-06-19 20:00:25 -07:00
// Encapsulate dependencies
2022-02-23 05:51:12 -08:00
this.adminLib = new AdminLib()
2022-06-19 20:00:25 -07:00
this.controllers = new Controllers()
this.mongoose = mongoose
this.config = config
this.process = process
2022-02-23 05:51:12 -08:00
}
async startServer () {
try {
// Create a Koa instance.
const app = new Koa()
2022-06-19 20:00:25 -07:00
app.keys = [this.config.session]
2022-02-23 05:51:12 -08:00
if (!this.config.noMongo) {
// Connect to the Mongo Database.
this.mongoose.Promise = global.Promise
this.mongoose.set('useCreateIndex', true) // Stop deprecation warning.
console.log(
`Connecting to MongoDB with this connection string: ${this.config.database}`
)
await this.mongoose.connect(this.config.database, {
useUnifiedTopology: true,
useNewUrlParser: true
})
}
2022-02-23 05:51:12 -08:00
2022-06-19 20:00:25 -07:00
console.log(`Starting environment: ${this.config.env}`)
2022-06-29 16:29:28 -07:00
console.log(`Debug level: ${this.config.debugLevel}\n`)
console.log(`Using this web3 CashStack service: ${this.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())
2024-04-26 14:38:03 -07:00
app.use(usageMiddleware())
2022-02-23 05:51:12 -08:00
// 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
2022-09-08 08:58:39 -07:00
// require('../config/passport')
applyPassportMods(passport)
2022-02-23 05:51:12 -08:00
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-06-27 10:09:08 -07:00
// Wait for any adapters to initialize.
await this.controllers.initAdapters()
// Wait for any use-libraries to initialize.
await this.controllers.initUseCases()
2022-02-23 05:51:12 -08:00
// Attach REST API and JSON RPC controllers to the app.
2022-06-19 20:00:25 -07:00
await this.controllers.attachRESTControllers(app)
2022-02-23 05:51:12 -08:00
2022-06-19 20:00:25 -07:00
app.controllers = this.controllers
2022-02-23 05:51:12 -08:00
// MIDDLEWARE END
// 7/7/22 CT: This code paragraph can be deleted
// Delay startup to give the P2WDB time to start first, so that it accepts the webook call
// if (this.config.env !== 'test') {
// await this.sleep(20000)
// }
2022-02-23 05:51:12 -08:00
// Create webhook
// try {
// try {
// // Delete an old webhook if it exists.
// await webhookLib.deleteWebhook(config.webhookTarget)
// } catch (err) {
// /* exit quietly */
// // console.log('err deleting webhook: ', err)
// }
//
// await webhookLib.createWebhook(config.webhookTarget)
// console.log('Webhook created')
// } catch (error) {
// console.log('Webhook cant be created')
// }
2022-02-23 05:51:12 -08:00
// startServer()
2022-06-29 16:29:28 -07:00
this.server = await app.listen(config.port)
2022-02-23 05:51:12 -08:00
console.log(`Server started on ${config.port}`)
if (!this.config.noMongo) {
// Create the system admin user.
const success = await this.adminLib.createSystemUser()
if (success) console.log('System admin user created.')
}
2022-02-23 05:51:12 -08:00
// Attach the other IPFS controllers.
// Skip if this is a test environment.
2022-06-19 20:00:25 -07:00
if (this.config.env !== 'test') {
await this.controllers.attachControllers(app)
}
2022-02-23 05:51:12 -08:00
// Display configuration settings
2022-05-26 08:24:45 -07:00
console.log('\nConfiguration:')
2022-06-19 20:00:25 -07:00
console.log(`Circuit Relay: ${this.config.isCircuitRelay}`)
console.log(`IPFS TCP port: ${this.config.ipfsTcpPort}`)
console.log(`IPFS WS port: ${this.config.ipfsWsPort}`)
console.log(`IPFS WebRTC port: ${this.config.ipfsWebRtcPort}`)
console.log(`Connection preference: ${this.config.connectPref}\n`)
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 this.sleep(5000)
this.process.exit(1)
2022-02-23 05:51:12 -08:00
}
}
sleep (ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
2021-12-29 17:46:05 -08:00
}
2022-09-08 08:58:39 -07:00
export default Server