seo.js 9.53 KB
'use strict';

const Router = require('koa-router');
const _ = require('lodash');
const md5 = require('md5');
const pager = require('../utils/pager');
const seoModel = require('../models/seoModel');

let r = new Router();

const TYPE_LIST = [
    {name: '商品', type: 'skn', lt: 'SKN'},
    {name: '逛', type: 'article', lt: 'ID'},
    {name: '店铺', type: 'shop', lt: 'ShopId'},
    {name: '链接', type: 'url', lt: 'URL'}
];

const tdk = {
    // tdk 列表
    index: async(ctx, next) => {
        let resData = {};
        let type = ctx.query.type || 'skn',
            page = parseInt(`0${ctx.query.page}`, 10) || 1,
            limit = parseInt(`0${ctx.query.limit}`, 10) || 20,
            query = ctx.query.query;
        let listKey = `tdk:${type}:links`,
            startId = (page - 1) * limit,
            typeObj = _.find(TYPE_LIST, {'type': type}) || {};
        let hmget = [];

        if (query) {
            query = _.trim(query);
            resData.query = query;

            query = type === 'url' ? md5(query) : query;

            await ctx.redis.multi([
                ['exists',  `tdk:${type}:${query}`],
                ['hmget', `tdk:${type}:${query}`, 'key', 'title', 'keywords', 'description']
            ]).execAsync().then(function(res) {
                if (!res[0]) {
                    return;
                }

                resData.tdkList = [{
                    id: 1,
                    typeName: typeObj.name,
                    typeLt: typeObj.lt,
                    key: res[1][0],
                    title: res[1][1],
                    keywords: res[1][2],
                    description: res[1][3]
                }];
            });
        } else {
            await ctx.redis.multi([
                ['llen', listKey],
                ['lrange', listKey, startId, page * limit]
            ]).execAsync().then(function(res) {
                let total = res[0] || 1;

                resData.pager = pager(Math.floor((total - 1) / limit) + 1, ctx.query);

                _.forEach(res[1], value => {
                    hmget.push(['hmget', `tdk:${type}:${value}`, 'key', 'title', 'keywords', 'description']);
                });
            });

            await ctx.redis.multi(hmget).execAsync().then(function(res) {
                let tdkList = [];

                _.forEach(res, value => {
                    tdkList.push({
                        id: ++startId,
                        typeName: typeObj.name,
                        typeLt: typeObj.lt,
                        key: value[0],
                        title: value[1],
                        keywords: value[2],
                        description: value[3]
                    });
                });

                if (tdkList.length) {
                    resData.tdkList = tdkList;
                }
            });
        }

        await ctx.render('action/seo_tdk', Object.assign(resData, {
            title: 'TDK管理',
            typeList: TYPE_LIST,
            type: typeObj.type,
            typeName: typeObj.name
        }));
    },

    // 添加tdk
    add: async(ctx, next) => {
        let result = {code: 500, message: '非法参数'};

        // skn, article, shop, url
        let type = ctx.request.body.type,
            key = ctx.request.body.key,
            title = ctx.request.body.title || '',
            keywords = ctx.request.body.keywords || '',
            description = ctx.request.body.description || '';


        // type 不合法, 返回错误
        if (!_.find(TYPE_LIST, ['type', type])) {
            return ctx.response.body = result;
        }

        let hashKey = key;

        if (type === 'url') {
            key = _.replace(key, /http[s]?:\/\//, '');
            hashKey = md5(key);
        }

        await ctx.redis.multi([
            ['lpushx', `tdk:${type}:links`, hashKey],
            ['hmset', `tdk:${type}:${hashKey}`, 'key', key, 'title', title, 'keywords', keywords,
                'description', description, 'modify_time', Date.parse(new Date()) / 1000]
        ]).execAsync().then(function(res) {
            if (res[1]) {
                if (!res[0]) {
                    ctx.redis.lpush(`tdk:${type}:links`, hashKey);
                }
                Object.assign(result, {code:200, message: 'success'});
            } else {
                Object.assign(result, {code:400, message: 'failed'});
            }
        });

        ctx.response.body = result;
    },

    edit: async(ctx, next) => {
        let result = {code: 500, message: '非法参数'};

        // skn, article, shop, url
        let type = ctx.request.body.type,
            key = ctx.request.body.key,
            title = ctx.request.body.title || '',
            keywords = ctx.request.body.keywords || '',
            description = ctx.request.body.description || '';

        // type 不合法, 返回错误
        if (!_.find(TYPE_LIST, ['type', type])) {
            return ctx.response.body = result;
        }

        let hashKey = key;

        if (type === 'url') {
            key = _.replace(key, /http[s]?:\/\//, '');
            hashKey = md5(key);
        }

        await ctx.redis.multi([
            ['hmset', `tdk:${type}:${hashKey}`, 'title', title, 'keywords', keywords,
                'description', description, 'modify_time', Date.parse(new Date()) / 1000]
        ]).execAsync().then(function(res) {
            if (res[0]) {
                Object.assign(result, {code:200, message: 'success'});
            } else {
                Object.assign(result, {code:400, message: 'failed'});
            }
        });

        ctx.response.body = result;
    },
    delete: async(ctx, next) => {
        let result = {code: 500, message: '非法参数'};
        let list = ctx.request.body.list;
        let delArr = ['del']
        let multiArr = [];

        // list 不合法, 返回错误
        if (!list || !list.length) {
            return ctx.response.body = result;
        }

        _.forEach(list, value => {
            let hashKey = value.type === 'url' ? md5(value.key) : value.key;

            if (!_.find(TYPE_LIST, ['type', value.type])) {
                return;
            }

            multiArr.push(['lrem', `tdk:${value.type}:links`, 1, hashKey]);

            delArr.push(`tdk:${value.type}:${hashKey}`)
        });

        if (multiArr.length) {
            multiArr.push(delArr);

            await ctx.redis.multi(multiArr).execAsync().then(function(res) {
                Object.assign(result, {code:200, message: 'success'});
            });
        }

        ctx.response.body = result;
    }
};

// 词根
const rootWords = {
    index: async(ctx, next) => {

        let model = new seoModel(ctx);
        let page = ctx.query.page || 1;
        let resData = {};
        let limit = 20;

        resData = await model.rootWordsData(page, limit);
        resData.pager = pager(Math.floor((resData.total[0]['count(id)']/limit)+1), ctx.query);
        await ctx.render('action/seo_root_words', Object.assign(resData, {
            title: '词根管理'
        }));
    },

    add: async(ctx, next) => {
        let model = new seoModel(ctx);
        let resData = {};

        resData = await model.addRootWordsData();

        await ctx.render('action/seo_root_add', Object.assign(resData, {
            title: '添加词根'
        }));

    },

    doAdd: async(ctx, next) => {
        let rootWord = ctx.request.body.rootWord || '',
            brand = ctx.request.body.brand || 0,
            sort = ctx.request.body.sort || 0,
            filterWord = ctx.request.body.filterWord || '',
            isKeyword = ctx.request.body.isKeyword || 0,
            errorMessage = '',
            result,
            model = new seoModel(ctx);


        if (rootWord === '') {
            errorMessage = '词根必填';
        }

        if (sort === 0) {
            errorMessage = '分类必选';
        }

        if (errorMessage !== '') {
            result = {
                code: 201,
                message: errorMessage
            }
            ctx.response.body = result;
            return;
        }

        let sel = await model.queryKeyword(rootWord);

        if (sel.length > 0) {
            ctx.response.body = {code: 201, message: '已存在'};
        } else {
            result = await model.addRootWord(rootWord, brand, sort, filterWord, isKeyword);
            ctx.response.body = result;
        }

    },

    delete: async(ctx, next) => {
        let ids = ctx.request.body.ids || 0,
            model = new seoModel(ctx);
        if (ids === 0) {
            ctx.response.body = {};
        }

        model.delRoorWord(ids);
        ctx.response.body = {};
    },

    rootToKeywords: async(ctx, next) => {
        let ids = ctx.request.body.ids || 0,
            model = new seoModel(ctx);
        if (ids === 0) {
            ctx.response.body = {};
        }

        model.rootToKeywords(ids);
        ctx.response.body = {};
    },

    getSubSorts: async(ctx, next) => {
        let model = new seoModel(ctx);
        let sortId = ctx.request.body.sortId,
            resData;

        resData = await model.getSubSorts(sortId);

        ctx.response.body = resData;
    }
}

r.get('/', tdk.index);
r.get('/tdk', tdk.index);
r.post('/tdk/add', tdk.add);
r.post('/tdk/edit', tdk.edit);
r.post('/tdk/delete', tdk.delete);

// 词根管理
r.get('/rootwords', rootWords.index);
r.get('/rootwords/add', rootWords.add);
r.post('/rootwords/doadd', rootWords.doAdd);
r.post('/rootwords/delete', rootWords.delete);
r.post('/rootwords/getsubsorts', rootWords.getSubSorts);
r.post('/rootwords/rootToKeywords', rootWords.rootToKeywords);


module.exports = r;