import {join} from "path"; import {readFileSync} from "fs"; import * as express from "express"; import {cyan} from "chalk"; import {views} from "./views"; import {Config, getConfig} from "./config"; import {Data} from "./data"; import {Watch} from "./watch"; export class Server { private app = express(); private http = require('http').Server(this.app); private io = require('socket.io')(this.http); private config: Config = getConfig(); private data: Data = new Data(); public start(): void { const port: number = process.env.PORT || 9095; this.bootstrap(); this.http.listen(port, () => { console.log(`Listening at ${cyan(`http://127.0.0.1:${port}`)}`) }); } public bootstrap(): void { this.app.use('/data', (req, res) => res.send(this.fetchData())); this.app.get('/', (req, res) => { const viewEngine = new views['twig'](); const context = this.fetchData(); const templateFile: string = this.config.template ? join(process.cwd(), this.config.template) : join(__dirname, '..', 'web/templates/pattern-library.twig'); const template: string = readFileSync(templateFile, 'utf8'); const view: string = viewEngine.compile(template, context); res.send(view); }); this.app.get('/:type/:name', (req, res) => { const viewEngine = new views['twig'](); const {type, name} = req.params; const context = { item: this.fetchData()[type].find((item: any) => item.name === name), globals: this.config.globals }; const templateFile: string = join(__dirname, '..', 'web/templates/component-view.twig'); const template: string = readFileSync(templateFile, 'utf8'); const view: string = viewEngine.compile(template, context); res.send(view); }); } public fetchData(): Object { return this.data.getAllItems(); } public watch(): void { this.start(); new Watch(this.io).start(); } }