checkcode.js 2.87 KB
'use strict';

const schedule = require('node-schedule'); 
const Router = require('koa-router');
const moment = require('moment');
const Check = require('../../ci/checkcode');

const {
    Project,
    Checklist,
    Checklogs
} = require('../../models');

const router = new Router();

router.get('/list', async(ctx) => {
    await ctx.render('action/checklist');
});

router.post('/list/query', async(ctx) => {
    let q = ctx.request.body;
    let start = parseInt(q.start || 0, 10);
    let length = parseInt(q.length || 10, 10);
    let draw = parseInt(q.draw, 10);

    let sort = {buildtime: -1};
    if (q.order && q.order.length > 0) {
        let col = q.order[0].column;
        let dir = q.order[0].dir === 'desc' ? -1 : 1;

        col = parseInt(col, 10);
        if (q.columns && q.columns.length > col) {
            sort = {};
            sort[q.columns[col].data] = dir;
        }
    }

    let logs = await Checklist.cfind({}).sort(sort).skip(start).limit(length).exec();
    let total = await Checklist.count();

    logs.forEach(l => {
        l.buildtime = moment(Number(l.buildtime)).format('YYYY-MM-DD HH:mm:ss');
    });

    ctx.body = {
        draw: draw,
        recordsTotal: total,
        recordsFiltered: total,
        data: logs
    };
});

router.get('/log', async(ctx) => {
    await ctx.render('action/checklog');
});

router.post('/log/query', async(ctx) => {
    let q = ctx.request.body;
    let data;
    if (!q.id) {
        data = "未找到相应id的数据";
    } else {
        data = await Checklogs.findById(q.id);
        data = (data || {}).text;
    }

    ctx.body = {
        data: data
    }
});

router.post('/exec', async(ctx) => {
    let q = ctx.request.body;

    if (!q.name || !q.branch) {
        ctx.body = {
            msg: "请输入正确的项目名及分支名"
        }
    } else {
        let project = await Project.findByName(q.name);

        new Check(project.name, project.gitlab, q.branch).check();
        ctx.body = {
            code: 200
        }
    }
});

module.exports = {
    router,
    async check() {
        let names = ['yohobuywap-node', 'yohobuy-node']; // 只检查pc 和wap站
        let rule = new schedule.RecurrenceRule();
        
        rule.dayOfWeek = [0, new schedule.Range(1, 6)];  
        rule.hour = 23;
        rule.minute = 59;  
        schedule.scheduleJob(rule, async() => {
            let running = {};
            let projects = await Project.findAll();
            if (!projects || !projects.length) {
                return;
            }

            projects.forEach(async(p) => {
                if (names.indexOf(p.name) === -1) {
                    return;
                }
                if (!running[p.name]) {
                    running[p.name] = true;
                    new Check(p.name, p.gitlab, p.checkbranch || 'master').check();    
                }
            });
        });
    },
};