NOTES

Objective

Use Nodejs runtime, Typescript, ExpressJs, Typeorm, PostgreSQL, Beekeeper and Bruno to create an api from scratch. Create a Task and Todo Manager.

Module 1: Foundations & TypeScript

Project Initialization & Tooling

  • Initialize nodejs project environment
    • npm init -y
  • Install and configure Typescript
    • npm install -D typescript @types/node tsx
  • Initialize typescript configuration
    • npx tsc --init

TypeScript Fundamentals for Backend

  • types: string, boolean, number, any

  • variables

const username = "doeman"; let isActive = false; let age = 25; const numberOfPoints = [2, 3, 4, 5]; const profile = { name: "John Doe", isEngineer: true, }; let profileColor: "red" | "green" | "blue" = "blue"; 
  • conditions
let color: "red" | "green" | "blue" = "blue"; if (color === "red") { console.log("This is red"); } else if (color === "green") { console.log("This is green"); } else { // this means the default (color console.log("This is green"); } switch (color) { case "red": { console.log("This is red"); break; } case "green": { console.log("This is green"); break; } case "blue": { console.log("This is blue"); break; } default: { // this means that color is not found console.log("It seems we don't know what this color is"); break; } } 
  • operations: +,-, /, *, <, >, <=, >=, === ==, !=

  • interfaces and type aliasing
    We use interface to define payloads, type request and response bodies. We call these DTO - Data Transfer Object

interface UserInput { firstName: string; lastName: string; age: number; address?: { addressLineOne: string; addressLineTwo?: string; countryCode?: string; }; } type Colors = "red" | "green" | "blue"; 
  • loops and condition
for (const i in [1, 2, 3]) { console.log(`do something with element at index i, ${arr[i]}`); } for (const i of [1, 2, 3]) { console.log(`${i} is an item in arr`); } // square and filter out the even numbers [1, 2, 3].map((i) => i * i).filter((i) => i % 2 === 0); 
  • functions and promises (async and await)
function name(params) {} // call function name(1, 2); function addTwoNumbers(a: number, b: number) { return a + b; } console.log(`The sum of 1 and 2 is ${addTwoNumbers(1, 2)}`); async function addThreeNumbers(a: number, b: number, c: number) { // usually we will put await return a + b + c; } 
  • classes
class MyClass { properties; methods; private name: string; constructor(name: string) { this.name = string; } constructor(public readonly name: string) {} doubleName(): string { const fullname = this.name + " " + this.name; console.log(fullname); return fullname; } } 
  • all properties and methods are by default public
  • public: accessible anywhere
  • private: not accessible outside of the class
  • protected: it is private but accessible to sub-classes
  • readonly: prevents the fields from reassignment after initialized

Module 2: HTTP Architecture & Express

The Express Server & Request Lifecycle

Install express for the http server.

npm install express npm install -D @types/express 

In src/index.ts, we bootstrap an express application and add a health-check endpoint

import express, { Request, Response, NextFunction } from "express"; const app = express(); app.use(express.json()); app.get("/health", (req: Request, res: Response, next: NextFunction) => { try { res.status(200).json({ status: "ok", timestamp: new Date() }); } catch (error) { return next(error); } }); 

Break down

  • Import express and types needed: import express, { Request, Response, NextFunction } from "express";
  • Create an express app, const app = express();
  • Add a builtin middleware to parse json-payload to JSON: app.use(express.json());
  • Create a GET request, app.get(...)
  • With an endpoint. app.get("/health",...)
  • After this we have a request handler that return a JSON object with properties, status and timestamp
  • req is how data (input) is passed into the controller (request handler)
  • res is how data is passed back (returned) to the client
  • next passes control to the next request handler.
  • When next() is empty, it means everything is fine, move to the middleware (request-handler)
  • When next(error) is not empty, it means there was an error and as such control needs to be passed to the error handling middleware

Update the tsconfig

{ "compilerOptions": { "lib": ["ES2016"], "module": "commonjs", "target": "es2016", "rootDir": "./src", "outDir": "./dist", "emitDecoratorMetadata": true, "experimentalDecorators": true, "sourceMap": true, "strictPropertyInitialization": false, "typeRoots": ["./node_modules/@types"], "types": ["node"] } } 

Update the package.json

{ ..., "scripts": { "build": "npx tsc", "clean": "rm -rf dist", "start": "npm run build && node ./dist/index.js" }, } 

We can now run the command npm run start

Add and listen on a port

Lets add a static port and run this app on port 3000.

app.listen(3000, () => { console.log("app is running on port 3000"); }); 

Request and Response

Say we have req: Request, we can get the user input passed via

  • body as req.body. If there is a specific field we are interested in, we can access it directly as req.body.field
  • headers as req.headers
  • query strings as req.query
  • params as req.params

When returning a response, we can update the status code and return a JSON object by res.status(STATUS_CODE).json({ ...})

Controllers

A controller is a request handler. Requests and responses are handled in the controller. From above, this is a controller.

(req: Request, res: Response, next: NextFunction) => { try { res.status(200).json({ status: "ok", timestamp: new Date() }); } catch (error) { return next(error); } }; 

A controller is a function (usually async). In this case we have to create a function for this controller.

Directly we can do:

const healthController = (req: Request, res: Response, next: NextFunction) => { try { res.status(200).json({ status: "ok", timestamp: new Date() }); } catch (error) { return next(error); } }; 

I prefer creating or using the function keyword stylistically.

function healthController(req: Request, res: Response, next: NextFunction) { try { res.status(200).json({ status: "ok", timestamp: new Date() }); } catch (error) { return next(error); } } 

The difference between the two functions looks like

const funcName = (params) => { // actions }; 

and

function funcName(params) { // actions } 

Now the health route will look like

function healthController(req: Request, res: Response, next: NextFunction) { try { res.status(200).json({ status: "ok", timestamp: new Date() }); } catch (error) { return next(error); } } app.get("/health", healthController); 

NB: usually controllers are async

Route Grouping

Another way to create a route is to use the Router function from express. This way we can have a router for each feature of our app and then mount it in the main app (index.ts).

// feature-name/index.ts // or feature-name/router.ts import { Router } from "express"; const router = Router(); // here you can add middlewares and routes and mount controllers export default router; 

I usually prefer the /index.ts approach.

We can now import this grouped router in the main app.

// other imports import tasksRouter from "./tasks"; 

then we mount the new router under the app.get("/health", healthController);

app.use("/tasks", tasksRouter); 

Module 3: Database, Docker & TypeORM

Install Docker and Create a database

An easy way to set up a postgres database is via docker. Follow the instruction here to install docker. To make management rather straight forward, install docker desktop - choose your OS.

docker run --name taskflow-postgres \ -e POSTGRES_USER=postgres \ -e POSTGRES_PASSWORD=secret \ -e POSTGRES_DB=taskflow_db \ -p 5432:5432 -d postgres:18-alpine 

postgres:18-alpine means we are installing version 18 but you can choose any version you want

You should see something similar to

Unable to find image 'postgres:18-alpine' locally 18-alpine: Pulling from library/postgres b90627b8f429: Pull complete 4dabfc2d1ead: Pull complete 1636401909fe: Pull complete 8d8e256c4dbb: Pull complete 8a9967ff79bf: Pull complete fed66866fab0: Pull complete bd55ea5c71cd: Pull complete 284a2c96f7d3: Pull complete 85f0bdc54780: Pull complete Digest: sha256:9ba53c7d41ea093baf5c1ba635ba5434c4f979880527d49bb7d9237d3193085b Status: Downloaded newer image for postgres:18-alpine e21be0ef6a68a58acb48e42140c093d312c8b5d5874f909e3cc6f6b83d960e5f 

We can download Beekeeper studio. There is a community version as well.

We can connect to see the new (default) database created above using postgresql://postgres:secret@localhost:5432/taskflow_db where here you replace the username, secret and database. The data URL is the same as postgresql://username:secret@localhost:5432/database-name.

Beekeeper has Import from URL. Click on it and paste the data URL.

NB: From here, you can create as many new databases as you wish and all will fall under the same database user and secret.

Configure TypeORM

We will use TypeORM to connect to the newly created database. We will create entities (tables) and run migrations.

NB: Migrations is a way to tell the database the changes it should make to the tables (either create new ones, update fields, etc)

Read on typeorm and postgres set up

Install typeorm and its needed dependencies

npm install typeorm reflect-metadata pg 

From the docs, we must update the tsconfig.json file with these in the compilerOptions

"emitDecoratorMetadata": true, "experimentalDecorators": true 

Initialize a typeorm

The doc says we can do npx typeorm init --name MyProject --database postgres. That works but for this project we want the project name to be database

Basically, we want the entity, migration and data-source.ts inside a folder called database.

Since this is a project we have already started, not specifying --name puts in the entity, migration and data-source.ts src folder. We have to rearrange them.

Update tsconfig.json to add or update "strictPropertyInitialization": false,

The new tsconfig.json file must or should look like or you should update it to:

{ "compilerOptions": { "lib": ["es2021"], "target": "es2021", "module": "commonjs", "rootDir": "./src", "outDir": "./dist", "emitDecoratorMetadata": true, "experimentalDecorators": true, "sourceMap": true, "strictPropertyInitialization": false } } 

Run, npm run build to check if anything is broken

src |-entity | |-User.ts |-migration | |-data-source.ts 

User.ts has

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() firstName: string; @Column() lastName: string; @Column() age: number; } 

and data-source.ts has

import "reflect-metadata"; import { DataSource } from "typeorm"; import { User } from "./entity/User"; export const AppDataSource = new DataSource({ type: "postgres", host: "localhost", port: 5432, username: "test", password: "test", database: "test", synchronize: true, logging: false, entities: [User], migrations: [], subscribers: [], }); 

Configuring TypeORM from scratch

  • First you'd need to create the data-source.ts inside database folder.
import "reflect-metadata"; import { DataSource } from "typeorm"; export const AppDataSource = new DataSource({ type: "postgres", host: "localhost", port: 5432, username: "test", password: "test", database: "test", synchronize: true, logging: false, entities: [], migrations: [], subscribers: [], }); 
  • Then create the folder for the entities and migrations

NB: I prefer to have index.ts to export all entities and data-source so the an entity import would look like ./database instead of ./database/entity/EntityName.ts

Environmental variable

Environmental variable is one way to pass data into your app so that you don't have to statically put your apis/service credentials into your app.

For this, we create a .env file in the root of the project and pass all the values we want to pass into our api but must be hidden for security reasons.

We can add host, username, password, port and database to the .env file.

# Database config DATABASE_HOST=localhost DATABASE_USERNAME=postgres DATABASE_PASSWORD=secret DATABASE_PORT=5432 DATABASE_NAME=taskflow_db 

Previously we set our application's port directly into the main app. We can add it here

# application config APP_PORT=3000 

Now we have to read these constants into our code base and use it.

We can use process.env.CONSTANT_NAME directly however it is recommended that your group them in one place.

In the root of the src folder we can create another folder, core and then create index.ts and another env-constants.ts

In env-constants we create an object

export const envConstants = { // Database config DATABASE_HOST: process.env.DATABASE_HOST ?? "", DATABASE_USERNAME: process.env.DATABASE_USERNAME ?? "", DATABASE_PASSWORD: process.env.DATABASE_PASSWORD ?? "", DATABASE_PORT: Number(process.env.DATABASE_PORT ?? 5432), DATABASE_NAME: process.env.DATABASE_NAME ?? "", // application config APP_PORT: Number(process.env.APP_PORT ?? 3000), }; 

We can create a function to check if a value is set as a wrapper around any of the fields, this way we can throw an error when any of the critical fields aren't set.

Install dotenv.

Now we can add import 'dotenv/config' at the top of env-constants.

We will be needing status codes to work with. We will add it to src/core/app-constants.ts

// app-constants.ts export const appConstants = { STATUS_CODES: { SUCCESS: 200, CREATED: 201, BAD_REQUEST: 400, VALIDATION_ERROR: 422, }, }; 

export * from "./env-constants" and export * from "./app-constants"; in the index.ts

Refactor Datasource and Main app

We will update the data-source to

Related posts