DEV Community

Cover image for The Complete Beginner’s Guide to Backend Development with Node.js, TypeScript & PostgreSQL
Michael Otu
Michael Otu

Posted on

The Complete Beginner’s Guide to Backend Development with Node.js, TypeScript & PostgreSQL

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";
Enter fullscreen mode Exit fullscreen mode
  • 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;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 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";
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode
  • 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;
}
Enter fullscreen mode Exit fullscreen mode
  • 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;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

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);
  }
});
Enter fullscreen mode Exit fullscreen mode

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"]
  }
}
Enter fullscreen mode Exit fullscreen mode

Update the package.json

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

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");
});
Enter fullscreen mode Exit fullscreen mode

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);
  }
};
Enter fullscreen mode Exit fullscreen mode

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);
  }
};
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

The difference between the two functions looks like

const funcName = (params) => {
  // actions
};
Enter fullscreen mode Exit fullscreen mode

and

function funcName(params) {
  // actions
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

I usually prefer the /index.ts approach.

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

// other imports
import tasksRouter from "./tasks";
Enter fullscreen mode Exit fullscreen mode

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

app.use("/tasks", tasksRouter);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

"emitDecoratorMetadata": true,
"experimentalDecorators": true
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

Run, npm run build to check if anything is broken

src
 |-entity
 |    |-User.ts
 |-migration
 |
 |-data-source.ts
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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: [],
});
Enter fullscreen mode Exit fullscreen mode

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: [],
});
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

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

# application config
APP_PORT=3000
Enter fullscreen mode Exit fullscreen mode

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),
};
Enter fullscreen mode Exit fullscreen mode

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,
  },
};
Enter fullscreen mode Exit fullscreen mode

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

import "reflect-metadata";

import { DataSource } from "typeorm";
import { envConstants } from "../core";

export const AppDataSource = new DataSource({
  type: "postgres",
  host: envConstants.DATABASE_HOST,
  port: envConstants.DATABASE_PORT,
  username: envConstants.DATABASE_USERNAME,
  password: envConstants.DATABASE_PASSWORD,
  database: envConstants.DATABASE_NAME,
  synchronize: false,
  logging: false,
  entities: [__dirname + "/entity/**/*{.js,.ts}"],
  migrations: [__dirname + "/migration/**/*{.js,.ts}"],
  subscribers: [],
});
Enter fullscreen mode Exit fullscreen mode
  • From the doc we can pass the path to the entities and migrations rather than importing each entity.
  • set synchronization to false for production applications. I encourage you to set it to false and use migrations to do the synchronization. Synchronization is how the changes from your entities update your database tables to be in sync.
  • logging lets you see the SQL commands executed. In dev or testing environment, you can choose to enable

Run npm run build to ensure nothing is broken

Creating an Entity

We will create the Task entity together and you will create the Note entity.

A task must have a name, optional description, created date, updated date, we need to know if the task is done or not. An entity is a class with some decorators.

Every row of task must be uniquely identifiable as such there what is known as primary key (ID)

Every team and how they name their files and folders. Ensure you know the file-naming format

export class Task {
  id: number;

  name: string;

  description?: string;

  createdDate: Date;

  updatedDate?: Date;

  isCompleted: boolean;
}
Enter fullscreen mode Exit fullscreen mode

To turn this class into a valid TypeORM entity, decorators that can be used. More info can be found here and also on active records

  • Entity: It is used to mark a class as an Entity. Entity(table-name). We also do Entity({ name: table-name})
  • BaseEntity: It is the base abstract entity for all entities, used in ActiveRecord patterns.
  • PrimaryGeneratedColumn: It decorator marks a field as primary key and also the value for this field is auto-generated. Read more on this decorator here. In our use case we want PrimaryGeneratedColumn() since default is increment
  • Column: It is used on any other field. It has options, @Column({ }). Some of these options are type: some-type, length: N, nullable: false, unique: false. Read more here
  • CreatedDateColumn: It automatically sets the date the record was created
  • UpdatedDateColumn: It automatically sets the date the record was updated

