api_cache.js 2.03 KB


'use strict';

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

const {
    MemcachedHost
} = require('../../models');

const ApiCache = require('../../ci/api_cache');

let r = new Router();

const api_cache = {
    async index(ctx) {
        let hosts = await MemcachedHost.findAll();

        hosts.forEach(host => {
            host.hostFm = host.host.replace(/\./g, '-').replace(/:/g, '-');
        });
        await ctx.render('action/memcached', {hosts: hosts});
    },

    async addHost(ctx) {
        let q = ctx.request.body;

        await MemcachedHost.insert({host: q.host});
        return ctx.body = {
            code: 200
        };
    },

    async delHost(ctx) {
        let q = ctx.request.body;

        await MemcachedHost.removeById(q.id);
        return ctx.body = {
            code: 200
        };
    },

    async cleanKey(ctx) {
        let q = ctx.request.body;
        let key = q.key;

        let hosts = await MemcachedHost.findAll();

        _.each(hosts, (h) => {
            (new ApiCache(h.host)).clean(key);
        });

        return ctx.body = {
            code: 200
        };
    },

    async flushAll(ctx) {
        let hosts = await MemcachedHost.findAll();

        _.each(hosts, (h) => {
            (new ApiCache(h.host)).flushAll();
        });

        return ctx.body = {
            code: 200
        };
    },

    async monit(ctx) {
        let hosts = await MemcachedHost.findAll();

        _.each(hosts, (h) => {
            (new ApiCache(h.host)).stats();
        });

        return ctx.body = {
            code: 200
        };
    },

    async restart(ctx) {
        let host = ctx.request.body.host;

        (new ApiCache(host)).restart();
        return ctx.body = {
            code: 200
        };
    }
};

r.get('/', api_cache.index);
r.get('/monit', api_cache.monit);
r.post('/host/add', api_cache.addHost);
r.post('/host/del', api_cache.delHost);
r.post('/clean', api_cache.cleanKey);
r.post('/flush', api_cache.flushAll);
r.post('/restart', api_cache.restart);

module.exports = r;