recommend.js 2.24 KB
/**
 * 推荐商品(店铺推荐|为您优选|最近浏览)controller
 * @author: wsl<shuiling.wang@yoho.cn>
 * @date: 2016/11/21
 */
'use strict';

const recommend = require('../models/recommend');
const _ = require('lodash');
const md5 = require('md5');
const requestIp = require('request-ip');

const _channel = (channel) => {
    let yhChannel = 1;

    switch (channel) {
        case 'men':
            yhChannel = 1;
            break;
        case 'women':
            yhChannel = 2;
            break;
        case 'lifestyle':
            yhChannel = 4;
            break;
        default:
            break;
    }

    return yhChannel;
};

/**
 * 获取客户端唯一标识
 * @return string
 */
const getUdid = (req, res) => {
    let udid = req.cookies.udid;

    if (!udid) {
        udid = md5(req.ip || requestIp.getClientIp(req));

        if (res && res.cookie) {
            res.cookie('udid', udid);
        }
    }
    return udid;
};

/**
 * 为您优选
 * @param req
 * @param res
 * @param next
 */
const getRecommendProduct = (req, res, next) => {
    let params = {
        yh_channel: _channel(req.query.channel || req.cookies._Channel || 'men'),
        udid: getUdid(req, res)
    };

    if (req.user.uid) {
        params.uid = req.user.uid;
    }

    recommend.getRecommendProduct(params).then((result) => {
        res.json(result);
    }).catch(next);
};

/**
 * 店铺推荐
 * @param req
 * @param res
 * @param next
 */
const getRecommendShop = (req, res, next) => {
    recommend.getRecommendShop(req.query.productSkn).then((result) => {
        res.json(result);
    }).catch(next);
};

/**
 * 最近浏览
 * @param req
 * @param res
 * @param next
 */
const recentPreview = (req, res, next) => {
    let browserSkn = req.cookies._browseskn || '';
    let limit = req.query.limit || 20;
    let skn = _.trim(browserSkn ? decodeURIComponent(browserSkn).replace(/\-(\d)+(\,){0,1}/g, ',') : '', ',');

    if (skn) {
        skn = _.slice(_.uniq(skn.split(',')), 0, limit).join(','); // 去重+截取

        recommend.recentPreview(skn, limit).then(data => {
            res.json(data);
        }).catch(next);
    } else {
        res.json(false);
    }
};

module.exports = {
    getRecommendProduct,
    getRecommendShop,
    recentPreview
};