Skip to content

Instantly share code, notes, and snippets.

@yusukebe

yusukebe/swr.js Secret

Created June 29, 2021 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yusukebe/8f367414afa20000b9652b02d2d06182 to your computer and use it in GitHub Desktop.
Save yusukebe/8f367414afa20000b9652b02d2d06182 to your computer and use it in GitHub Desktop.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
let count = 1;
const server = http.createServer((req, res) => {
if (req.url != '/') {
return;
}
console.log(count + '番目のアクセスが来ました。ページ生成に10秒かかります...');
setTimeout(() => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Cache-Control', 'max-age=5, stale-while-revalidate=3600');
const hash = Math.random().toString(26).slice(-4);
const date = new Date();
const message = `${count}番目のページです...
${date.toISOString()}
ページ: ${hash}`;
console.log(count + '番目のページ ' + hash + ' の生成が終わりました。これを返します。');
count++;
res.end(message);
setTimeout(() => {
console.log(`${hash} を返して5秒経ちました。キャッシュが切れました。
次回アクセスでは、古いキャッシュを返しつつ、新しいキャッシュを生成します。`);
}, 5000);
}, 10000);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment