|
| 1 | +import { app } from "@arkecosystem/core-container"; |
| 2 | +import { createServer, mountServer } from "@arkecosystem/core-http-utils"; |
| 3 | +import { Logger } from "@arkecosystem/core-interfaces"; |
| 4 | +import Hapi from "@hapi/hapi"; |
| 5 | + |
| 6 | +export class Server { |
| 7 | + private logger = app.resolvePlugin<Logger.ILogger>("logger"); |
| 8 | + |
| 9 | + private http: any; |
| 10 | + |
| 11 | + public constructor(private readonly config: any) { |
| 12 | + this.config = config; |
| 13 | + } |
| 14 | + |
| 15 | + public async start(): Promise<void> { |
| 16 | + const options = { |
| 17 | + host: this.config.host, |
| 18 | + port: this.config.port, |
| 19 | + }; |
| 20 | + |
| 21 | + if (this.config.enabled) { |
| 22 | + this.http = await createServer(options); |
| 23 | + this.http.app.config = this.config; |
| 24 | + |
| 25 | + await Server.registerRoutes("HTTP", this.http); |
| 26 | + } |
| 27 | + |
| 28 | + // TODO: add SSL support. See plugin `core/packages/core-api` for more information |
| 29 | + } |
| 30 | + |
| 31 | + public async stop(): Promise<void> { |
| 32 | + if (this.http) { |
| 33 | + this.logger.info(`Stopping Custom HTTP SERVER`); |
| 34 | + await this.http.stop(); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public async restart(): Promise<void> { |
| 39 | + if (this.http) { |
| 40 | + await this.http.stop(); |
| 41 | + await this.http.start(); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public instance(type: string): Hapi.Server { |
| 46 | + return this[type]; |
| 47 | + } |
| 48 | + |
| 49 | + private static async registerRoutes(name: string, server: Hapi.Server): Promise<void> { |
| 50 | + server.route({ |
| 51 | + method: "GET", |
| 52 | + path: "/", |
| 53 | + handler() { |
| 54 | + return { data: "Hello World!" }; |
| 55 | + }, |
| 56 | + }); |
| 57 | + |
| 58 | + await mountServer(`Custom HTTP Public ${name.toUpperCase()} API`, server); |
| 59 | + } |
| 60 | +} |
0 commit comments