import {Interfaces} from "./Interfaces" import * as HTTP from "http"; import url = require("url"); export namespace ChatApi { export class ApiServer implements Interfaces.ServerInterface { private clientsManager: Interfaces.ClientsManagerInterface; private conversationsManager: Interfaces.ConversationsManagerInterface; private logger: Interfaces.LoggerInterface; private routes: RoutesCollection = {}; constructor(clientsManager: Interfaces.ClientsManagerInterface, conversationsManager: Interfaces.ConversationsManagerInterface, logger: Interfaces.LoggerInterface, routes: RoutesCollection) { this.clientsManager = clientsManager; this.conversationsManager = conversationsManager; this.logger = logger; this.routes = routes; this.logger.debug(`Starting API server`); } processRequest(request: HTTP.IncomingMessage, response: HTTP.ServerResponse) { let path = url.parse(request.url).pathname; if (this.routes.hasOwnProperty(path)) { this.logger.debug(`Processing action "${path}"`); let action = this.routes[path]; action.call(this, request, response); } else { this.logger.debug(`Action "${path}" not found`); response.writeHead(404); response.end(`Action "${path}" not found`); } } refreshUsers(request: HTTP.IncomingMessage, response: HTTP.ServerResponse) { let content = ''; request.on('data', (chunk) => { content += chunk; }).on('end', () => { try { let data = JSON.parse(content); this.clientsManager.get(data.id, true).then((client: Interfaces.ClientInterface) => { response.end('Ok'); }).catch((err: Error) => { this.logger.error(err.message); this.logger.error(err.stack); response.writeHead(500, {'Content-type': 'text/plain'}); response.end(err.message + err.stack); }); } catch (err) { this.logger.error(err.message); this.logger.error(err.stack); this.logger.error('DATA: '+content); response.writeHead(500, {'Content-type': 'text/plain'}); response.end(err.message + "\n" + err.stack + "\nData: "+ content); } }); } } export interface RoutesCollection { [path: string]: (request: HTTP.IncomingMessage, response: HTTP.ServerResponse) => void } }