-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssr.js
31 lines (26 loc) · 946 Bytes
/
ssr.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
const puppeteer = require('puppeteer');
const TIMEOUT_DURATION_HOURS = 24 * 30;
const TIMEOUT_DURATION_SECONDS = 30;
const REQUEST_CACHE = {};
async function ssr(url, force = false) {
const now = +new Date();
if (REQUEST_CACHE[url] && force === false) {
const diffInHrs = (now - REQUEST_CACHE[url]['ttl']) / (1000 * 3600);
if (diffInHrs < TIMEOUT_DURATION_HOURS) {
return REQUEST_CACHE[url]['html'];
}
};
try {
const browser = await puppeteer.launch({ args: ['--no-sandbox'] });
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle0' })
const html = await page.content(); // serialized HTML of page DOM.
await browser.close();
REQUEST_CACHE[url] = { ttl: now, html };
return html;
} catch (error) {
console.log('Error', error);
throw new Error(error);
}
}
module.exports = ssr;