NestJS: Generate N random users using Faker.js

Updated: February 13, 2024 By: Guest Contributor Post a comment

Overview

Creating realistic data for testing and development environments is a crucial part of software development. With NestJS, a progressive Node.js framework, and Faker.js, a popular library for generating fake data, developers can easily simulate a variety of data for their applications. This tutorial will guide you through generating N random users in a NestJS project using Faker.js.

Setting Up Your NestJS Project

First, ensure that you have Node.js installed on your computer. Then, install the Nest CLI globally with npm:

npm i -g @nestjs/cli

Create a new Nest project:

nest new nest-random-users

Navigate to your project directory:

cd nest-random-users

Installing Faker.js

Add Faker.js to your project:

npm install --save faker

Creating the User Module

In NestJS, functionalities are organized into modules. The next step is to generate a User module:

nest generate module users

Now, generate a service where the random user generation logic will live:

nest generate service users

Generating Fake Users in the User Service

Open up the users.service.ts file. Begin by importing Faker:

import * as faker from 'faker';

Next, let’s define our UserService class:

import { Injectable } from '@nestjs/common';
import * as faker from 'faker';

@Injectable()
export class UsersService {
  createRandomUsers(count: number): any[] {
    const users = [];
    for (let i = 0; i < count; i++) {
      users.push({
        id: i + 1,
        name: faker.name.findName(),
        email: faker.internet.email(),
        avatar: faker.internet.avatar(),
      });
    }
    return users;
  }
}

This service method createRandomUsers generates an array of users, with each user having a unique id, name, email, and avatar URL, all of which are generated using Faker.js.

Creating a Controller

To expose our service through an API, we need to create a controller:

nest generate controller users

Then, update the users.controller.ts file:

import { Controller, Get, Query } from '@nestjs/common';
import { UsersService } from './users.service';

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

  @Get()
  getRandomUsers(@Query('count') count: number): any[] {
    return this.usersService.createRandomUsers(count || 10);
  }
}

The controller defines a GET endpoint that accepts an optional query parameter count. It uses the UsersService to generate the desired number of random users.

Testing Your Endpoint

To test your application, run the server:

npm run start

Use a tool like Postman or open your browser and navigate to http://localhost:3000/users?count=5 to see your generated users.

Tips for Extending Functionality

  • Custom User Fields: Use Faker’s vast library of methods to generate a wide variety of data types if you need more detailed user information.
  • Database Integration: Consider integrating your NestJS application with a database, using libraries such as TypeORM or Mongoose, to persist generated users.
  • Validation: Implement validation in your application to ensure the count query parameter is a positive integer.

Conclusion

In conclusion, Faker.js provides an expansive toolset for generating mock data, which, when combined with NestJS, can greatly assist in rapidly setting up realistic datasets for development and testing. Whether you’re building an API, a CRM, or any other system that requires test data, following the steps outlined above will help you create a flexible, scalable way to generate random users.