From my point of view, when using a nullable field, we usually have to check if the field is null and then pass a default value when the field is null. Example, the description field is nullable. So before we render it as text we have to check else null will be displayed and it is not necessarily a desired outcome. It can become a nuisance as such, I usually set a default value for nullable fields.

The task entity now becomes

import {
  BaseEntity,
  Column,
  CreateDateColumn,
  Entity,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from "typeorm";

@Entity("tasks")
export class Task extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: "varchar", length: 200 })
  name: string;

  @Column({ type: "text", default: "" })
  description: string;

  @CreateDateColumn()
  createdDate: Date;

  @UpdateDateColumn({ nullable: true })
  updatedDate?: Date;

  @Column({ type: "boolean", default: false })
  isCompleted: boolean;
}
Enter fullscreen mode Exit fullscreen mode

Use varchar for normal strings and text for large strings like a description of an item. However, some restrictions are also features.

Migrations

We have an entity. The database has no idea of the existence of this table. This table only exists in code. Migration is a way to make changes to the database. A migration is an SQL script that you execute to write changes to the database. Read more on migrations here.

To create a migration, we use the command

npx tsx ./node_modules/typeorm/cli.js migration:create <path/to/migrations>/<migration-name>
Enter fullscreen mode Exit fullscreen mode

Any migration script that we'd want to run would look similar to this. We can improve this, just a bit.

In package.json, under the scripts block, update or set the typeorm script to "typeorm": "tsx ./node_modules/typeorm/cli.js".

We can now shorten the npx tsx ./node_modules/typeorm/cli.js part of the script to npm run typeorm. When running the rest of the scripts, we'd get an error. It is parsed as an npm flag or input as such we have to add the npm separator, -- so that the next input will be passed to typeorm instead.

npm run typeorm -- migration:create <path/to/migrations>/<migration-name>
Enter fullscreen mode Exit fullscreen mode

we can change the name, typeorm to anything however it is best to keep it this way, especially when working in a team.

Lets create a migration file called HeyThereMigration:

npm run typeorm -- migration:create ./src/database/migration/HeyThereMigration
Enter fullscreen mode Exit fullscreen mode

A file will be created that has the absolute path - /username/project/src/database/migration/timestamp-HeyThereMigration.ts

import { MigrationInterface, QueryRunner } from "typeorm";

export class HeyThereMigration1794882501254 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {}

  public async down(queryRunner: QueryRunner): Promise<void> {}
}
Enter fullscreen mode Exit fullscreen mode

I usually prefer generating the migration to creating it. This is cause the changes are detected automatically and the needed scripts are generated.

The command for generating a migration file is similar to that of creating a migration but here we have to add the path to the datasource.

npm run typeorm -- migration:generate -d /path/to/datasource /path/to/migrations/<migration-name>
Enter fullscreen mode Exit fullscreen mode

Migration names do not conflict since a timestamp is added

Lets generate migration for the current entity we have. Lets call it InitialMigration

npm run typeorm -- migration:generate -d ./src/database/data-source.ts ./src/database/migration/InitialMigration
Enter fullscreen mode Exit fullscreen mode

A new file will be created with the content:

import { MigrationInterface, QueryRunner } from "typeorm";

