-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuggestions_index.js
71 lines (59 loc) · 1.52 KB
/
suggestions_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
68
69
70
71
'use strict';
const _ = require('lodash');
const request = require('request-promise');
const indexName = 'crateful-suggestions';
const stripPatterns = [
'\\.|,|\\*', // punctuation
'\\(.*\\)', // anything in brackets
'1.*per outlet', // 1 kit/deal per outlet, 1 per outlet
];
const stripRegex = new RegExp(stripPatterns.join('|'), 'gm');
const cleanProductName = function(name) {
return name
.replace(stripRegex, '')
.replace(/\s$/, '');
};
class SuggestionsIndex {
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: ['query'],
facets: []
},
json: true
});
}
indexProductBatch(products) {
const requests = products.map(product => {
return {action: 'create', body: {query: cleanProductName(product.name)}};
});
return request.post({
uri: `${this._apiBaseUrl}/batch`,
headers: this._apiHeaders,
body: {requests},
json: true
});
}
}
module.exports = SuggestionsIndex;