-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducts_index.js
67 lines (56 loc) · 1.53 KB
/
products_index.js
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
'use strict';
const _ = require('lodash');
const request = require('request-promise');
const indexName = 'crateful-products';
const buildCategoryHierachy = code => {
if (!code) {
return [];
}
const levels = code.split('.');
return levels.map((level, index) => levels.slice(0, index + 1).join('.'));
};
class ProductsIndex {
constructor(apiBaseUrl, apiToken) {
this._apiBaseUrl = `${apiBaseUrl}/indexes/${indexName}`;
this._apiHeaders = {
'content-type': 'application/json',
authorization: `bearer ${apiToken}`
};
}
delete() {
return request.del({
url: this._apiBaseUrl,
headers: this._apiHeaders
})
.then(() => {}, err => {
if (err.statusCode === 404 && err.message.indexOf(indexName) >= 0) {
return;
}
throw err;
});
}
create() {
return request.put({
uri: `${this._apiBaseUrl}/settings`,
headers: this._apiHeaders,
body: {
searchable_fields: ['name', 'category_desc', 'brand'],
facets: [{field: 'supplier', order: 'value'}, {field: 'category_code', order: 'countDESC'}, {field: 'brand', order: 'value'}]
},
json: true
});
}
indexProductBatch(indexingRequests) {
const requests = indexingRequests.map(r => {
r.body.category_hierarchy = buildCategoryHierachy(r.body.category_code);
return r;
});
return request.post({
uri: `${this._apiBaseUrl}/batch`,
headers: this._apiHeaders,
body: {requests},
json: true
});
}
}
module.exports = ProductsIndex;