This repository has been archived by the owner on May 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathcatalog.js
executable file
·119 lines (101 loc) · 3.88 KB
/
catalog.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import jwt from 'jwt-simple';
import request from 'request';
import ProcessorFactory from '../processor/factory';
function _updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
if (uri.match(re)) {
if (value) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
return uri.replace(re, '$1' + '$2');
}
} else {
var hash = '';
if( uri.indexOf('#') !== -1 ){
hash = uri.replace(/.*#/, '#');
uri = uri.replace(/#.*/, '');
}
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
return uri + separator + key + "=" + value + hash;
}
}
export default ({config, db}) => function (req, res, body) {
let groupId = null
// Request method handling: exit if not GET or POST
// Other metods - like PUT, DELETE etc. should be available only for authorized users or not available at all)
if (!(req.method == 'GET' || req.method == 'POST' || req.method == 'OPTIONS')) {
throw new Error('ERROR: ' + req.method + ' request method is not supported.')
}
let requestBody = {}
if (req.method === 'GET') {
if (req.query.request) { // this is in fact optional
requestBody = JSON.parse(decodeURIComponent(req.query.request))
console.log(requestBody)
}
} else {
requestBody = req.body
}
const urlSegments = req.url.split('/');
let indexName = ''
let entityType = ''
if (urlSegments.length < 2)
throw new Error('No index name given in the URL. Please do use following URL format: /api/catalog/<index_name>/<entity_type>_search')
else {
indexName = urlSegments[1];
if (urlSegments.length > 2)
entityType = urlSegments[2]
if (config.elasticsearch.indices.indexOf(indexName) < 0) {
throw new Error('Invalid / inaccessible index name given in the URL. Please do use following URL format: /api/catalog/<index_name>/_search')
}
if (urlSegments[urlSegments.length - 1].indexOf('_search') !== 0) {
throw new Error('Please do use following URL format: /api/catalog/<index_name>/_search')
}
}
// pass the request to elasticsearch
let url = 'http://' + config.elasticsearch.host + ':' + config.elasticsearch.port + (req.query.request ? _updateQueryStringParameter(req.url, 'request', null) : req.url)
// Check price tiers
if (config.usePriceTiers) {
const userToken = requestBody.groupToken
// Decode token and get group id
if (userToken && userToken.length > 10) {
// if (userToken && userToken.length > 10) {
const decodeToken = jwt.decode(userToken, config.authHashSecret ? config.authHashSecret : config.objHashSecret)
groupId = decodeToken.group_id || groupId
}
delete requestBody.groupToken
}
request({ // do the elasticsearch request
uri: url,
method: req.method,
body: requestBody,
json: true,
auth: {
user: config.elasticsearch.user,
pass: config.elasticsearch.password
},
}, function (_err, _res, _resBody) { // TODO: add caching layer to speed up SSR? How to invalidate products (checksum on the response BEFORE processing it)
if (_resBody && _resBody.hits && _resBody.hits.hits) { // we're signing up all objects returned to the client to be able to validate them when (for example order)
const factory = new ProcessorFactory(config)
let resultProcessor = factory.getAdapter(entityType, indexName)
if (!resultProcessor)
resultProcessor = factory.getAdapter('default', indexName) // get the default processor
if (entityType === 'product') {
resultProcessor.process(_resBody.hits.hits, groupId).then((result) => {
_resBody.hits.hits = result
res.json(_resBody);
}).catch((err) => {
console.error(err)
})
} else {
resultProcessor.process(_resBody.hits.hits).then((result) => {
_resBody.hits.hits = result
res.json(_resBody);
}).catch((err) => {
console.error(err)
})
}
} else {
res.json(_resBody);
}
});
}