<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by musanzi on Medium]]></title>
        <description><![CDATA[Stories by musanzi on Medium]]></description>
        <link>https://medium.com/@musanzi?source=rss-247f4c1e5c93------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9sx0_IdYf8FVSf_97jzHpg.png</url>
            <title>Stories by musanzi on Medium</title>
            <link>https://medium.com/@musanzi?source=rss-247f4c1e5c93------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 03:13:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@musanzi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[NestJS Session based Authentication]]></title>
            <link>https://medium.com/@musanzi/nestjs-session-based-authentication-2503f0f3ed2d?source=rss-247f4c1e5c93------2</link>
            <guid isPermaLink="false">https://medium.com/p/2503f0f3ed2d</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[sessions]]></category>
            <dc:creator><![CDATA[musanzi]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 15:56:25 GMT</pubDate>
            <atom:updated>2026-06-25T20:32:41.875Z</atom:updated>
            <content:encoded><![CDATA[<p>For the sake of this tutorial, let’s assume we’re using <strong>Listify</strong>, our product listing app (with users, products, etc.).</p><p>Let’s take a look at our UserEntity:</p><pre>@Entity()<br>export class User extends AbstractEntity {<br>  @Column()<br>  name: string;<br><br>  @Column({ nullable: true })<br>  avatar: string;<br><br>  @Column({ unique: true })<br>  email: string;<br><br>  @Column()<br>  password: string;<br><br>  @ManyToMany(() =&gt; Role, (role) =&gt; role.users)<br>  @JoinTable()<br>  roles: Role[];<br><br>  @OneToMany(() =&gt; Product, (product) =&gt; product.user)<br>  products: Product[];<br>}</pre><p>Before we get hands-on, we’ll need to install a few dependencies.</p><pre>pnpm add @nestjs/passport passport passport-local express-session bcrypt<br>pnpm add -D @types/express-session @types/passport-local @types/bcrypt</pre><p>Now, let’s focus on the <strong>authentication logic</strong> itself.</p><pre>nest g mo core/auth --no-spec<br>nest g co core/auth --no-spec<br>nest g s core/auth --no-spec</pre><p>In our auth.service.ts</p><pre>import { BadRequestException, Injectable, Req } from &#39;@nestjs/common&#39;;<br>import { UsersService } from &#39;src/features/users/users.service&#39;;<br>import * as bcrypt from &#39;bcrypt&#39;;<br>import { User } from &#39;src/features/users/entities/user.entity&#39;;<br>import { Request } from &#39;express&#39;;<br><br>@Injectable()<br>export class AuthService {<br>  constructor(private usersService: UsersService) {}<br><br>  async validateUser(email: string, pass: string): Promise&lt;User&gt; {<br>    try {<br>      const user = await this.usersService.findByEmail(email);<br>      await this.verifyPassword(pass, user.password);<br>      return user;<br>    } catch {<br>      throw new BadRequestException();<br>    }<br>  }<br><br>  private async verifyPassword(password: string, encrypted: string): Promise&lt;boolean&gt; {<br>    const isMatch = await bcrypt.compare(password, encrypted);<br>    if (!isMatch) throw new BadRequestException();<br>    return isMatch;<br>  }<br><br>  async signIn(@Req() req: Request): Promise&lt;User&gt; {<br>    return req[&#39;user&#39;] as User;<br>  }<br>}</pre><p><strong>Note:</strong> Make sure that UsersService is exported from the UsersModule and that the UsersModule is imported into the AuthModule.</p><p>Here’s what the findByEmail method in UsersService looks like:</p><pre><br>  async findByEmail(email: string): Promise&lt;User&gt; {<br>    try {<br>      const user = await this.usersRepository.findOneOrFail({<br>        where: { email },<br>        relations: [&#39;roles&#39;],<br>      });<br>      const roles = user.roles.map((role) =&gt; role.name);<br>      return { ...user, roles } as unknown as User;<br>    } catch {<br>      throw new NotFoundException();<br>    }<br>  }</pre><p>Okay, next we need to create a <strong>local guard</strong> at src/core/auth/guards/local.guard.ts and a <strong>local strategy</strong> at src/core/auth/strategies/local.strategy.ts.</p><p>local.guard.ts</p><pre>import { ExecutionContext, Injectable } from &#39;@nestjs/common&#39;;<br>import { AuthGuard } from &#39;@nestjs/passport&#39;;<br><br>@Injectable()<br>export class LocalAuthGuard extends AuthGuard(&#39;local&#39;) {<br>  constructor() {<br>    super();<br>  }<br><br>  async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {<br>    const result: boolean = (await super.canActivate(context)) as boolean;<br>    await super.logIn(context.switchToHttp().getRequest());<br>    return result;<br>  }<br>}</pre><p>local.strategy.ts</p><pre>import { PassportStrategy } from &#39;@nestjs/passport&#39;;<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { Strategy } from &#39;passport-local&#39;;<br>import { AuthService } from &#39;../auth.service&#39;;<br><br>@Injectable()<br>export class LocalStrategy extends PassportStrategy(Strategy) {<br>  constructor(private authService: AuthService) {<br>    super({ usernameField: &#39;email&#39; });<br>  }<br><br>  async validate(email: string, password: string) {<br>    return await this.authService.validateUser(email, password);<br>  }<br>}</pre><p>Let’s add a session serializer in our src/auth/session.serializer.ts</p><pre>import { PassportSerializer } from &#39;@nestjs/passport&#39;;<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { User } from &#39;src/features/users/entities/user.entity&#39;;<br><br>@Injectable()<br>export class SessionSerializer extends PassportSerializer {<br>  serializeUser(user: User, done: (_: null, user: User) =&gt; void): void {<br>    done(null, user);<br>  }<br><br>  deserializeUser(payload: string, done: (_: null, payload: string) =&gt; void) {<br>    done(null, payload);<br>  }<br>}</pre><p>Next, we need to <strong>add our guard</strong> to the AuthModule in auth.module.ts</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { AuthController } from &#39;./auth.controller&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br>import { UsersModule } from &#39;src/features/users/users.module&#39;;<br>import { LocalAuthGuard } from &#39;./guards/local-auth.guard&#39;;<br>import { SessionSerializer } from &#39;./session.serializer&#39;;<br>import { LocalStrategy } from &#39;./strategies/local.strategy&#39;;<br><br>@Module({<br>  imports: [UsersModule],<br>  controllers: [AuthController],<br>  providers: [AuthService, SessionSerializer, LocalAuthGuard, LocalStrategy]<br>})<br>export class AuthModule {}</pre><p>Now, we need to add an <strong>Auth Guard</strong> to protect routes so that only authenticated users can access them. Let’s create a file named auth.guard.ts in src/core/auth/guards.</p><pre>import { CanActivate, ExecutionContext, Injectable } from &#39;@nestjs/common&#39;;<br>import { Reflector } from &#39;@nestjs/core&#39;;<br>import { IS_PUBLIC_KEY } from &#39;../decorators/public.decorator&#39;;<br><br>@Injectable()<br>export class AuthGuard implements CanActivate {<br>  constructor(private reflector: Reflector) {}<br><br>  async canActivate(ctx: ExecutionContext): Promise&lt;boolean&gt; {<br>    const isPublic =<br>      this.reflector.getAllAndOverride&lt;boolean&gt;(IS_PUBLIC_KEY, [ctx.getHandler(), ctx.getClass()]) || false;<br>    if (isPublic) return true;<br>    const req = ctx.switchToHttp().getRequest();<br>    return req.isAuthenticated();<br>  }<br>}</pre><p>Next, let’s add a <strong>@Public decorator</strong> and a <strong>@CurrentUser decorator</strong>.</p><ul><li>The @Public decorator will allow certain routes to be accessible by <strong>unauthenticated users</strong>.</li><li>The @CurrentUser decorator will help us easily retrieve the <strong>currently authenticated user</strong> (useful, for example, when updating a user’s profile).</li></ul><p>public.decorator.ts</p><pre>import { SetMetadata } from &#39;@nestjs/common&#39;;<br><br>export const IS_PUBLIC_KEY = &#39;isPublic&#39;;<br>export const Public = () =&gt; SetMetadata(IS_PUBLIC_KEY, true);</pre><p>current-user.decorator.ts</p><pre>import { createParamDecorator, ExecutionContext } from &#39;@nestjs/common&#39;;<br>import { Request } from &#39;express&#39;;<br>import { User } from &#39;src/features/users/entities/user.entity&#39;;<br><br>export const CurrentUser = createParamDecorator((key: keyof User, ctx: ExecutionContext) =&gt; {<br>  const request = ctx.switchToHttp().getRequest&lt;Request &amp; { user?: User }&gt;();<br>  const user = request.user;<br>  return key ? user?.[key] : user;<br>});</pre><p>Now our auth.controller.ts</p><pre>import { Controller, Post, Req, UseGuards } from &#39;@nestjs/common&#39;;<br>import { User } from &#39;src/features/users/entities/user.entity&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br>import { Request } from &#39;express&#39;;<br>import { LocalAuthGuard } from &#39;./guards/local-auth.guard&#39;;<br>import { Public } from &#39;./decorators/public.decorator&#39;;<br><br>@Controller(&#39;auth&#39;)<br>export class AuthController {<br>  constructor(private authService: AuthService) {}<br>  @Post(&#39;sign-in&#39;)<br>  @Public()<br>  @UseGuards(LocalAuthGuard)<br>  signIn(@Req() req: Request): Promise&lt;User&gt; {<br>    return this.authService.signIn(req);<br>  }<br>}</pre><p>Now, let’s apply <strong>global protection</strong> for our app in app.module.ts.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>import { DatabaseModule } from &#39;./core/database/database.module&#39;;<br>import { UsersModule } from &#39;./features/users/users.module&#39;;<br>import { ProductsModule } from &#39;./features/products/products.module&#39;;<br>import { GalleriesModule } from &#39;./features/galleries/galleries.module&#39;;<br>import { APP_GUARD} from &#39;@nestjs/core&#39;;<br>import { ServeStaticModule } from &#39;@nestjs/serve-static&#39;;<br>import { resolve } from &#39;path&#39;;<br>import { AuthModule } from &#39;./core/auth/auth.module&#39;;<br>import { AuthGuard } from &#39;./core/auth/guards/auth.guard&#39;;<br><br>@Module({<br>  imports: [<br>    ServeStaticModule.forRoot({<br>      rootPath: resolve(__dirname, &#39;../../&#39;),<br>      renderPath: &#39;/uploads&#39;<br>    }),<br>    ConfigModule.forRoot({<br>      isGlobal: true<br>    }),<br>    DatabaseModule,<br>    UsersModule,<br>    ProductsModule,<br>    GalleriesModule,<br>    AuthModule<br>  ],<br>  providers: [<br>    { provide: APP_GUARD, useClass: AuthGuard }<br>  ]<br>})<br>export class AppModule {}</pre><p>Next, we need to <strong>enable sessions</strong> in main.ts (src/main.ts).</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { ValidationPipe } from &#39;@nestjs/common&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import passport from &#39;passport&#39;;<br>import session from &#39;express-session&#39;;<br><br>const port = Number(process.env.PORT) as number;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  app.useGlobalPipes(new ValidationPipe({ transform: true }));<br>  app.enableCors({<br>    origin: true,<br>    methods: [&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;],<br>    credentials: true<br>  });<br>  app.use(<br>    session({<br>      secret: process.env.SESSION_SECRET as string,<br>      resave: Boolean(process.env.SESSION_RESAVE),<br>      saveUninitialized: Boolean(process.env.SESSION_SAVE_UNINITIALIZED),<br>      cookie: { maxAge: 86400000, secure: false, sameSite: &#39;strict&#39;, httpOnly: true }<br>    })<br>  );<br>  app.use(passport.initialize());<br>  app.use(passport.session());<br><br>  await app.listen(port);<br>}<br>bootstrap().then();</pre><p>Our .env</p><pre># Session configuration<br># openssl rand -hex 32<br>SESSION_SECRET=&#39;generate_a_secure_random_string_here&#39;<br>SESSION_RESAVE=true<br>SESSION_SAVE_UNINITIALIZED=false</pre><p>Now, let’s <strong>test our Products API using Postman</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhIiSbj354BKszrrLKY8TA.png" /></figure><p>First, <strong>log in</strong> to obtain an authenticated session, then try again to <strong>fetch the products</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeSPtdWMmTPAdAI9O2iaYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrZ_qXq0qH93J3pMmn9CFQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2503f0f3ed2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Database Seeding]]></title>
            <link>https://medium.com/@musanzi/nestjs-database-seeding-daa11f32e066?source=rss-247f4c1e5c93------2</link>
            <guid isPermaLink="false">https://medium.com/p/daa11f32e066</guid>
            <category><![CDATA[database-seeding]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[musanzi]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 14:41:58 GMT</pubDate>
            <atom:updated>2026-03-09T09:59:15.186Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we’ll insert some default data into our database so we can use the API we created in the previous article on database migrations: <a href="https://medium.com/@musanziwilfried/nestjs-typeorm-migrations-b3c5a55195f0">NestJS TypeORM Migrations</a>.</p><p>Take a close look at the orm.config.ts file located in src/core/database/orm.config.ts. You’ll notice a configuration line for <strong>seeding</strong>.</p><p>Let’s start by installing the necessary extensions.</p><pre>pnpm add typeorm-extension <br>pnpm add -D @faker-js/faker</pre><p>In the src/core/database directory, we’ll create a new file named db.seeder.ts inside src/core/database/seeders/db.seeder.ts.</p><p>Let’s take a closer look at what this file will contain.</p><pre>import { Category } from &#39;src/features/products/categories/entities/category.entity&#39;;<br>import { Product } from &#39;src/features/products/entities/product.entity&#39;;<br>import { User } from &#39;src/features/users/entities/user.entity&#39;;<br>import { Role } from &#39;src/features/users/roles/entities/role.entity&#39;;<br>import { DataSource } from &#39;typeorm&#39;;<br>import * as bcrypt from &#39;bcrypt&#39;;<br>import { Seeder } from &#39;typeorm-extension&#39;;<br>import { faker } from &#39;@faker-js/faker&#39;;<br>import slugify from &#39;slugify&#39;;<br><br>export default class DbSeeder implements Seeder {<br>  async run(dataSource: DataSource) {<br>    await dataSource.dropDatabase();<br>    await dataSource.synchronize();<br><br>    const roleRepository = dataSource.getRepository(Role);<br>    const userRepository = dataSource.getRepository(User);<br>    const categoryRepository = dataSource.getRepository(Category);<br>    const productRepository = dataSource.getRepository(Product);<br><br>    // 1. Create Roles<br>    const seed = async () =&gt; {<br>      await roleRepository.save([&#39;admin&#39;, &#39;manager&#39;].map((r) =&gt; roleRepository.create({ name: r })));<br>      // 2. Create Admin User<br>      await userRepository.save({<br>        name: &#39;Admin User&#39;,<br>        email: &#39;admin@admin.com&#39;,<br>        password: await bcrypt.hash(&#39;admin1234&#39;, 10),<br>        roles: await roleRepository.find({ where: { name: &#39;admin&#39; } })<br>      });<br>      // 3. Create Categories<br>      const categoryNames = [&#39;Electronics&#39;, &#39;Books&#39;, &#39;Clothing&#39;, &#39;Home &amp; Kitchen&#39;, &#39;Sports&#39;, &#39;Toys&#39;];<br>      const categories = await categoryRepository.save(<br>        categoryNames.map((name) =&gt; categoryRepository.create({ name }))<br>      );<br>      // 4. Create Products<br>      const createProducts = async (count: number): Promise&lt;Product[]&gt; =&gt; {<br>        const products = Array.from({ length: count }).map((_, i) =&gt; {<br>          const name = `${faker.commerce.productName()} ${i + 1}`;<br>          return productRepository.create({<br>            name,<br>            slug: slugify(name, { lower: true }),<br>            description: faker.commerce.productDescription(),<br>            price: Number(faker.commerce.price({ min: 10, max: 1000, dec: 2 })),<br>            categories: faker.helpers.arrayElements(categories, faker.number.int({ min: 1, max: 2 }))<br>          });<br>        });<br>        return productRepository.save(products);<br>      };<br>      await createProducts(200);<br>    };<br>    await seed();<br>  }<br>}</pre><p>Now, let’s add a <strong>seed command</strong> to our package.json file.</p><p>This command will make it easier to run the database seeder directly from the terminal without having to type a long script each time.</p><pre>{<br>  &quot;typeorm-extension&quot;: &quot;ts-node ./node_modules/typeorm-extension/bin/cli.cjs&quot;,<br>  &quot;db:seed&quot;: &quot;pnpm build &amp;&amp; pnpm typeorm-extension seed:run -d src/core/database/orm.config.ts&quot;,<br>}</pre><p>And voilà! Let’s seed our database.</p><pre>pnpm db:seed</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daa11f32e066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS TypeORM Migrations]]></title>
            <link>https://medium.com/@musanzi/nestjs-typeorm-migrations-b3c5a55195f0?source=rss-247f4c1e5c93------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3c5a55195f0</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[typeorm]]></category>
            <dc:creator><![CDATA[musanzi]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 15:17:36 GMT</pubDate>
            <atom:updated>2026-03-09T10:00:18.095Z</atom:updated>
            <content:encoded><![CDATA[<h3>NestJS TypeORM Database Migrations</h3><p>For this tutorial, we will use <strong>Listify</strong>, a small product listing app.</p><p><strong>Table of Content</strong></p><ul><li>Create new NestJS app</li><li>Install and configure TypeOrm migrations</li></ul><p>Make sure you have the <strong>NestJS CLI</strong> installed. The CLI requires <strong>Node.js v22</strong>. If it’s not installed, you can install it with the following command:</p><pre>nest g new listify-api<br>code listify-api</pre><p>It should look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVv6r1HsOs6s2jjoP3wLzQ.png" /></figure><p>We need to delete app.controller.spec.ts, app.controller.ts, and app.service.ts. Make sure to also remove their references in app.module.ts.</p><p>Next, let’s install <strong>ConfigModule</strong> and <strong>TypeORM</strong> (including Migrations and Seeds).</p><pre>pnpm add @nestjs/config dotenv<br>pnpm approve-builds</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJt5hafN1MMZbPp5j6IxJA.png" /></figure><p>Let’s use the previously installed <strong>ConfigModule</strong> in our app.module.ts.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      isGlobal: true,<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><p>We need to add a .env file now. We’ll use it soon for environment variables such as the database name, password, and more.</p><pre>PORT=8000</pre><p>Before we continue, let’s take advantage of our PORT environment variable in main.ts.</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br><br>const port = process.env.PORT || 3000;<br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  await app.listen(port);<br>}<br>bootstrap()</pre><p>Let’s start our app. It should look like the screenshot below — fingers crossed! If it doesn’t, you may have missed a step. Start the development server with:</p><pre>pnpm start:dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22cxofpQE-A1VsnhRU-C5g.png" /></figure><p>Congratulations! Let’s now focus on <strong>TypeORM</strong> simple configurations and migrations.</p><h3>TypeORM installation (Mariadb 12)</h3><pre>pnpm add @nestjs/typeorm typeorm mysql2 typeorm-extension</pre><p>We need a <strong>DatabaseModule</strong>, so let’s generate it using the Nest CLI. You can see the available CLI options by running:</p><pre>nest g --help<br>nest g mo core/database</pre><p>Let’s configure it now inside src/core/database/database.module.ts. The command not only generated the module but also imported it into app.module.ts</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forRootAsync({<br>      inject: [ConfigService],<br>      useFactory: (configService: ConfigService) =&gt; ({<br>        type: &#39;mysql&#39;,<br>        port: +configService.get(&#39;DB_PORT&#39;),<br>        host: configService.get(&#39;DB_HOST&#39;),<br>        username: configService.get(&#39;DB_USERNAME&#39;),<br>        subscribers: [&#39;dist/**/*.subscriber.js&#39;],<br>        password: configService.get(&#39;DB_PASSWORD&#39;),<br>        database: configService.get(&#39;DB_NAME&#39;),<br>        synchronize: false,<br>        autoLoadEntities: true,<br>      }),<br>    }),<br>  ],<br>})<br>export class DatabaseModule {}</pre><p>In our .env file, we need to add DB_PORT, DB_HOST, DB_USERNAME, DB_PASSWORD, and DB_NAME. The <strong>Listify</strong> database must be created using the MariaDB CLI or any other database management tool.</p><pre>PORT=8000<br><br># Database configuration<br>DB_HOST=127.0.0.1<br>DB_PORT=3306<br>DB_USERNAME=root<br>DB_PASSWORD=root<br>DB_NAME=listify</pre><p>We may need to restart the server because we just updated the .env file. Run pnpm start:dev again, and hopefully everything works fine!</p><h3>TypeORM migrations</h3><p>We need an orm.config.ts file because we’ll use the CLI for migrations and seeders. Let’s create this file in src/core/database/orm.config.ts.</p><pre>import { DataSource } from &#39;typeorm&#39;;<br>import * as process from &#39;node:process&#39;;<br>import type { DataSourceOptions } from &#39;typeorm/data-source/DataSourceOptions&#39;;<br>import { config } from &#39;dotenv&#39;;<br><br>config({<br>  path: &#39;.env&#39;<br>});<br><br>export default new DataSource({<br>  type: &#39;mysql&#39;,<br>  host: process.env.DB_HOST,<br>  port: Number(process.env.DB_PORT),<br>  database: process.env.DB_NAME,<br>  username: process.env.DB_USERNAME,<br>  password: process.env.DB_PASSWORD,<br>  migrations: [&#39;src/core/database/migrations/**&#39;],<br>  seeds: [&#39;dist/core/database/seeders/**.js&#39;],<br>  entities: [&#39;dist/**/*.entity.js&#39;]<br>} as DataSourceOptions &amp; { seeds: string[] });<br>  </pre><p>Let’s add the corresponding script to the package.json file.</p><pre>&quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;nest build&quot;,<br>    &quot;format&quot;: &quot;prettier --write \&quot;src/**/*.ts\&quot; \&quot;test/**/*.ts\&quot;&quot;,<br>    &quot;start&quot;: &quot;nest start&quot;,<br>    &quot;start:dev&quot;: &quot;nest start --watch&quot;,<br>    &quot;start:debug&quot;: &quot;nest start --debug --watch&quot;,<br>    &quot;start:prod&quot;: &quot;node dist/main&quot;,<br>    &quot;lint&quot;: &quot;eslint \&quot;{src,apps,libs,test}/**/*.ts\&quot; --fix&quot;,<br>    <br>    // Migation scripts<br>    &quot;typeorm&quot;: &quot;ts-node ./node_modules/typeorm/cli&quot;,<br>    &quot;db:migrate&quot;: &quot;pnpm build &amp;&amp; pnpm typeorm migration:generate src/core/database/migrations/$npm_config_name -d src/core/database/orm.config.ts&quot;,<br>    &quot;db:up&quot;: &quot;pnpm typeorm migration:run -d src/core/database/orm.config.ts&quot;,<br>    &quot;db:down&quot;: &quot;pnpm typeorm migration:revert -d src/core/database/orm.config.ts&quot;<br>    <br>  },</pre><p>We need to add the following modules: UsersModule, RolesModule, ProductsModule, CategoriesModule, and GalleriesModule.</p><pre>nest g res features/users --no-spec <br>nest g res features/users/roles --no-spec <br>nest g res features/products --no-spec <br>nest g res features/products/categories --no-spec <br>nest g res features/galleries --no-spec</pre><p>Let’s explore how our entities should look. First, we need a BaseEntity from which other entities will extend. Let’s create it in src/database/abstract.entity.ts.</p><pre>import { PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from &#39;typeorm&#39;;<br><br>export abstract class AbstractEntity {<br>  @PrimaryGeneratedColumn(&#39;uuid&#39;)<br>  id: string;<br><br>  @CreateDateColumn()<br>  created_at: Date;<br><br>  @UpdateDateColumn()<br>  updated_at: Date;<br><br>  @DeleteDateColumn()<br>  deleted_at: Date;<br>}</pre><p>user.entity.ts</p><pre>import { AbstractEntity } from &#39;src/core/database/abstract.entity&#39;;<br>import { Column, Entity, JoinTable, ManyToMany } from &#39;typeorm&#39;;<br>import { Role } from &#39;../roles/entities/role.entity&#39;;<br><br>@Entity()<br>export class User extends AbstractEntity {<br>  @Column()<br>  name: string;<br><br>  @Column({ unique: true })<br>  email: string;<br><br>  @Column()<br>  password: string;<br><br>  @ManyToMany(() =&gt; Role, (role) =&gt; role.users)<br>  @JoinTable()<br>  roles: Role[];<br><br>  @OneToMany(() =&gt; Product, (product) =&gt; product.user)<br>  products: Product[];<br>}</pre><p>role.entity.ts</p><pre>import { Column, Entity, ManyToMany } from &#39;typeorm&#39;;<br>import { User } from &#39;../../entities/user.entity&#39;;<br>import { AbstractEntity } from &#39;src/core/database/abstract.entity&#39;;<br><br>@Entity()<br>export class Role extends AbstractEntity {<br>  @Column()<br>  name: string;<br><br>  @ManyToMany(() =&gt; User, (user) =&gt; user.roles)<br>  users: User[];<br>}</pre><p>product.entity.ts</p><pre>import { AbstractEntity } from &#39;src/core/database/abstract.entity&#39;;<br>import { Column, Entity, JoinColumn, JoinTable, ManyToMany, ManyToOne, OneToMany } from &#39;typeorm&#39;;<br>import { Category } from &#39;../categories/entities/category.entity&#39;;<br>import { User } from &#39;src/features/users/entities/user.entity&#39;;<br>import { Gallery } from &#39;src/features/galleries/entities/gallery.entity&#39;;<br><br>@Entity()<br>export class Product extends AbstractEntity {<br>  @Column()<br>  name: string;<br><br>  @Column()<br>  description: string;<br><br>  @Column()<br>  price: number;<br><br>  @ManyToMany(() =&gt; Category, (category) =&gt; category.products)<br>  @JoinTable()<br>  categories: Category[];<br><br>  @ManyToOne(() =&gt; User, (user) =&gt; user.products)<br>  @JoinColumn()<br>  user: User;<br><br>  @OneToMany(() =&gt; Gallery, (gallery) =&gt; gallery.products)<br>  galleries: Gallery[];<br>}</pre><p>category.entity.ts</p><pre>import { AbstractEntity } from &#39;src/core/database/abstract.entity&#39;;<br>import { Column, Entity, ManyToMany } from &#39;typeorm&#39;;<br>import { Product } from &#39;../../entities/product.entity&#39;;<br><br>@Entity()<br>export class Category extends AbstractEntity  {<br>  @Column()<br>  name: string;<br><br>  @ManyToMany(() =&gt; Product, (product) =&gt; product.categories)<br>  products: Product[];<br>}</pre><p>gallery.entity.ts</p><pre>import { AbstractEntity } from &#39;src/core/database/abstract.entity&#39;;<br>import { Product } from &#39;src/features/products/entities/product.entity&#39;;<br>import { Column, Entity, JoinColumn, ManyToMany } from &#39;typeorm&#39;;<br><br>@Entity()<br>export class Gallery extends AbstractEntity {<br>  @Column()<br>  name: string;<br><br>  @ManyToMany(() =&gt; Product)<br>  @JoinColumn()<br>  products: Product[];<br>}</pre><p>Okay, now let’s make TypeORM aware of our entities. Do this for each module, focusing on the imports array.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { RolesService } from &#39;./roles.service&#39;;<br>import { RolesController } from &#39;./roles.controller&#39;;<br>import { Role } from &#39;./entities/role.entity&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br><br>@Module({<br>  imports: [TypeOrmModule.forFeature([Role])],<br>  controllers: [RolesController],<br>  providers: [RolesService],<br>})<br>export class RolesModule {}</pre><p>Well done! Let’s now finally generate our migration.</p><pre>pnpm --name=&quot;init&quot; db:migrate</pre><p>Here is the result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izujbSnOTh1HXCMUVXOJeQ.png" /></figure><p>Finally, let’s create the tables using pnpm db:up, which we previously added to the package.json scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwioqWRy8gNkWmE_ZczogQ.png" /></figure><p>And voilà! It was a long journey, I hope you enjoyed it.<br> In the next articles, we’ll use this starting point to add seeds, session-based authentication, file uploads, and role-based access (RBAC).</p><p><strong>Bonus:</strong> We can also add commit-lint to run before pushing to GitHub.</p><pre>pnpm add -D @commitlint/cli @commitlint/config-conventional<br>echo &quot;export default { extends: [&#39;@commitlint/config-conventional&#39;] };&quot; &gt; commitlint.config.js<br>pnpm add --save-dev husky<br>pnpm husky init<br>echo &quot;pnpm dlx commitlint --edit \$1&quot; &gt; .husky/commit-msg</pre><p>In .husky/pre-commit, we can add a pre-commit command. In my case, I use pnpm lint to check for any linting errors before each commit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3c5a55195f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>