client-precache.js 1.73 KB

const Router = require('koa-router');
const _ = require('lodash');
const md5 = require('md5');

const CDNCONFIG = require('../../../config/cdn_config');


let r = new Router();

const manifestPath = 'client/precache/statics/manifest.json';

const client = {
    index: async(ctx, next) => {
        await ctx.render('action/client-precache', {
            manifestPath
        });
    },
    save: async(ctx, next) => {
        let files = ctx.request.body.files;
        let lastRevision = ctx.request.body.lastRevision;
        let trimFiles = [];

        _.forEach(files, val => {
            trimFiles.push(_.trim(val));
        });

        trimFiles = _.compact(_.uniq(trimFiles));

        let revision = md5(trimFiles.join(','));

        if (revision === lastRevision) {
            return ctx.body = {
                code: 400,
                message: '请修改后再保存'
            };
        }

        let readable = new Buffer.from(JSON.stringify({
            files: trimFiles,
            revision
        }));
        let config = _.cloneDeep(CDNCONFIG.main);

        _.assign(config, {
            key: manifestPath
        });

        let qnMain = require('../../../lib/qiniu')(config);
        let upResult = await qnMain.uploadAsync(readable, {key: manifestPath});

        if (upResult && upResult.url) {
            return ctx.body = {
                code: 200,
                message: '修改成功',
                data: {
                    url: upResult.url
                }
            };
        } else {
            return ctx.body = {
                code: 400,
                message: '修改失败'
            };
        }
    }
}

r.get('/client', client.index);
r.post('/client/save', client.save);

module.exports = r;