-
Notifications
You must be signed in to change notification settings - Fork 0
/
amazon-function.js
238 lines (234 loc) · 7.04 KB
/
amazon-function.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
const fli = require('fli-webtask');
const express = require('express');
const wt = require('webtask-tools');
const bodyParser = require('body-parser');
const request = fli.npm.request;
const as = fli.npm.async;
const _ = fli.npm.lodash;
const loader = fli.lib.loader;
const responseHandler = fli.lib.responseHandler;
const operationHelper = require('apac').OperationHelper;
const Paapi = require('amazon-pa-api50');
const PaapiConfig = require('amazon-pa-api50/lib/config');
const PaapiOptions = require('amazon-pa-api50/lib/options');
const app = express();
const router = express.Router();
const routerPaapi = express.Router();
const validateMiddleware = (req, res, next) => {
if(req.webtaskContext.secrets.token !== req.query.token) {
const errMsgToken = 'No token.';
responseHandler(errMsgToken, res);
return next(errMsgToken);
}
const market = _.get(req, 'params.market');
if(!market) {
const errMsgMarket = 'No market name provided.';
responseHandler(errMsgMarket, res);
return next(errMsgMarket);
}
req.market = _.upperCase(market);
return next();
};
const apacMiddleware = (req, res, next) => {
req.oph = new operationHelper({
awsId: req.webtaskContext.secrets.awsId,
awsSecret: req.webtaskContext.secrets.awsSecret,
assocId: req.webtaskContext.secrets.assocId,
locale: req.market
});
next();
};
const paapiMiddleware = (req, res, next) => {
let resourceList = null;
let countryName = {
'US': 'UnitedStates',
'DE': 'Germany',
'UK': 'UnitedKingdom'
}[req.market];
let country = _.get(PaapiOptions.Country, countryName);
if(!country) {
const errMsgCountry = 'Country not supported or empty.';
responseHandler(errMsgCountry, res);
return next(errMsgCountry);
}
let paapiConfig = new PaapiConfig(resourceList, country);
paapiConfig.accessKey = req.webtaskContext.secrets.awsId;
paapiConfig.secretKey = req.webtaskContext.secrets.awsSecret;
paapiConfig.partnerTag = req.webtaskContext.secrets.assocId;
req.paapi = new Paapi(paapiConfig);
return next();
};
const jsonMapper = (asin) => (info, next) => {
var item = _.get(info, 'result.ItemLookupResponse.Items.Item');
if(!item || item.ASIN !== asin) {
return next(null, {});
}
var title = _.get(item, 'ItemAttributes.Title');
var content = _.get(item, 'EditorialReviews.EditorialReview.Content') ||
_.chain(item).get('ItemAttributes.Feature', '').concat([]).join('; ').value();
var image = _.get(item, 'LargeImage.URL') ||
_.get(item, 'MediumImage.URL');
var price = _.get(item, 'ItemAttributes.ListPrice.FormattedPrice') ||
_.get(item, 'OfferSummary.LowestNewPrice.FormattedPrice');
var labels = [];
(function fetchNodeName(node) {
if(_.isArray(node)) {
return _.map(node, (n) => fetchNodeName(n));
}
var nodeName = _.get(node, 'Name');
var nodeAncestor = _.get(node, 'Ancestors.BrowseNode');
if(nodeName) {
labels.push(nodeName);
}
if(nodeAncestor) {
fetchNodeName(nodeAncestor);
}
})(_.get(item, 'BrowseNodes.BrowseNode'));
if(!title || !content || !image || !price) {
return next('No content.');
}
return next(null, {
title: title,
content: content,
image: image,
price: price,
labels: _.uniq(labels)
});
};
router
.get('/lookup/:asin', function (req, res) {
const asin = _.get(req, 'params.asin');
if(!asin) {
return responseHandler('No asin provided.', res);
}
as.parallel([
(next) => {
const enpoint = req.webtaskContext.secrets[req.market];
if(!enpoint) {
return next('No market endpoint');
}
return loader({
method: 'post',
url: req.webtaskContext.secrets.scrapeItFunction,
qs: {
token: req.webtaskContext.secrets.token
},
json: {
"endpoint": {
"url": `${enpoint}/dp/${asin}`,
"headers": { "User-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" }
},
"config": {
"keywords": {
"selector": "meta[name='keywords']",
"attr": "content"
}
}
}
}, next);
},
(next) => {
req.oph.execute('ItemLookup', {
'ItemId': asin,
'ResponseGroup': 'Large'
})
.then((info) => jsonMapper(asin)(info, next))
.catch((err) => next(err));
}
],
(err, result) => {
const keywords = _.get(result, '[0].keywords', '');
const info = _.get(result, '[1]', {});
const labels = _.get(req.webtaskContext.secrets, `${req.market}-labels`, `BestDeal,AmazingDeal`).split(',');
info.labels = _.concat(
_.get(info, 'labels', labels),
_.chain(keywords).split(',').compact().map(_.trim).value()
);
responseHandler(null, res, info);
});
})
.get('/browsenodelookup/:node', function (req, res) {
as.waterfall([
(next) => {
var node = _.get(req, 'params.node');
if(!node) {
return next('No node provided.');
}
req.oph.execute('BrowseNodeLookup', {
'BrowseNodeId': node,
'ResponseGroup': 'BrowseNodeInfo'
})
.then((info) => {
next(null, {
info: info
});
})
.catch((err) => next(err));
}
],
(err, info) => responseHandler(err, res, info));
})
.get('/minify', function (req, res) {
as.waterfall([
(next) => {
if(!req.query.url) {
return next('No url provided.');
}
return fli.npm.request({
auth: {
bearer: req.webtaskContext.secrets.minifyToken
},
url: req.webtaskContext.secrets.minifyFunction,
method: 'post',
json: {
long_url: req.query.url
}
}, (err, shortRes, shortBody) => next(null, shortBody));
},
(shortBody, next) => {
let shortUrl = _.get(shortBody, 'link', '');
let longUrl = _.get(shortBody, 'long_url', '');
return next(null, {
isOk: !!shortUrl,
longUrl: longUrl,
shortUrl: shortUrl
});
}
],
(err, info) => responseHandler(err, res, info));
});
routerPaapi
.post('/v5/:method', async function (req, res) {
/** https://github.com/arifulhb/amazon-pa-api50#usage
* https://webservices.amazon.com/paapi5/documentation/operations.html
* Methods: getItems, getBrowseNodes, getVariations, searchItems
**/
let error, data;
let requestConfig = _.merge(
{
PartnerTag: req.paapi.props.partnerTag,
PartnerType: req.paapi.props.partnerType
},
_.get(req, 'body', {})
);
try {
/* global Promise */
data = await new Promise((resolve, reject) => {
req.paapi._api[req.params.method](requestConfig, (e, d) => {
if(!!e) {
return reject(e);
}
return resolve(d);
});
});
} catch(e) {
error = { error: _.toString(e) };
} finally {
responseHandler(error, res, data);
}
});
app
.use(bodyParser.json())
.use('/:market', validateMiddleware, apacMiddleware, router)
.use('/:market/paapi', validateMiddleware, paapiMiddleware, routerPaapi);
module.exports = wt.fromExpress(app);