2019-01-22 19:26:18 +01:00
|
|
|
const express = require('express');
|
|
|
|
import {read} from "./read";
|
|
|
|
|
|
|
|
interface Middleware{
|
|
|
|
name:string;
|
|
|
|
keys:Array<string>;
|
|
|
|
run:Function;
|
|
|
|
}
|
|
|
|
|
|
|
|
function containsAny(array:Array<string>, keys:Array<string>):boolean{
|
|
|
|
for (let i = 0; i < keys.length; i++) {
|
|
|
|
if (array.indexOf(keys[i]) != -1)
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
class Translucid {
|
|
|
|
middleware:Array<Middleware> = [];
|
|
|
|
|
|
|
|
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<void>{
|
|
|
|
const json = await read(path);
|
|
|
|
const object = JSON.parse(json);
|
|
|
|
|
|
|
|
for (let i in object){
|
2019-01-22 20:01:26 +01:00
|
|
|
const classes = object[i].classes || [];
|
2019-01-22 21:23:50 +01:00
|
|
|
let sendFiles = object[i].sendFiles;
|
2019-01-22 21:18:43 +01:00
|
|
|
if (sendFiles != false) sendFiles = true;
|
|
|
|
this.bind(i,object[i].file,classes,sendFiles);
|
2019-01-22 19:26:18 +01:00
|
|
|
}
|
|
|
|
}
|
2019-01-22 21:18:43 +01:00
|
|
|
bind(path:string = "/", filepath:string = "", classes:Array<string> = [],sendFiles:boolean=true):void{
|
2019-01-22 19:26:18 +01:00
|
|
|
this.app.get(path, async (req, res)=> {
|
|
|
|
const readResults = await read(filepath);
|
|
|
|
const toRun:Array<Function> = [];
|
|
|
|
|
|
|
|
for (let i of this.middleware){
|
|
|
|
if (containsAny(classes, i.keys)) {
|
|
|
|
toRun.push(i.run);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const decorated:Array<Function> = [];
|
|
|
|
const expressArgs = [req, res];
|
|
|
|
|
|
|
|
for (let i = 0; i < toRun.length; i++) {
|
|
|
|
decorated.push((prev:any):void => {
|
|
|
|
toRun[i](prev, ...expressArgs, decorated[i + 1]);
|
|
|
|
});
|
|
|
|
}
|
2019-01-22 20:54:03 +01:00
|
|
|
decorated.push((prev:any):void => {
|
2019-01-22 21:14:51 +01:00
|
|
|
if (!sendFiles)
|
|
|
|
res.send(prev);
|
|
|
|
else
|
|
|
|
res.sendFile(prev);
|
2019-01-22 19:26:18 +01:00
|
|
|
});
|
|
|
|
|
2019-01-22 21:14:51 +01:00
|
|
|
decorated[0](sendfiles?readResults:`${__dirname}/../../${filepath}`);
|
2019-01-22 19:26:18 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2019-01-22 19:49:50 +01:00
|
|
|
export {Translucid};
|