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-sequelize-seeder

v1.1.4

Published

๐ŸŒพ A simple extension library for nestjs sequelize to perform seeding.

Downloads

1,134

Readme

๐ŸŒ Description

Under the hood, nestjs-sequelize-seeder makes use of the nest framework, and you also need to install nestjs, and sequelize !

๐Ÿ“ฆ Integration

To start using it, we first install the required dependencies. In this chapter we will demonstrate the use of the seeder for nestjs.

You simply need to install the package !

// We install with npm, but you could use the package manager you prefer !
npm install --save nestjs-sequelize-seeder

โ–ถ๏ธ Getting started

Once the installation process is complete, we can import the SeederModule into the root AppModule

import { Module } from '@nestjs/common';
import { SeederModule } from 'nestjs-sequelize-seeder';

@Module({
   imports: [
      SeederModule.forRoot({
         // Activate this if you want to run the seeders if the table is empty in the database
         runOnlyIfTableIsEmpty: true,
      }),
   ],
})
export class AppModule {}

All options

SeederModule.forRoot({
   isGlobal: true,
   logging: true,
   disabled: false,
   runOnlyIfTableIsEmpty: false,
   connection: 'default',
   autoIdFieldName: 'id',
   disableEveryOne: false,
   enableAutoId: true,
   foreignDelay: 2000, // 2 seconds
});

The forRoot() method supports all the configuration properties exposed by the seeder constuctor . In addition, there are several extra configuration properties described below.

| name | Description | type | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | | isGlobal | If you want the module globally (default: true ) | boolean | | logging | Option to display or not, the log of each creation (default: true) | boolean | | disabled | This option allows you to disable the whole module, it is very useful for production mode (default: false) | boolean | | runOnlyIfTableIsEmpty | This option allows you to disable if the table is empty (default: false) | boolean | | connection | This option is to add the name of the connection, this is very important if you use several connections to different databases (default: default) | string | | autoIdFieldName | This option is the id field, it works if the option enableAutoId is activated (default: id) | string | | enableAutoId | This option adds the id automatically to each item, saving you the work, and solving some errors, the name of the id field is customized with the option autoIdFieldName (default: true) | boolean | | foreignDelay | This option adds the timeout for tables that have relationships with other tables for each element, and this works if a seed has the containsForeignKeys option enabled | number |

Seeder

Sequelize implements the Active Record pattern. With this pattern, you use model classes directly to interact with the database. To continue the example, we need at least one seed. Let's define the User seed.

The decorator Seeder receives as parameter the unique values, this has to be added if you have in the table any column as unique !

The following options will be applied individually to the seeders, and will be compared and operated with the global configuration

@Seeder({
   model: ModelUser,
   unique: ['name'], // You can add more !
   // Here you can also add the following options, but those options only work for this seeder !
   disabled: false,
   logging: true,
   runOnlyIfTableIsEmpty: false,
   connection: 'default',
   disableEveryOne: false,
   enableAutoId: true,

    // Enables this function if it uses a relationship management model (foreignKeys)
   containsForeignKeys: false,

   // This option add run time delay, if you still have errors just increase the delay time
   foreignDelay: 2000,
})

genSaltSync and hashSync are imported from bcryptjs, you will have to install it independently !

import { Seeder, OnSeederInit } from 'nestjs-sequelize-seeder';
import { ModelUser } from 'src/models/user';
import { genSaltSync, hashSync } from 'bcryptjs';

@Seeder({
   model: ModelUser,
   unique: ['name', 'username'],
})
export class SeedUser implements OnSeederInit {
   run() {
      const data = [
         {
            name: 'Admin',
            username: 'admin',
            age: 34,
            password: 'admin_password',
         },
         {
            name: 'Editor',
            username: 'editor',
            age: 25,
            password: 'editor_password',
         },
      ];
      return data;
   }

   // This function is optional!
   everyone(data) {
      // Encrypting the password for each user !
      if (data.password) {
         const salt = genSaltSync(10);
         data.password = hashSync(data.password, salt);
         data.salt = salt;
      }

      // Aggregated timestamps
      data.created_at = new Date().toISOString();
      data.updated_at = new Date().toISOString();

      return data;
   }
}

Next, let's look at the UserModule:

import { Module } from '@nestjs/common';
import { SeederModule } from 'nestjs-sequelize-seeder';
import { SeedUser } from 'src/seeds/user.seed';

@Module({
   imports: [
      // Within an array!
      SeederModule.forFeature([SeedUser]),
   ],
})
export class UserModule {}

๐ŸŽ‰ Associations, ForeignKeys

You were probably wondering how I handle seeders with associations, well I'm anxious to tell you that it's like this

  • First create three models
  • We'll make some connections
  • Creation of seeders for each model
@Table
export class Cat extends Model<Cat> {
   @PrimaryKey
   @AutoIncrement
   @Column
   id: number;

   @Column
   name: string;

   @BelongsToMany(
      () => Breed,
      () => CatBreed,
   )
   breeds: Breed[];
}

@Table
export class Breed extends Model<Breed> {
   @PrimaryKey
   @AutoIncrement
   @Column
   id: number;

   @Column
   name: string;

   @BelongsToMany(
      () => Cat,
      () => CatBreed,
   )
   Cats: Cat[];
}

@Table
export class CatBreed extends Model<CatBreed> {
   @ForeignKey(() => Cat)
   @Column
   cat_id: number;

   @ForeignKey(() => Breed)
   @Column
   breed_id: number;
}

And as a consequence we will create the sowers

@Seeder({
   model: Cat,
})
export class SeedCat implements OnSeederInit {
   run() {
      const data = [
         {
            name: 'First Cat',
         },
         {
            name: 'Second Cat',
         },
      ];
      return data;
   }
}
@Seeder({
   model: Breed,
})
export class SeedCatBreed implements OnSeederInit {
   run() {
      const data = [
         {
            name: 'First Breed',
         },
         {
            name: 'Second Breed',
         },
      ];
      return data;
   }
}

As you can see we already created the sembredores free of relations, but the next one has relations, therefore we have to activate the option containsForeignKeys, this works with One-to-many, Many-to-many, and One-to-one, if you get an error just increase the delay time in the foreignDelay option in the global configuration

@Seeder({
   model: CatBreed,
   containsForeignKeys: true,
})
export class SeedCatBreedUse implements OnSeederInit {
   run() {
      const data = [
         {
            cat_id: 1,
            breed_id: 2,
         },
         {
            cat_id: 1,
            breed_id: 1,
         },
         {
            cat_id: 2,
            breed_id: 1,
         },
         {
            cat_id: 2,
            breed_id: 2,
         },
      ];
      return data;
   }
}

โญ Support for

nestjs-sequelize-seeder is an open source project licensed by MIT. You can grow thanks to the sponsors and the support of the amazing sponsors. If you want to join them, contact me here.

๐ŸŽฉ Stay in touch

๐Ÿš€ Contributors

Thanks to the wonderful people who collaborate with me !

๐Ÿ“œ License

nestjs-sequelize-seeder is MIT licensed.