-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler.js
More file actions
84 lines (68 loc) · 1.64 KB
/
handler.js
File metadata and controls
84 lines (68 loc) · 1.64 KB
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
const puppeteer = require('puppeteer-core');
const chromium = require('chrome-aws-lambda');
const FormData = require('form-data');
const fetch = require('node-fetch');
module.exports.render = async ({
type,
id,
url,
variable,
selector,
return_url: returnURL,
secret,
version,
}) => {
const browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: chromium.headless,
});
const page = await browser.newPage();
try {
await page.goto(url, {
waitUntil: 'networkidle0',
});
await page.waitForSelector(selector);
} catch (err) {
throw new Error('page.goto/waitForSelector timed out.');
}
let html;
try {
const handle = await page.evaluateHandle(variable);
html = await handle.jsonValue();
await handle.dispose();
} catch {
const handle = await page.$(selector);
html = await page.evaluate((el) => el.innerHTML, handle);
await handle.dispose();
}
await browser.close();
const body = new FormData();
const data = {
type,
id,
html,
secret,
version,
};
Object.keys(data)
.forEach(key => {
try {
body.append(key, data[key]);
} catch {}
});
const response = await fetch(returnURL, {
method: 'POST',
body,
insecureHTTPParser: true,
});
if (!response.ok) {
throw new Error(response.statusText);
}
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
return response.status;
}
return response.json();
};