From bb3d9b9c25cdf0915b1d10c670d71815e31b3486 Mon Sep 17 00:00:00 2001 From: Damillora Date: Mon, 25 Jan 2021 01:39:46 +0700 Subject: [PATCH] Serve short URLs --- package.json | 1 + src/server.js | 30 ++++++++++++++++++++++++++++++ yarn.lock | 5 +++++ 3 files changed, 36 insertions(+) diff --git a/package.json b/package.json index 80c240c..d10ddbb 100644 --- a/package.json +++ b/package.json @@ -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" }, diff --git a/src/server.js b/src/server.js index c77f593..3af53d1 100644 --- a/src/server.js +++ b/src/server.js @@ -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 => { diff --git a/yarn.lock b/yarn.lock index d0c55e1..5ff93b6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -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"