Serve short URLs

This commit is contained in:
Damillora 2021-01-25 01:39:46 +07:00
parent 9c03ba9f54
commit bb3d9b9c25
3 changed files with 36 additions and 0 deletions

View File

@ -11,6 +11,7 @@
"dependencies": { "dependencies": {
"compression": "^1.7.1", "compression": "^1.7.1",
"modern-normalize": "^1.0.0", "modern-normalize": "^1.0.0",
"node-fetch": "^2.6.1",
"polka": "next", "polka": "next",
"sirv": "^1.0.0" "sirv": "^1.0.0"
}, },

View File

@ -1,15 +1,45 @@
import sirv from 'sirv'; import sirv from 'sirv';
import polka from 'polka'; import polka from 'polka';
import fetch from 'node-fetch';
import compression from 'compression'; import compression from 'compression';
import * as sapper from '@sapper/server'; import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env; const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development'; const dev = NODE_ENV === 'development';
const shortenerBase = process.env.SHORTENER_BASE || 'https://link.nanao.moe';
var linksCache = {}
const links = async function(req, res, next) {
if(linksCache[req.path]) {
if(linksCache[req.path] == 'none') {
next();
} else {
res.writeHead(301, { Location: linksCache[req.path] });
res.end();
}
return;
}
fetch(shortenerBase+req.path, {
redirect: 'manual',
}).then(function(fetchres){
var unshortenedUrl = fetchres.headers.get('Location');
if(unshortenedUrl == shortenerBase+"/") {
linksCache[req.path] = "none";
next()
} else {
res.writeHead(301, { Location: unshortenedUrl });
res.end();
}
})
}
polka() // You can also use Express polka() // You can also use Express
.use( .use(
compression({ threshold: 0 }), compression({ threshold: 0 }),
sirv('static', { dev }), sirv('static', { dev }),
links,
sapper.middleware() sapper.middleware()
) )
.listen(PORT, err => { .listen(PORT, err => {

View File

@ -1984,6 +1984,11 @@ no-case@^2.2.0:
dependencies: dependencies:
lower-case "^1.1.1" lower-case "^1.1.1"
node-fetch@^2.6.1:
version "2.6.1"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.1.tgz#045bd323631f76ed2e2b55573394416b639a0052"
integrity sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==
node-gyp@^7.1.0: node-gyp@^7.1.0:
version "7.1.2" version "7.1.2"
resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-7.1.2.tgz#21a810aebb187120251c3bcec979af1587b188ae" resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-7.1.2.tgz#21a810aebb187120251c3bcec979af1587b188ae"