export class InitialMigration1794884023332 implements MigrationInterface {
  name = "InitialMigration1794884023332";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `CREATE TABLE "tasks" ("id" SERIAL NOT NULL, "name" character varying(200) NOT NULL, "description" text NOT NULL DEFAULT '', "createdDate" TIMESTAMP NOT NULL DEFAULT now(), "updatedDate" TIMESTAMP DEFAULT now(), "isCompleted" boolean NOT NULL DEFAULT false, CONSTRAINT "PK_8d12ff38fcc62aaba2cab748772" PRIMARY KEY ("id"))`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE "tasks"`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Lets break this down

  • up: when we run migration this method contains the script to be executed. So all the changes need to write to the database will be here.
  • down: when we undo migration, the down is called to undo the changes.

If you don't want to use or generate migrations, you can set the synchronization value to true in the datasource file but I strongly discourage it.

Now we can run migration for the newly generated migrations. All newly added migrations will be written permanently to the database.

The command is almost the same for create and generate. This is command is run.

npm run typeorm -- migration:run -d ./src/database/data-source.ts
Enter fullscreen mode Exit fullscreen mode

Now when we run migrations, the up are executed. We can verify this using Beekeeper studio. There should be two tables under public.

Finally, when we want to do the last migration executed, we use the revert command. So instead of run we use revert instead.

npm run typeorm -- migration:revert -d ./src/database/data-source.ts
Enter fullscreen mode Exit fullscreen mode

We can verify this. There should be only one table left.

There is the --fake flag that can be used with :run and :revert (...:action --fake ...) which will only insert/remove a record of the migrations table instead of actually writing the changes to the database or reverting the changes.

Typing out this long command will be recurring. Lets update the scripts in the package.json

"scripts": {
  "build": "tsc",
  "clean": "rm -rf dist",
  "start": "tsx src/index.ts",
  "dev": "tsx watch ./src/index.ts",
  "typeorm": "tsx ./node_modules/typeorm/cli.js",
  "migration:create": "npm run typeorm migration:create --",
  "migration:run": "npm run typeorm migration:run -- -d ./src/database/data-source.ts",
  "migration:generate": "npm run typeorm migration:generate -- -d ./src/database/data-source.ts",
  "migration:revert": "npm run typeorm migration:revert -- -d ./src/database/data-source.ts"
},
Enter fullscreen mode Exit fullscreen mode

Now all you have to do is

  • npm run migration:create <file-path> to create migration
  • npm run migration:generate <file-path> to generate migration
  • npm run migration:run to run migration
  • npm run migration:revert to revert migration

Ensure you undo all migrations and delete all pre-generated files. Start from scratch with your migrations. Generate a new one and run it.

You can use node run your migrations in js. Run npm run build then lets say you want to generate a migration, you'd run node ./node_modules/typeorm/cli.js migration:generate -d ./dist/to/datasource.js /path/to/migrations/<migration-name>. We can also update the scripts to manage migrations via .js extensions.

Module 4: Wiring It All Together

Project Structure

I encourage and promote implementing APIs based on resources/features. Since we are building API for tasks and notes. We will look at them as if they are standalone features and that is the idea. All APIs for tasks will be in a folder called tasks.

Now, every request comes with

  • request handlers: these are controllers and sometimes specific middlewares for this particular feature
  • router: this is how we map or route request for this particular feature
  • validation: this is how we check the input and ensure it matches certain criteria before we pass it down to the request handlers
  • interface: this is where we create the types, interfaces or DTOs for payloads that we use
  • service: this is when we want to keep our request handler lean by abstracting certain actions into functions or classes that can be called and used as the building blocks of the controller.

Router and controllers are enough for what we want to do. The others are optional design and architecture choices that have their own pros and cons.

Currently, we are to have, core, database and index.ts in the src folder. Anything else probably will be in a new folder called api. So the tasks and notes features will be in the api folder. In the api folder, we will have an index.ts file and it will import the routers from tasks and notes. It will then export them. Now we will import the index.ts in the api folder into the index.ts in the src folder and map out the route.

index.ts in src

import "reflect-metadata";

import express, { NextFunction, Request, Response } from "express";
import apiRouter from "./api";
import { envConstants } from "./core";

const app = express();

app.disable("x-powered-by");
app.disable("server");

app.use(express.json());

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);

app.use("/api", apiRouter);

app.listen(envConstants.APP_PORT, () => {
  console.log("app is running on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

index.ts in api

import { Router } from "express";
import taskRouter from "./tasks";

const router = Router();

router.use("/tasks", taskRouter);

export default router;
Enter fullscreen mode Exit fullscreen mode

index.ts in tasks

import { Router } from "express";

const router = Router();

//

export default router;
Enter fullscreen mode Exit fullscreen mode

Mount database

When the app is running, the first thing we want to do is establish a connection to the database.

From the docs, we need to call the initialize() method on the datasource object. data-source.ts exports AppDataSource. We will import this into index.ts in src folder and call the initialize() method.

import "reflect-metadata";

import express, { NextFunction, Request, Response } from "express";
import apiRouter from "./api";
import { envConstants } from "./core";
import { AppDataSource } from "./database/data-source";

const app = express();

app.disable("x-powered-by");
app.disable("server");

app.use(express.json());

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);

app.use("/api", apiRouter);

// connect to database and run app
AppDataSource.initialize()
  .then(() => {
    console.log("Database connected successfully");

    app.listen(envConstants.APP_PORT, () => {
      console.log("app is running on port 3000");
    });
  })
  .catch((error) => console.log(error));
Enter fullscreen mode Exit fullscreen mode

Task Controllers and Routes

In our case, we want to create, list, read, update and delete tasks. For these, we will implement controllers for each function.

Every action we expect from the user (you) will be in a file on it own, named accordingly.

We will use the:

  • POST method to create records
  • GET method to list and read one record
  • PUT method some update at least one field
  • PATCH method for just one field
  • DELETE method to delete a record

In our case, we'd have to update the name and description and PUT fits this case. We will use PATCH to update the status of the record, the isCompleted.

At this point you can install postman or bruno or install its vscode extension.

Create a collection and create a folder for the tasks and create your first request with a post method with URL, http://localhost:3000/api/tasks and also update the body of the request with

{
  "name": "Pay for the ethereum course on Udemy",
  "description": "Pay $9.99 for Grider's course on Udemy"
}
Enter fullscreen mode Exit fullscreen mode

Create Tasks

Create controllers and interfaces folder in the tasks folder.

In the interfaces folder, lets create index.ts and add the DTO for creating a task.

// interfaces/index.ts
export interface CreateTaskDTO {
  name: string;
  description?: string;
}
Enter fullscreen mode Exit fullscreen mode

Now let proceed to create the controller in a file called create-task.ts

// controllers/create-task.ts
import { NextFunction, Request, Response } from "express";
import { appConstants } from "../../../core/app-constants";
import { Task } from "../../../database/entity/task";
import { CreateTaskDTO } from "../interfaces";

export async function CreateTask(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  try {
    // read input
    // const {name, description } = req.body as CreateTaskDTO
    const { name, description }: CreateTaskDTO = req.body;

    if (!name) {
      return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
        message: "Name is required, and must be between 5 to 100 characters.",
      });
    }

    // validate name
    const nameLength = name.length;

    const isNameValid = nameLength > 5 && nameLength <= 100;

    if (!isNameValid) {
      return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
        message:
          "Name must be between 5 to 100 characters. received - " +
          nameLength.toString(),
      });
    }

    // validate description
    const descriptionLength = description?.length ?? 0;

    const isDescriptionValid = description && descriptionLength > 500;

    if (isDescriptionValid) {
      return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
        message:
          "Description must be at most 500 characters. received - " +
          descriptionLength.toString(),
      });
    }

    // create task
    // const taskObj = Task.create({ name, description });
    // const task = await Task.save(taskObj);

    const task = await Task.save(Task.create({ name, description }));

    return res.status(appConstants.STATUS_CODES.CREATED).json({
      message: "Task created successfully",
      taskId: task.id,
    });
  } catch (error) {
    return next(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

We validated the input against some requirements such as

  • name must be provided (required) and that name must be between 5 to 100 characters
  • description when provided must be at most 500 characters

As exercise, refactor the 5, 100 and 500 into the app constants file

Now we need to import the controller inside the tasks/index.ts

import { Router } from "express";
import { CreateTask } from "./controllers";

const router = Router();

router.post("/", CreateTask);

export default router;
Enter fullscreen mode Exit fullscreen mode

Run the request with bruno and the response should be similar to:

{
  "message": "Task created successfully",
  "taskId": 7
}
Enter fullscreen mode Exit fullscreen mode

List Tasks

You can use one controller to list and read one task by id when provided. However I encourage the use of different functions.

Now we use the .find() and the .findAndCount(). We can say they do the same thing however, .findAndCount() returns an array with two values. The first is an array of rows available and the second is the number of records.

What is important here is the options available. The often used ones are:

  • where: filters based on values
  • select: reads the specified columns and when not provided reads all
  • skip: this is offset used in pagination
  • take: this is limit used in pagination
  • relations: this is when we are using a foreign key and want to load that relation

The list tasks controller in list-tasks.ts

import { NextFunction, Request, Response } from "express";
import { appConstants } from "../../../core/app-constants";
import { Task } from "../../../database/entity/task";

export async function ListTasks(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  try {
    const tasks = await Task.find();

    return res.status(appConstants.STATUS_CODES.SUCCESS).json(tasks);
  } catch (error) {
    return next(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

Or replace .find with .findAndCount

const tasks = await Task.findAndCount();
Enter fullscreen mode Exit fullscreen mode

Lets update the router by adding

router.get("/", ListTasks);
Enter fullscreen mode Exit fullscreen mode

Remember to import ListTasks
As exercise, select the id, name, isCompleted and createdDate since when listing, we want to send a little information as such as possible. hint: { select: { field: true } }

Read Task

Here we want to read a particular task by id. The id is a number such we have to perform numerical validation on the input.

We can pass data via the url to the controller by

  • parameter: /url/:someKey where we can access it via req.someKey
  • query: /url?:someKey=value&:anotherKey=another-value where we can access it via req.query.somKey and req.query.anotherKey.

In our case, passing the data as request parameter will do.

// read-task.ts
import { NextFunction, Request, Response } from "express";
import { appConstants } from "../../../core/app-constants";
import { Task } from "../../../database/entity/task";

export async function ReadTask(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  try {
    const id = Number(req.params?.id);

    if (Number.isNaN(id)) {
      return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
        message: "A valid number is required to read a row",
      });
    }

    const task = await Task.findOne({
      where: { id },
    });

    if (!task) {
      return res.status(appConstants.STATUS_CODES.BAD_REQUEST).json({
        message: "Record not found",
      });
    }

    return res.status(appConstants.STATUS_CODES.SUCCESS).json(task);
  } catch (error) {
    return next(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

and import ReadTask in the router and add a new route

router.get("/:id", ReadTask);
Enter fullscreen mode Exit fullscreen mode

Update the list controller to expect an option filter query to filter response by some keyword

Update Task (name and description)

Just as we did for create task (POST), here we'll use PUT to update the name and description.

Request body will expect name, and description. At least one field is required. Which means both can not be null. Same validation logic must be applied here.

We can use the .save() and .update({ where }, { payload }) methods.

The payload for update tasks

export interface UpdateTaskDTO {
  name?: string;
  description?: string;
}
Enter fullscreen mode Exit fullscreen mode

Even though both are optional, we require at least one to be provided.

// update-task.ts
import { NextFunction, Request, Response } from "express";
import { appConstants } from "../../../core/app-constants";
import { Task } from "../../../database/entity/task";
import { UpdateTaskDTO } from "../interfaces";

export async function UpdateTask(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  try {
    const id = Number(req.params?.id);

    if (Number.isNaN(id)) {
      return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
        message: "A valid number is required to read a row",
      });
    }

    // read input
    // const { name, description } = req.body as CreateTaskDTO
    const { name, description }: UpdateTaskDTO = req.body;

    if (!name && !description) {
      return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
        message: "Name or description required",
      });
    }

    if (name) {
      // validate name
      const nameLength = name.length;

      const isNameValid = nameLength > 5 && nameLength <= 100;

      if (!isNameValid) {
        return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
          message:
            "Name is required, and must be between 5 to 100 characters. received - " +
            nameLength.toString(),
        });
      }
    }

    if (description) {
      // validate description
      const descriptionLength = description.length;

      const isDescriptionValid = descriptionLength > 500;

      if (isDescriptionValid) {
        return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
          message:
            "Description must be at most 500 characters. received - " +
            descriptionLength.toString(),
        });
      }
    }

    const task = await Task.findOne({
      where: { id },
    });

    if (!task) {
      return res.status(appConstants.STATUS_CODES.BAD_REQUEST).json({
        message: "Record not found",
      });
    }

    // task.name = name ?? task.name;
    // task.description = description ?? task.description;

    // await task.save();

    await Task.update(
      { id },
      {
        name: name ?? task.name,
        description: description ?? task.description,
      },
    );

    return res.status(appConstants.STATUS_CODES.SUCCESS).json({
      message: "Task updated successfully",
      taskId: task.id,
    });
  } catch (error) {
    return next(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

and we'd update the route

router.put("/:id", UpdateTask);
Enter fullscreen mode Exit fullscreen mode

Mark Task as Complete

PATCH is also used for update, usually updating a single field.

// mark-task-as-completed
import { NextFunction, Request, Response } from "express";
import { appConstants } from "../../../core/app-constants";
import { Task } from "../../../database/entity/task";

export async function MarkTaskAsCompleted(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  try {
    const id = Number(req.params?.id);

    if (Number.isNaN(id)) {
      return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
        message: "A valid number is required to read a row",
      });
    }

    const task = await Task.findOne({
      where: { id },
    });

    if (!task) {
      return res.status(appConstants.STATUS_CODES.BAD_REQUEST).json({
        message: "Record not found",
      });
    }

    if (task.isCompleted) {
      return res.status(appConstants.STATUS_CODES.BAD_REQUEST).json({
        message: "Task already completed",
      });
    }

    // task.isCompleted = true;

    // await task.save();

    await Task.update(
      { id },
      {
        isCompleted: true,
      },
    );

    return res.status(appConstants.STATUS_CODES.SUCCESS).json({
      message: "Task completed successfully",
      taskId: task.id,
    });
  } catch (error) {
    return next(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

and update the route

router.patch("/:id", MarkTaskAsCompleted);
Enter fullscreen mode Exit fullscreen mode

for this feature, we can only mark the task as completed. but what if we want to revert a completed task? What do you do? Would you implement another endpoint or update the current one? Implement your flow as exercise.

Delete Task

To delete a record, we use the .remove() method.

In a production application, your employer or company will have a data retention policy. Which basically means how you keep data or how long you'd keep data.

There are some niches where deleting can be costly and such in those situations we either provide a new field called isDeleted or isActive. We set this value to true when we delete a record. The updated date column will automatically be updated.

As exercise, add a new field called isDeleted and account for isDeleted when reading, listing, and updating (and patching) a record.

// delete-task.ts
import { NextFunction, Request, Response } from "express";
import { appConstants } from "../../../core/app-constants";
import { Task } from "../../../database/entity/task";

export async function DeleteTask(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  try {
    const id = Number(req.params?.id);

    if (Number.isNaN(id)) {
      return res.status(appConstants.STATUS_CODES.VALIDATION_ERROR).json({
        message: "A valid number is required to read a row",
      });
    }

    const task = await Task.findOne({
      where: { id },
    });

    if (!task) {
      return res.status(appConstants.STATUS_CODES.BAD_REQUEST).json({
        message: "Record not found",
      });
    }

    await task.remove();

    return res.status(appConstants.STATUS_CODES.SUCCESS).json({
      message: "Task deleted successfully",
    });
  } catch (error) {
    return next(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

and the route.

router.delete("/:id", DeleteTask);
Enter fullscreen mode Exit fullscreen mode

Summary & Verification Checklist

  • [x] Environment configured with Node.js, TypeScript, and hot-reloading (tsx).
  • [x] PostgreSQL container running via Docker and verified with Beekeeper Studio.
  • [x] Express routing configured with grouped controller endpoints.
  • [x] TypeORM entity defined and database table generated via migration scripts.
  • [x] Persistent CRUD API operations fully wired and verified.

Top comments (0)