import { Debe } from 'debe' ; import express from 'express' ; import cors from 'cors' ; import bodyParser from 'body-parser' ; import { Server } from 'http' ; import { IHandlerArgs } from 'debe-http' ; export class HttpServer { express : express . Express ; app : Server ; db : Debe ; queryLogger ? : ( args : IHandlerArgs [ ] ) => void ; constructor ( db ) ; constructor ( db , port ) ; constructor ( db , express ) ; constructor ( db , arg ? ) { if ( typeof arg === 'number' ) { this . express = express ( ) ; this . app = this . express . listen ( arg ) ; this . express . use ( cors ( ) ) ; this . express . use ( bodyParser . urlencoded ( { extended : true } ) ) ; this . express . use ( bodyParser . json ( ) ) ; this . express . post ( `/` , ( req , res ) => { const requests = req . body || [ ] ; this . handleRequest ( requests ) . then ( ( result ) => res . json ( result ) ) . catch ( ( err ) => res . json ( { err } ) ) ; } ) ; } else if ( arg ) { this . express = arg ; } this . db = db ; } async close ( ) { if ( this . app ) { this . app . close ( ) ; } } async handleRequest ( args ) { const orderedArgs = args . reduce < { arg : IHandlerArgs ; index : number ; } [ ] > ( ( result , arg , index ) => { if ( arg . method === 'insert' ) { result = [ { arg , index } , ... result ] ; } else { result = [ ... result , { arg , index } ] ; } return result ; } , [ ] ) ; if ( this . queryLogger ) { this . queryLogger ( args ) ; } const results = [ ] ; return Promise . all ( orderedArgs . map ( ( { arg , index } ) => { const { collection , method , query , options } = arg ; let promise = method === 'insert' ? this . db . insert ( collection , query , options ) : this . db [ method as 'all' ] ( collection , query ) ; return promise . then ( result => ( results [ index ] = result ) ) ; } ) ) . then ( ( ) => results ) ; } }