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": {
"compression": "^1.7.1",
"modern-normalize": "^1.0.0",
"node-fetch": "^2.6.1",
"polka": "next",
"sirv": "^1.0.0"
},

View File

@ -1,15 +1,45 @@
import sirv from 'sirv';
import polka from 'polka';
import fetch from 'node-fetch';
import compression from 'compression';
import * as sapper from '@sapper/server';
const { PORT, NODE_ENV } = process.env;
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
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
links,
sapper.middleware()
)
.listen(PORT, err => {

View File

@ -1984,6 +1984,11 @@ no-case@^2.2.0:
dependencies:
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:
version "7.1.2"
resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-7.1.2.tgz#21a810aebb187120251c3bcec979af1587b188ae"