Express API

Express is a minimal and flexible Node.js web application framework. We will be using it to build our API.

Let's create an endpoint to get an emoji.

Here's the list of what we have to do:

  • DeleteEmoji.ts and Emoji.spec.ts.

  • Install express

  • Create a routers folder to keep our files organised

  • Create a new file/routers/emoji

  • Create a new file app.ts

  • Create a new file index.ts (our main file)

  • Update our config with shared.ts and .env to add port.

  • To simplify imports, addindex.ts exporting all the relevant files to each folder.

We will create the following file structure

.
β”œβ”€β”€ app.ts
β”œβ”€β”€ index.ts
└── routers
 Β Β  β”œβ”€β”€ Emoji
    |   β”œβ”€β”€ index.spec.ts
    |   └── index.ts
    └── index.ts

To keep things clean, each top-level endpoint will have a router. The router defines the GET, POST, PUT and DELETE.

We can test any method by mocking request and response using jest.fn().mockReturnValue().

When types don't match, we use as unknown first to force TypeScript to accept the other type. This is useful when we are mocking params.

We need a way to bootstrap our app (set containers, connect to the database, ...) and create an express app.

Our main file requires it and starts the server:

Note: sharedConfig and .env needs to be updated to add port.

express branch available on GitHub.

Last updated

Was this helpful?