A new project starts here: a link shortener. It gives each long URL a short code and remembers the pair. Later, whoever opens the code is sent on to the long URL. You will build it over five lessons, starting now.
Codes in base 36: codes count like numbers, 1, 2, 3…, but with 36 characters instead of 10: after 9 come a, b, … z, and only then 10. As in base 10, % 36 gives the last digit, and dividing by 36 and rounding down with Math.floor drops it. For example, 100 = 2 × 36 + 28, and the character for 28 is s, so 100 is written "2s".
Creating with POST: a route that stores something new uses POST, reads the JSON body from req.body and answers 201 Created. req.body has the type any, so give the values you take from it a type yourself. For example, on another route:
app.post("/notes", (req: Request, res: Response) => {
const data = req.body;
const text: string = data.text;
notes.push(text);
res.status(201).json({ text: text });
});
Your app must give these answers, in this order:
POST /links {"url": "https://www.python.org/downloads/"}
→ 201 {"code": "1", "url": "https://www.python.org/downloads/"}
POST /links {"url": "https://en.wikipedia.org/wiki/URL_shortening"}
→ 201 {"code": "2", "url": "https://en.wikipedia.org/wiki/URL_shortening"}
POST /links {"url": "https://flask.palletsprojects.com/en/stable/quickstart/"}
→ 201 {"code": "3", "url": "https://flask.palletsprojects.com/en/stable/quickstart/"}
GET /check/codes (the check calls your makeCode)
→ 1 → "1", 9 → "9", 10 → "a", 35 → "z", 36 → "10", 37 → "11", 1295 → "zz", 1296 → "100"
Your task: the starting code already has DIGITS, the object links and the counter lastNumber. Write makeCode(number: number): string, which turns a number into its base-36 code. Then write POST /links: it gives the URL the next code, stores the pair in links and answers 201 with the code and the URL.
Assignment
Follow the Coding Tutorial to write makeCode and the POST /links route.
Hint
Build the code from the back: each new character goes in front of code. A function typed : string must return the code, or tsc stops with an error. Add 1 to lastNumber before you make the code, and remember res.status(201) before .json(...).
Free plan: 30 tutor messages. PRO is unlimited.
