All files staticLib.js

96% Statements 24/25
70% Branches 7/10
100% Functions 5/5
96% Lines 24/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55    1x 1x 1x     1x   2x 2x     2x 2x   2x         2x 2x 2x   2x 2x   2x 2x 2x 2x   1x 1x 1x                   2x       2x 2x        
'use strict';
 
const fs = require('fs')
    , path = require('path')
    , debug = require('debug')('koajs-toolkit:staticLib')
    ;
 
module.exports = class StaticLib{
    constructor(app, config) {
        const Koa = require('koa')
            , mount = require('koa-mount')
            ;
 
        return new Promise((resolve)=>{
            let pathSites=config || {} ;
 
            Iif(typeof pathSites === 'string'){
                pathSites={'/':pathSites};
            }
 
            // for(let i=0, end=pathSites.length; i<end; i++){
            let asyncs=[];
            for (let pathSite in pathSites) {
                let pathDir=pathSites[pathSite];
 
                Eif(pathDir.indexOf('/')!=0){
                    pathDir=path.join(process.cwd() ,pathDir);
                }
                asyncs.push(new Promise(function(resolve){
                    fs.stat(pathDir, (err, stat)=>{
                        err && debug(pathDir + ' not exists');
                        if(stat){
                            // si "/_site" exist alors on sert les fichiers present dans ce dossier
                            const appSite=new Koa();
                            appSite.use(require('koa-static')(pathDir, {extensions: ['html','htm','txt']}));
                            app.use(mount(pathSite, appSite));
 
                            // respond specific 404 page if no file found
                            // const notFoundPage=fs.readFileSync(pathDir+'/assets/html/404.html');
                            // app.use(async (ctx, next) => {
                            //     await next();
                            //     ctx.response.type = 'text/html';
                            //     ctx.response.body = notFoundPage;
                            // });
                        }
                        resolve();
                    });
                }));
            }
            Promise.all(asyncs).then(function() {
                resolve();
            });
        });
    }
};