const express = require('express'); import {read} from "./read"; interface Middleware{ name:string; keys:Array; run:Function; } function containsAny(array:Array, keys:Array):boolean{ for (let i = 0; i < keys.length; i++) { if (array.indexOf(keys[i]) != -1) return true; } return false; } class Translucid { middleware:Array = []; constructor(public app) {} use(obj:Middleware):void{ this.middleware.push(obj); } public(path:string = ""):void{ this.app.use(`/${path}`, express.static(`${__dirname}/../../${path}`)); } async bindJSON(path:string):Promise{ const json = await read(path); const object = JSON.parse(json); for (let i in object){ const classes = object[i].classes || []; const sendAsFiles = object[i].sendFiles; if (sendFiles != false) sendFiles = true; this.bind(i,object[i].file,classes,sendFiles); } } bind(path:string = "/", filepath:string = "", classes:Array = [],sendFiles:boolean=true):void{ this.app.get(path, async (req, res)=> { const readResults = await read(filepath); const toRun:Array = []; for (let i of this.middleware){ if (containsAny(classes, i.keys)) { toRun.push(i.run); } } const decorated:Array = []; const expressArgs = [req, res]; for (let i = 0; i < toRun.length; i++) { decorated.push((prev:any):void => { toRun[i](prev, ...expressArgs, decorated[i + 1]); }); } decorated.push((prev:any):void => { if (!sendFiles) res.send(prev); else res.sendFile(prev); }); decorated[0](sendfiles?readResults:`${__dirname}/../../${filepath}`); }); } } export {Translucid};