servers.js 2.13 KB
'use strict';

import Router from 'koa-router';

import Operation from '../../logger/operation';
import {
    Server
} from '../../models';

const r = new Router;

const envs = {
    production: '线上环境',
    preview: '灰度环境',
    test: '测试环境'
};

const servers = {
    config_page: async(ctx, next) => {
        let servers = await Server.findAll();
        servers.forEach(s => {
            s.envName = envs[s.env];
        });
        await ctx.render('action/servers', {
            servers: servers
        });
    },
    new_page: async(ctx, next) => {
        await ctx.render('action/server_form');
    },
    edit_page: async(ctx, next) => {
        let id = ctx.query.id;
        let server = await Server.findById(id);
        await ctx.render('action/server_form', server);
    },
    save: async(ctx, next) => {
        let {_id, host,username,password,port,env,deployDir } = ctx.request.body;
        let server = {
            host: host,
            username: username,
            password: password,
            port: port,
            env: env,
            deployDir: deployDir
        };
        if (_id) {
            await Server.update({
                _id: _id
            }, {
                $set: server
            });
            await Operation.action(ctx.session.user, 'EDIT_SERVER', '修改服务器配置', {_id: _id, host: host});
        } else {
            await Server.insert(server);
            await Operation.action(ctx.session.user, 'NEW_SERVER', '新增服务器配置', {_id: _id, host: host});
        }

        ctx.redirect('/servers/setting');
        ctx.status = 301;
    },
    del: async(ctx, next) => {
        let id = ctx.request.body.id;
        let server = await Server.findById(id);

        await Server.removeById(id);
        await Operation.action(ctx.session.user, 'DELETE_SERVER', '删除服务器配置', {_id: id, host: server.host});
        ctx.body = {
            code: 200
        };
    }
};

r.get('/setting', servers.config_page);
r.get('/new', servers.new_page);
r.get('/edit', servers.edit_page);
r.post('/save', servers.save);
r.post('/del', servers.del);

export default r;