Start learning free

LESSON 171 OF 173 · BACKEND: YOUR OWN API

Short Links: Count the Clicks in TypeScript

Practice

Whoever shares a short link wants to know how many people opened it. Every visit through the short link is a click, so each link must now remember two things: its URL and its number of clicks.

An object of objects: the value stored under each code becomes a small object of its own, described by an interface, and a dot after the brackets reaches inside it. TypeScript checks every object you store against the interface. For example, with pages instead of links:

interface Page {
  title: string;
  views: number;
}
const pages: { [name: string]: Page } = { home: { title: "Home", views: 0 } };
pages["home"].views += 1;
console.log(pages["home"]);   // { title: 'Home', views: 1 }

The starting code already has the interface Link (url and clicks), and links holds a Link under each code. Count the click in the GET /:code route, after the 404 check and before the redirect. The 404 check starts with return, and nothing after a return runs, so an unknown code never gets that far. Then a new route, GET /links/:code/stats, answers a link's numbers. Looking at the stats is not a click.

After three POST /links made the codes 1, 2 and 3, and the visits GET /1, GET /1 and GET /2 (each still answers 302 to its URL), your app must answer:

GET /links/1/stats  →  200  {"code": "1", "url": "https://www.python.org/downloads/", "clicks": 2}
GET /links/2/stats  →  200  {"code": "2", "url": "https://en.wikipedia.org/wiki/URL_shortening", "clicks": 1}
GET /links/3/stats  →  200  {"code": "3", "url": "https://flask.palletsprojects.com/en/stable/quickstart/", "clicks": 0}
GET /links/4/stats  →  404  {"error": "Link not found"}

Your task: in the POST /links route, store each link as a Link object with its url and its clicks, starting at 0. In the GET /:code route, count the click, then redirect to the link's URL. At the end of the file, add GET /links/:code/stats, with the same 404 for unknown codes.


Assignment
Follow the Coding Tutorial to count the clicks and add the GET /links/:code/stats route.


Hint
links[code] is a Link object now, so the URL is one level deeper, under the key url; tsc reports an error if you redirect to the whole object. Add 1 to the clicks before the redirect.


STEP 1 OF 9
    Ctrl + Enter to check

    Own Links Stats in TypeScript

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free