-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
43 lines (35 loc) · 1.2 KB
/
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
const functions = require('@google-cloud/functions-framework');
const axios = require('axios');
const cheerio = require('cheerio');
functions.http('fetchData', async (req, res) => {
const DATA_DOMAIN = 'ENDPOINT URL FOR DATA COLLECTION GOES HERE';
const { user } = req.query;
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET, POST');
if (req.method === 'OPTIONS') {
res.status(204).send('Invalid request');
return;
}
if (!user) {
res.status(422).send('API Error: Missing params!');
return;
}
if (user) {
try {
const { data: html } = await axios.get(`${DATA_DOMAIN}users/${user}`);
const $ = cheerio.load(html);
const cards = [];
$('#collection .card-collection').each((_, card) => {
const id = $(card).attr('data-cid');
const name = $(card).find('.name').text();
const imgUrl = $(card).find('img').attr('data-src');
cards.push({ id, name, imgUrl });
});
res.json(cards);
} catch (error) {
res.status(500).send(`Failed to retrieve user collection - ${error}`);
}
} else {
res.status(422).send('Invalid query parameter!');
}
});