search-api.js
3.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
* Created by TaoHuang on 2016/6/14.
*/
const Fn = require('lodash/fp');
const md5 = require('md5');
const config = global.yoho.config;
const cache = global.yoho.cache;
const logger = global.yoho.logger;
// 缓存生效时间
const CACHE_TIME_S = 60;
const getSearchCacheKey = params => {
let removeUnusedKey = Fn.omit(['page', 'limit', 'need_filter', 'order']);
let sortByKey = Fn.pipe(Fn.toPairs, Fn.sortBy(0), Fn.flatten);
let genKey = Fn.pipe(Fn.cloneDeep, removeUnusedKey, sortByKey, Fn.join('_'));
return 'search_custom_' + md5(genKey(params));
};
const saveCache = (key, kv, cacheTime) => {
cache.set(key, kv, cacheTime)
.catch(err => logger.debug(`product query save cache data fail:${err.toString()}`));
};
module.exports = class extends global.yoho.BaseModel {
constructor(ctx) {
super(ctx);
}
getProductListOrig(finalParams) {
return this.get({data: finalParams});
}
/**
* 获取商品列表
* @return
*/
getProductList(params, from) {
let finalParams = {
method: 'web.search.search',
sales: 'Y',
outlets: 2,
stocknumber: 1,
need_filter: 'yes',
limit: 60
};
Object.assign(finalParams, params);
// 店铺默认排序s_w_desc
if (params.shopId || params.shop_id || params.shop) {
finalParams.order = params.order || 's_w_desc';
}
if (from) {
finalParams.from = from;
}
if (!config.useCache) {
return this.getProductListOrig(finalParams);
} else {
let cKey = getSearchCacheKey(finalParams);
return cache.get(cKey)
.catch(err => logger.debug(`product query save cache data fail:${err.toString()}`))
.then(cdata => {
let hasCache = false;
if (cdata) {
try {
cdata = JSON.parse(cdata);
} catch (e) {
logger.debug('getProductList cache data parse fail.');
}
if (cdata.filter && cdata.standard) {
hasCache = true;
finalParams.need_filter = 'no';
}
}
return this.getProductListOrig(finalParams).then(result => {
if (hasCache && result && result.data) {
Object.assign(result.data, cdata);
} else {
if (result && result.data && result.data.filter) {
saveCache(cKey, Object.assign({}, {
filter: result.data.filter,
standard: result.data.standard
}), CACHE_TIME_S);
}
}
return result;
});
});
}
}
};