import { runMiddleware } from './runMiddleware'; import { Application } from 'express'; import { assignIn } from 'lodash'; export interface ICallOptions { method: "post", headers?: { 'Content-Type': 'application/json' }, body: { [index: string]: any } } /** * Function that will generate an async accessor Function. * @param app the provided Express App. */ export function getBackendAccesors(app: Application){ // Create a Run-Middle-Ware runMiddleware(app); // Define a apiCall Function, which could be used to perform internal // Request on the API. function apiCall(url: string, options: ICallOptions){ return new Promise((resolve, reject) => { // Define the Default Options const defaults: Partial = { headers: { 'Content-Type': 'application/json' } } // Mix the Options. const opts: ICallOptions = assignIn(defaults, options); // Perform the Call (app as any).runMiddleware(url,opts,(responseCode: number,body: T) => { // Based on the Response code, decide whether the call was a Fail or not. if (responseCode === 200){ // If everything is fine, // Just return the body. return resolve(body); } else { const error = new Error('Call Ended with responseCode = ' + responseCode.toString()); return reject(error) } }) }) } return apiCall; }