npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nestjs-db-seeder

v1.0.2

Published

An extension library for NestJS to perform seeding.

Downloads

10

Readme

This library does not depend on the database type that you use

How to use

1. Install the dependency

npm install nestjs-db-seeder --save-dev or yarn install nestjs-db-seeder -D

2. Define the model class

In this example, we'll use @nestjs/mongoose to define our model. But you could use any class that you want. It's not tied to any database type. The only requirement is that you use ES2015 class.

user.schema.ts

import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Document } from "mongoose";
import { Factory } from "nestjs-db-seeder";

@Schema()
export class User extends Document {
  @Factory(faker => faker.name.findName())
  @Prop()
  name: string;
}

export const userSchema = SchemaFactory.createForClass(User);

Notice that we use @Factory decorator to specify the value for this property. This value will be used during the seeding process.

@Factory decorator supports multiple argument types, for example:

Static Value

@Factory('male')
gender: string;

Faker Generated Value

@Factory(faker => faker.address.streetAddress())
address: string;

Custom Function

@Factory(() => {
  const minAge = 18;
  const maxAge = 30;
  return Math.round(Math.random() * (maxAge - minAge) + minAge);
})
age: number;

3. Define seeder

A seeder is a class that implements Seeder interface. It requires you to implement two methods:

  • async seed(): Promise<any>
  • async drop(): Promise<any>

Use seed method to insert data into the database, and use drop method to clear the data in the database (collection / table).

To insert the data into the database, you could use the provided DataFactory.createForClass method. Please see the example below:

users.seeder.ts

import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { User } from "../schemas/user.schema";
import { Seeder, DataFactory } from "nestjs-db-seeder";

@Injectable()
export class UsersSeeder implements Seeder {
  constructor(@InjectModel(User.name) private readonly user: Model<User>) {}

  async seed(): Promise<any> {
    // Generate 10 users.
    const users = DataFactory.createForClass(User).generate(10);

    // Insert into the database.
    return this.user.insertMany(users);
  }

  async drop(): Promise<any> {
    return this.user.deleteMany({});
  }
}

4. Register the seeder

Create a seeder file under src folder in your NestJS project and name it seeder.ts.

src/seeder.ts

import { seeder } from "nestjs-db-seeder";
import { MongooseModule } from "@nestjs/mongoose";
import { User, userSchema } from "./schemas/user.schema";
import { UsersSeeder } from "./seeders/users.seeder";

seeder({
  imports: [
    MongooseModule.forRoot("mongodb://localhost/nestjs-db-seeder-sample"),
    MongooseModule.forFeature([{ name: User.name, schema: userSchema }]),
  ],
}).run([UsersSeeder]);

Notice that seeder function accepts NestJS @Module() decorator metadata such as imports and providers. This will allow you to use NestJS dependency injection and later inject it in your seeder file.

Finally, we call run method and pass any number of seeders that you want to run. In this case we want to run UsersSeeder.

If you want to run multiple seeders, you could do:

.run([UsersSeeder, ProductsSeeder])

5. Integrate your seeder into command line

Add these two script (seed, seed:refresh and seed:drop) under the scripts property in your package.json file:

package.json

"scripts": {
  "seed": "node dist/seeder",
  "seed:refresh": "node dist/seeder --refresh",
  "seed:drop": "node dist/seeder --drop"
}

NOTE: Don't replace the scripts. Add both seed, seed:refresh and seed:drop scripts after your existing scripts.

With the scripts integrated in the package.json file, now you could run 3 different commands:

Run seeders normally

npm run seed

Run seeders and replace existing data

npm run seed:refresh

Remove all existing data

npm run seed:drop

Advance Usage

Access previously generated value

user.schema.ts

@Schema()
export class User extends Document {
  @Factory(faker => faker.random.arrayElement(["male", "female"]))
  @Prop({ required: true })
  gender: string;

  @Factory((faker, ctx) => faker.name.firstName(ctx.gender === "male" ? 0 : 1))
  @Prop({ required: true })
  firstName: string;
}

Fill context with predefined values

user.schema.ts

const users = DataFactory.createForClass(User).generate(10, {
  zipCode: "10153",
});

users.seeder.ts

@Schema()
export class User extends Document {
  // If you pass predefined values to the `generate` function, you will be
  // able to access it in the context.
  @Factory((faker, ctx) => `${faker.address.streetAddress()} ${ctx.zipCode}`)
  @Prop({ required: true })
  address: string;
}

📜 License

nestjs-db-seeder is MIT licensed.