Connecting to Mock Database

Introduction: Why Use a Mock Database?

Welcome back! In the last lesson, you learned how to organize your code by moving business logic into a service layer. Now, you are ready to connect your service to a data source. In real-world applications, this data source is usually a database. However, when learning or testing, it’s common to use a mock database instead.

Common database options include SQL (like PostgreSQL or MySQL), NoSQL (like MongoDB), or cloud-hosted databases. These real databases persist your data between sessions and support complex queries. For now, we’re using a mock database to simulate this behavior using plain arrays in memory. It’s faster to set up and ideal for learning or prototyping — but keep in mind that all data is reset when the server restarts.

A mock database is a simple, fake version of a real database. It lets you store and retrieve data in memory, using arrays or objects, without needing to set up a real database server. This makes it much easier and faster to develop and test your API.

In this lesson, you will see how to connect your NestJS service layer to a mock database so your API can return real data instead of hardcoded values.

Quick Recap: Where We Are Now

Let’s quickly remind ourselves of the current project structure. You already have:

  • A controller that handles HTTP requests for users.
  • A service that contains the business logic for users.
  • A module that brings everything together.

Here’s a summary of the setup so far:

// src/users/users.controller.ts
import { Controller, Get, Param } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get('all')
  findAll() {
    return this.usersService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(+id);
  }
}

This controller receives requests and calls the service methods. In the last lesson, you learned how to move logic into the service. Now, let’s see how the service can get its data from a mock database.

How the Mock Database Works

Instead of connecting to a real database, we use a mock database defined in a file called mock-db.ts. This file contains a simple array of user objects:

// src/database/mock-db.ts
export interface User {
  id: number;
  name: string;
}

export const users: User[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
];

To access this data, we use a service called DatabaseService. The DatabaseService acts as a single source of truth for data access — a pattern often used in real applications, where services abstract direct access to databases. Here’s how it looks:

// src/database/database.service.ts
import { Injectable } from '@nestjs/common';
import { users, User } from './mock-db';

@Injectable()
export class DatabaseService {
  private readonly users: User[] = users;

  getUsers(): User[] {
    return this.users;
  }
  
  findUserById(id: number): User | undefined {
    return this.users.find(user => user.id === id);
  }
}

Explanation:

  • The DatabaseService is marked with @Injectable(), which means it can be injected into other classes.
  • It has two methods:
    • getUsers() returns the full list of users.
    • findUserById(id) returns a single user matching the given ID, or undefined if not found.

This setup lets you simulate a real database using just a simple array.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal