seoModel.js 5.7 KB
'use strict';

const _ = require('lodash');
const seoHelper = require('../utils/seoHelper');
const model = require('../../../lib/model');
const mysqlPromise = require('../../../lib/mysql-promise');
const config = require('../../../config/config');
const singleBrandKeyPre = config.singleBrandKeyPre;
const singleSortKeyPre = config.singleSortKeyPre;
const brandUrl = `${config.domains.search}brand/list.json`;
const sortUrl = `${config.domains.search}sortgroup.json`;

class seoModel extends model {

    constructor(ctx) {
        super(ctx);
        this.mysql = new mysqlPromise();
    }

    /**
     * 获取所有品牌(redis || api)
     */
    getBrands() {
        let brandsRedisKey = 'global:yoho:brands';

        // 先取redis
        return this.ctx.redis.getAsync(brandsRedisKey).then(brands => {
            if (!brands) {

                // 调用接口
                return this.get(brandUrl).then(res => {
                    if (res) {
                        this.ctx.redis.setAsync(brandsRedisKey, JSON.stringify(res));
                        brands = res;
                        this.storeBrands(res);
                    }
                    return brands;
                })
            } else {
                return JSON.parse(brands);
            }

        }).catch(()=>{
            return {};
        });
    }

    /**
     * 根据品牌id存储品牌名称到redis
     */
    storeBrands(brands) {

        let operation = [];

        _.forEach(_.get(brands, 'data'), val => {
            operation.push(['set', `${singleBrandKeyPre}${val.id}`, val.brand_name]);
        });

        this.ctx.redis.multi(operation).execAsync();
    }

    /**
     * 根据品类id存储品牌名称到redis
     */
    storeSorts(sort) {
        let operation = [];

        _.forEach(_.get(sort, 'data.sort'), (msort) => {
            operation.push(['set', `${singleSortKeyPre}${msort.sort_id}`, msort.sort_name]);
            _.forEach(_.get(msort, 'sub'), (misort) => {
                operation.push(['set', `${singleSortKeyPre}${misort.sort_id}`, misort.sort_name]);
                _.forEach(_.get(misort, 'sub'), (sort) => {
                    operation.push(['set', `${singleSortKeyPre}${sort.sort_id}`, sort.sort_name]);
                })
            })
        })

        this.ctx.redis.multi(operation).execAsync();
    }

    /**
     * 获取所有分类 (redis || api)
     */
    getSort() {
        let sortsRedisKey = 'global:yoho:sorts';

        // 先取redis
        return this.ctx.redis.getAsync(sortsRedisKey).then(sorts => {
            if (!sorts) {

                // 调用接口
                return this.get(sortUrl,{needAllSort:1, needSmallSort: 1}).then(res => {
                    if (res) {
                        this.ctx.redis.setAsync(sortsRedisKey, JSON.stringify(res));
                        sorts = res;
                        this.storeSorts(sorts);
                    }
                    return sorts;
                })
            } else {
                return JSON.parse(sorts);
            }

        }).catch(()=>{
            return {};
        });
    }

    /**
     * 添加词根数据
     */
    addRootWordsData() {
        return Promise.all([this.getBrands(), this.getSort()]).then(result => {
            return {brand: seoHelper.sortBrands(result[0]), sort: seoHelper.getSubSorts(result[1])};
        })
    }

    /**
     * 词根列表数据
     */
    rootWordsData(page, limit) {
        let sql = `select * from seo_keywords_root where status=1 order by id desc limit ${(page-1)*limit}, ${limit};`,
            countSql = `select count(id) from seo_keywords_root where status=1;`;

        return Promise.all([this.mysql.query(countSql), this.mysql.query(sql)]).then(res => {
            let list = _.get(res, '1'),
                operate = [];

            _.forEach(list, val => {
                operate.push(['get', `${singleBrandKeyPre}${val.brands_id}`]);
                operate.push(['get', `${singleSortKeyPre}${val.sort_id}`]);
            })

            return this.ctx.redis.multi(operate).execAsync().then(result => {

                _.forEach(list, (val, key) => {
                    list[key].brand_name = result[2*key];
                    list[key].sort_name = result[2*key+1];
                })
                return {total: res[0], list: list};
            });

        });
    }

    /**
     * 获取子分类
     */
    getSubSorts(sortId) {

        return this.getSort().then(sorts => {
            return seoHelper.getSubSorts(sorts, sortId);
        });
    }

/**
 * 查看词根是否存在
 */
queryKeyword(keyword) {
    return this.mysql.query(`select * from seo_keywords_root where keyword = '${keyword}' and status = 1 limit 1`).then(res => {
       return res;
    });
}

    /**
     * 添加词根
     */
    addRootWord(rootWord, brand, sort, filterWord, isKeyword) {
        let result = {};
        let sql = `insert into seo_keywords_root (keyword, brands_id, sort_id, filter_words, is_expand, is_keyword, add_time, status) values
        ('${rootWord}', ${brand}, ${sort}, '${filterWord}', 0, ${isKeyword}, ${Math.floor(new Date().getTime()/1000)}, 1)`;

        return this.mysql.query(sql).then(res => {
            return result = {code:200};
        }).catch(err=>{
            return result = {code:201, message: '插入失败'};
        })
    }

    /**
     * 删除词根
     */
    delRoorWord(ids) {
        let sql = `update seo_keywords_root set status=0 where id in (${ids});`;

        return this.mysql.query(sql);
    }

    /**
     * 词根设为关键词
     */
    rootToKeywords(ids) {
        let sql = `update seo_keywords_root set is_keyword=1 where id in (${ids});`;

        return this.mysql.query(sql);
    }
}



module.exports = seoModel;