Created
February 8, 2019 08:15
-
-
Save mikhailshilkov/57927b178db4696dc66cad81c1112ed0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as aws from "@pulumi/cloud-aws"; | |
// Create a table `urls`, with `name` as primary key. | |
let urlTable = new aws.Table("urls", "name"); | |
// Create a web server. | |
let endpoint = new aws.API("urlshortener"); | |
// Serve all files in the www directory to the root. | |
endpoint.static("/", "www"); | |
// GET /url/{name} redirects to the target URL based on a short-name. | |
endpoint.get("/url/{name}", async (req, res) => { | |
let name = req.params["name"]; | |
let value = await urlTable.get({name}); | |
let url = value && value.url; | |
// If we found an entry, 301 redirect to it; else, 404. | |
if (url) { | |
res.setHeader("Location", url); | |
res.status(301); | |
res.end(""); | |
} | |
else { | |
res.status(404); | |
res.end(""); | |
} | |
}); | |
// POST /url registers a new URL with a given short-name. | |
endpoint.post("/url", async (req, res) => { | |
let url = req.query["url"]; | |
let name = req.query["name"]; | |
await urlTable.insert({ name, url }); | |
res.json({ shortenedURLName: name }); | |
}); | |
export let endpointUrl = endpoint.publish().url; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment