DEV Community

Cover image for Database — Fastify with TypeScript (part 13/18)
Antonio Tripodi
Antonio Tripodi

Posted on

Database — Fastify with TypeScript (part 13/18)

Database

Thirteenth chapter of the "Fastify with TypeScript" series. Our users have lived in memory since chapter 5 and vanish at every restart. Time to give them a real home in PostgreSQL, and to organize the code around it with a repository and a service.


A PostgreSQL to work with

The quickest way to get a database is Docker:

docker run --name fastify-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=app -p 5432:5432 -d postgres:16
Enter fullscreen mode Exit fullscreen mode

That matches the DATABASE_URL we put in .env back in chapter 4 (postgres://postgres:postgres@localhost:5432/app). If you already have a PostgreSQL, point DATABASE_URL at it instead.

Save the table definition as sql/001-users.sql:

CREATE TABLE users (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  name          text NOT NULL,
  email         text NOT NULL UNIQUE,
  role          text NOT NULL DEFAULT 'user',
  password_hash text NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

and run it:

docker exec -i fastify-pg psql -U postgres -d app < sql/001-users.sql
Enter fullscreen mode Exit fullscreen mode

The database generates the id, gives new users the user role, and guarantees that an email appears only once.

The database plugin

npm install @fastify/postgres pg
Enter fullscreen mode Exit fullscreen mode

Create src/plugins/database.ts:

// src/plugins/database.ts
import fp from 'fastify-plugin';
import fastifyPostgres from '@fastify/postgres';

export default fp(async function databasePlugin(fastify) {
  await fastify.register(fastifyPostgres, {
    connectionString: fastify.config.DATABASE_URL,
  });

  // An idle connection can fail at any time (the database restarts, the network drops).
  // The pool replaces it, but without a listener the error would crash the process.
  fastify.pg.pool.on('error', (err: Error) => {
    fastify.log.error({ err }, 'Idle database connection failed');
  });
}, { name: 'database' });
Enter fullscreen mode Exit fullscreen mode

@fastify/postgres decorates the instance with fastify.pg, which is why our plugin is wrapped with fastify-plugin: the whole application needs it. It creates a connection pool, a set of open connections that are reused across requests, and it closes the pool in an onClose hook, so app.close() releases every connection.

The pool.on('error') listener is not optional. Connections sit idle in the pool between requests, and one of them can fail at any moment, for example when the database restarts. Node treats an error event that nobody listens to as an uncaught exception, so without those three lines a database restart would take the whole API down with it. With them, the failure is logged and the pool opens a new connection the next time one is needed.

This plugin takes the place of the in-memory store. In src/app.ts, replace the store import and its registration with the database ones:

import database from './plugins/database.ts';
Enter fullscreen mode Exit fullscreen mode
  app.register(database);
Enter fullscreen mode Exit fullscreen mode

and delete src/plugins/store.ts. The project doesn't compile for the moment, because the two route files still use fastify.store. We'll fix them in the next sections.

A query looks like this:

const { rows } = await fastify.pg.query<UserRow>('SELECT * FROM users WHERE id = $1', [id]);
Enter fullscreen mode Exit fullscreen mode

Always use parameterized queries ($1, $2). The values travel separately from the SQL text, so nothing a user types can be executed as SQL. Building a query by concatenating strings is how SQL injection happens.

Repository pattern

A repository is the one place that knows how the users are stored. Everything else asks it for users and never sees SQL. Create src/users/users.repository.ts:

// src/users/users.repository.ts
import type { FastifyInstance } from 'fastify';
import type { Role } from './users.schema.ts';

export interface UserRow {
  id: string;
  name: string;
  email: string;
  role: Role;
  password_hash: string;
}

export function createUserRepository(app: FastifyInstance) {
  return {
    async findById(id: string): Promise<UserRow | null> {
      const { rows } = await app.pg.query<UserRow>('SELECT * FROM users WHERE id = $1', [id]);
      return rows[0] ?? null;
    },

    async findByEmail(email: string): Promise<UserRow | null> {
      const { rows } = await app.pg.query<UserRow>('SELECT * FROM users WHERE email = $1', [email]);
      return rows[0] ?? null;
    },

    // Returns null when the email is already registered: the UNIQUE constraint decides, atomically.
    async create(data: { name: string; email: string; passwordHash: string }): Promise<UserRow | null> {
      const { rows } = await app.pg.query<UserRow>(
        `INSERT INTO users (name, email, password_hash)
         VALUES ($1, $2, $3)
         ON CONFLICT (email) DO NOTHING
         RETURNING *`,
        [data.name, data.email, data.passwordHash],
      );
      return rows[0] ?? null;
    },

    async findAll(limit: number): Promise<UserRow[]> {
      const { rows } = await app.pg.query<UserRow>('SELECT * FROM users ORDER BY name LIMIT $1', [limit]);
      return rows;
    },
  };
}

export type UserRepository = ReturnType<typeof createUserRepository>;
Enter fullscreen mode Exit fullscreen mode

createUserRepository is a factory function: it receives what it depends on (the instance, for fastify.pg) and returns an object of methods. No class, no this, no global connection.

create() deserves a second look. Checking "is this email free?" with a SELECT and then inserting is not atomic: two sign-ups with the same email arriving together can both pass the check, and the second INSERT would hit the UNIQUE constraint and surface as a 500. ON CONFLICT (email) DO NOTHING lets the database decide in a single statement, and RETURNING * gives back no row when the insert was skipped, so the method returns null instead of throwing.

export type UserRepository = ReturnType<typeof createUserRepository> at the bottom gives the rest of the app a name for that object without writing an interface by hand.

A service layer

The repository answers "how do I talk to the database?". The rules of the domain (an email can only be registered once, passwords are hashed before they are stored, a missing user is a 404) belong in neither the SQL nor the HTTP handler. They go into a service, built with the same factory function pattern. Create src/users/users.service.ts:

// src/users/users.service.ts
import { hash } from 'argon2';
import createError from '@fastify/error';
import type { UserRepository, UserRow } from './users.repository.ts';
import type { CreateUserBodyType } from './users.schema.ts';

export const UserNotFound = createError('USER_NOT_FOUND', 'User %s not found', 404);
export const EmailTaken = createError('EMAIL_TAKEN', 'Email %s is already registered', 409);

export function createUserService(users: UserRepository) {
  return {
    async create({ name, email, password }: CreateUserBodyType): Promise<UserRow> {
      if (await users.findByEmail(email)) throw new EmailTaken(email);

      const passwordHash = await hash(password, { memoryCost: 65536, timeCost: 3, parallelism: 4 });
      const user = await users.create({ name, email, passwordHash });
      // Two concurrent requests can both pass the check above: the database has the last word.
      if (!user) throw new EmailTaken(email);
      return user;
    },

    async getById(id: string): Promise<UserRow> {
      const user = await users.findById(id);
      if (!user) throw new UserNotFound(id);
      return user;
    },

    async list(limit: number): Promise<UserRow[]> {
      return users.findAll(limit);
    },
  };
}

export type UserService = ReturnType<typeof createUserService>;
Enter fullscreen mode Exit fullscreen mode

The typed errors and the hashing move here from users.route.ts: they sit next to the only code that uses them. Note what the service does not import: Fastify. It depends on a UserRepository and nothing else, so in a test you can hand it a fake one (chapter 15).

The route file is now only about HTTP: URL, schema, hooks, status code. Replace src/users/users.route.ts with:

// src/users/users.route.ts
import { Type } from 'typebox';
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import { createUserRepository } from './users.repository.ts';
import { createUserService } from './users.service.ts';
import {
  CreateUserBody,
  ListUsersQuery,
  UserParams,
  UserResponse,
} from './users.schema.ts';

const userRoutes: FastifyPluginAsyncTypebox = async (fastify) => {
  const users = createUserService(createUserRepository(fastify));

  fastify.get('/', {
    schema: {
      tags: ['users'],
      security: [{ bearerAuth: [] }],
      querystring: ListUsersQuery,
      response: { 200: Type.Array(UserResponse) },
    },
    onRequest: [fastify.authorize('admin')],
  }, async (request) => {
    const { limit = 10 } = request.query;
    return users.list(limit);
  });

  fastify.get('/:id', {
    schema: {
      tags: ['users'],
      security: [{ bearerAuth: [] }],
      params: UserParams,
      response: { 200: UserResponse },
    },
    onRequest: [fastify.authenticate],
  }, async (request) => {
    return users.getById(request.params.id);
  });

  fastify.post('/', {
    schema: {
      tags: ['users'],
      body: CreateUserBody,
      response: { 201: UserResponse },
    },
  }, async (request, reply) => {
    const user = await users.create(request.body);

    reply.code(201);
    reply.header('Location', `/api/v1/users/${user.id}`);
    return user; // password_hash is stripped by the response schema
  });
};

export default userRoutes;
Enter fullscreen mode Exit fullscreen mode

The whole dependency chain is wired in one line, from the fastify instance the plugin receives: instance → repository → service. The three routes, their schemas and their hooks are the same as in the previous chapter. Only the bodies of the handlers changed, and each is now a single call.

The same treatment for auth

The login handler has rules of its own (compare against a dummy hash, one error for both failures), so they move into a service too. This factory takes two dependencies: the user repository and a function that signs a token. Passing the function, rather than the whole Fastify instance, keeps this service free of Fastify as well. Create src/auth/auth.service.ts:

// src/auth/auth.service.ts
import { verify } from 'argon2';
import createError from '@fastify/error';
import type { JwtPayload } from '../plugins/auth.ts';
import type { UserRepository } from '../users/users.repository.ts';
import type { LoginBodyType } from './auth.schema.ts';

export const InvalidCredentials = createError('INVALID_CREDENTIALS', 'Invalid email or password', 401);

// Argon2id hash of a random string nobody knows, with the same parameters as real hashes.
// Verifying against it when the email is unknown keeps the response time the same in both cases.
const DUMMY_HASH = '$argon2id$v=19$m=65536,t=3,p=4$QILZ4fJyOMMpkXQnKPjP9w$yM7sx7qU2rUnHRyaAnmTBMwzW9+BRCXbJ1NhlPG+2+Y';

export function createAuthService(users: UserRepository, signToken: (payload: JwtPayload) => string) {
  return {
    async login({ email, password }: LoginBodyType): Promise<string> {
      const user = await users.findByEmail(email);
      const valid = await verify(user?.password_hash ?? DUMMY_HASH, password);
      if (!user || !valid) throw new InvalidCredentials();

      return signToken({ id: user.id, email: user.email, role: user.role });
    },
  };
}

export type AuthService = ReturnType<typeof createAuthService>;
Enter fullscreen mode Exit fullscreen mode

Use your own DUMMY_HASH from the previous chapter. Then replace src/auth/auth.route.ts with:

// src/auth/auth.route.ts
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import { createUserRepository } from '../users/users.repository.ts';
import { createAuthService } from './auth.service.ts';
import { LoginBody, LoginResponse } from './auth.schema.ts';

const authRoutes: FastifyPluginAsyncTypebox = async (fastify) => {
  const auth = createAuthService(createUserRepository(fastify), (payload) => fastify.jwt.sign(payload));

  fastify.post('/login', {
    schema: { tags: ['auth'], body: LoginBody, response: { 200: LoginResponse } },
  }, async (request) => {
    return { token: await auth.login(request.body) };
  });

  fastify.get('/me', {
    schema: { tags: ['auth'], security: [{ bearerAuth: [] }] },
    onRequest: [fastify.authenticate],
  }, async (request) => {
    return { user: request.user };
  });
};

export default authRoutes;
Enter fullscreen mode Exit fullscreen mode

auth is the one module that reaches into another: it imports from ../users/users.repository.ts. Keep those cross-module imports explicit and one-directional (auth depends on users, never the other way round) and the modules stay easy to reason about.

npm run typecheck passes again.

Try it

curl -i -X POST localhost:3000/api/v1/users \
  -H 'content-type: application/json' \
  -d '{"name":"Grace","email":"grace@example.com","password":"correct-horse"}'
# HTTP/1.1 201 Created
# location: /api/v1/users/08beb12a-0317-423f-b08c-9080c00bcbe8
# {"id":"08beb12a-0317-423f-b08c-9080c00bcbe8","name":"Grace","email":"grace@example.com","role":"user"}
Enter fullscreen mode Exit fullscreen mode

Stop the server and start it again. Grace is still there:

docker exec -it fastify-pg psql -U postgres -d app -c "SELECT id, name, email, role FROM users"
Enter fullscreen mode Exit fullscreen mode

Everything from the previous chapter works exactly as before: login, /auth/me, the 409 for a duplicate email, the 404 for an unknown id. Nothing changed for the client, which is the point of hiding storage behind a repository.

Now we can finally make an admin:

docker exec -it fastify-pg psql -U postgres -d app -c "UPDATE users SET role = 'admin' WHERE email = 'grace@example.com'"
Enter fullscreen mode Exit fullscreen mode

Try the list with the token you already have, and you still get 403. The role is written inside the token, and that token was signed when Grace was a plain user. Log in again to get a new one:

curl localhost:3000/api/v1/users -H "authorization: Bearer $NEW_TOKEN"
# [{"id":"08beb12a-0317-423f-b08c-9080c00bcbe8","name":"Grace","email":"grace@example.com","role":"admin"}]
Enter fullscreen mode Exit fullscreen mode

This is a property of JWTs worth remembering: a change of role (or a ban) only takes effect when the old token expires. It is one of the reasons to keep the expiry short, as we did with expiresIn: '1h'.

Transactions

When several statements must succeed or fail together, use transact(). It borrows one connection, runs BEGIN, commits if your callback resolves and rolls back if it throws:

await fastify.pg.transact(async (client) => {
  await client.query('UPDATE accounts SET balance = balance - $1 WHERE id = $2', [amount, fromId]);
  await client.query('UPDATE accounts SET balance = balance + $1 WHERE id = $2', [amount, toId]);
});
Enter fullscreen mode Exit fullscreen mode

If the second statement fails, the first one is undone, and the money doesn't disappear. Inside the callback use client, not fastify.pg: only queries made on that connection are part of the transaction.

Other official adapters follow the same plugin + pool pattern: @fastify/mysql, @fastify/mongodb, @fastify/redis.


⬅️ Previous chapter: Authentication and authorization · ➡️ Next chapter: Security: CORS, Helmet, rate limiting

This article is part of the "Fastify with TypeScript" series — chapter 13 of 18.

Top comments (0)