import * as http from 'http' ; import * as express from 'express' ; import { Request , Response } from 'express' ; import * as bodyParser from 'body-parser' ; import * as compress from 'compression' ; export interface JSONParameters { sql ? : string ; expression ? : any ; } export interface JSONQueryProcessor { ( parameters , res ) : void ; } export function createJSONServer ( port , queryProcessor ) { let app = express ( ) ; app . disable ( 'x-powered-by' ) ; app . use ( compress ( ) ) ; app . get ( '/health' , ( req , res ) => { res . send ( `I am healthy @ ${ new Date ( ) . toISOString ( ) }` ) ; } ) ; app . use ( bodyParser . json ( ) ) ; app . post ( '/plyql' , ( req , res ) => { let { sql } = req . body ; if ( typeof sql !== "string" ) { res . status ( 400 ) . json ( { error : "'sql' must be a string" } ) ; return ; } console . log ( `Got SQL: ${ sql }` ) ; queryProcessor ( { sql } , res ) ; } ) ; app . post ( '/plywood' , ( req , res ) => { let { expression } = req . body ; if ( typeof expression === "undefined" ) { res . status ( 400 ) . json ( { error : "'expression' must be defined" } ) ; return ; } console . log ( `Got expression` ) ; queryProcessor ( { expression } , res ) ; } ) ; app . use ( ( err , req , res , next ) => { res . status ( err . status || 500 ) ; res . json ( { error : err . message } ) ; } ) ; let server = http . createServer ( app ) ; server . on ( 'error' , ( error ) => { if ( error . syscall !== 'listen' ) { throw error ; } switch ( error . code ) { case 'EACCES' : console . error ( `Port ${ port } requires elevated privileges` ) ; process . exit ( 1 ) ; break ; case 'EADDRINUSE' : console . error ( `Port ${ port } is already in use` ) ; process . exit ( 1 ) ; break ; default : throw error ; } } ) ; server . on ( 'listening' , ( ) => { let address = server . address ( ) ; console . log ( 'PlyQL server listening on port: ' + address . port ) ; } ) ; app . set ( 'port' , port ) ; server . listen ( port ) ; }