<?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 Samresh Thapa on Medium]]></title>
        <description><![CDATA[Stories by Samresh Thapa on Medium]]></description>
        <link>https://medium.com/@thapasamresh9?source=rss-9137a5102f52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2bYgxY6ftPhYXh7VazkEyw.png</url>
            <title>Stories by Samresh Thapa on Medium</title>
            <link>https://medium.com/@thapasamresh9?source=rss-9137a5102f52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 06:26:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thapasamresh9/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[From Cake to Culture: Celebrating February’s Big Moments]]></title>
            <link>https://medium.com/younginnovations-blog/from-cake-to-culture-celebrating-februarys-big-moments-077c7a26e905?source=rss-9137a5102f52------2</link>
            <guid isPermaLink="false">https://medium.com/p/077c7a26e905</guid>
            <category><![CDATA[shivaratri]]></category>
            <category><![CDATA[cake]]></category>
            <category><![CDATA[stage]]></category>
            <category><![CDATA[earthquake]]></category>
            <category><![CDATA[birthday]]></category>
            <dc:creator><![CDATA[Samresh Thapa]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 12:24:46 GMT</pubDate>
            <atom:updated>2025-02-28T12:25:28.388Z</atom:updated>
            <content:encoded><![CDATA[<h3>YoungInnovations Weekly #444: From Cake to Culture- Celebrating February’s Big Moments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbPkw0u9ag3Ckoz9GmdGHA.jpeg" /></figure><blockquote><strong>“The mind is everything. What you think, you become.”</strong> — Buddha</blockquote><h3>Stage and Cake — Celebrating February Birthdays!🎂</h3><p>It’s the last Friday of the month, which means it’s time to celebrate all our amazing February birthdays! 🥳 Whether you were born on a chilly winter day or share a special leap year birthday, today is all about you. Let’s take a moment to wish <a href="https://medium.com/u/517d6b29509a">dikshya ghale</a> ,<a href="https://medium.com/u/f5e18fbc0323">Sanil Manandhar,</a> <a href="https://medium.com/u/93c51d61b2b9">Shreya Baidya</a>, <a href="https://medium.com/u/facc68a5fde2">Shreedharpandey</a>, <a href="https://medium.com/u/e7a5e24386fd">Prawesh Shrestha</a>,<strong>Binisha Maharjan</strong>, <strong>Alina Maharjan,</strong> <strong>Pradeep Chhetri</strong> , <strong>Shreedhar Pandey</strong> ,<strong>Kanchan Thapa </strong>a very happy birthday! May this year bring you endless joy, success, and of course, lots of cake!</p><p>Today, we also had some fantastic speakers on stage. <a href="https://medium.com/u/a86ad08ec8ff">Riju</a><strong> Shrestha </strong>shared an insightful presentation on <strong>“</strong>The Unofficial Guide to Money Management: What Not to Do<strong>.”</strong> <strong>Nabin Magar </strong>spoke about <strong>“</strong>Shivaratri<strong>.”</strong> <strong>Shristi Koju</strong> gave a captivating talk on <strong>“</strong>Neuralink: The Future of Brain Technology.<strong>”</strong> These sessions are always a great way to learn from each other and keep things fresh!</p><p>It’s been a moment full of learning, laughter, and, of course, delicious cake to wrap it all up (though I’m missing out). Here’s to many more celebrations and inspiring moments in the future!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eeTzsGA7dTMDy_kvfRxRYQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tSF0ncFF08fa5KgdoW0Lw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7yr-a-AM6G0gNqB_0mFBg.jpeg" /><figcaption>Spotlight on our speakers! — Riju, Nabin, and yep, that’s Shristi in the middle.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mgu4QzKjNyDhMQhMXfDbwQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmmufzMIAhUxR4IoxUdcNg.jpeg" /></figure><h3>Next Paila — Power BI Training</h3><p>The <strong>10-day Power BI training</strong> has been successfully completed at the Nabil Training Center, Ghantaghar branch. This program, aimed at the dedicated staff of Nabil Bank, equipped participants with advanced data visualization and analytical skills. A fantastic opportunity for the team to level up their data game and bring impactful insights to the table! 📊💡</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*DVca9rsxFjPrAa8f5tUZjA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwBaq-hrpFS7P5U1R-LYOg.jpeg" /></figure><h3>Embracing the Spirit of Shivaratri</h3><p>This week, we celebrated <strong>Shivaratri</strong>, a festival deeply rooted in devotion and spiritual significance. Across Nepal, especially at Pashupatinath Temple, thousands of devotees gathered to offer prayers, chant hymns, and seek blessings from Lord Shiva. The night was filled with the warmth of bonfires, as people came together to sing bhajans, meditate, and share stories of Shiva’s greatness. Many observed fasting, while sadhus and pilgrims embraced the sacred atmosphere, staying awake throughout the night in deep devotion.</p><p>Beyond the rituals, Shivaratri is a time for reflection — a reminder to cultivate patience, honesty, and forgiveness in our lives. As we move forward, let’s carry the spirit of this celebration with us, fostering kindness, respect, and a renewed sense of purpose in both our personal and professional journeys.</p><p>This year, I had the privilege of celebrating at my hometown’s Doleswor Temple, believed to be the head of Kedarnath. The divine ambiance, powerful chants, and the sea of devoted worshippers made it an unforgettable experience. Check out the pictures below! 🚩✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvnJSyqdgYBgulSSn-tk2g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSOEF8DhF8zBSZNKx6C4Bw.jpeg" /></figure><h3><strong>Gyalpo Loshar</strong></h3><p>A very happy Gyalpo Lhosar to all of us, Tashi Delek. Nepal is a unification of several diversities, these diversities are not adversities but an identity of a common platform of nationality, Nepali. Losar exhibits the rare culture of Tibetan and the values of Buddhism to the world, among three Lhosars celebrated in Nepal, Gyalpo Lhosar is the auspicious celebration of Tibetan New Year. Tibet and other neighboring nations prepare for this day in their own way, Lo means year and Shar means new so jointly it forms a New Year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yklDIgIExeEifG1hZhO6Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*G82_YW5uFwoPBAmSMTKjIw.jpeg" /><figcaption>Image source:- Republica</figcaption></figure><h3><strong>Earthquake Hits Again — Hold On Tight </strong>🌀🚨</h3><p>This morning, a <strong>6.1 magnitude earthquake</strong> struck around Bhairab Kunda in the Sindhupalchok District. While we’re all still standing, it’s a good reminder that the ground sometimes likes to remind us who’s boss! Stay safe, stay calm, and make sure you’re prepared in case the ground decides to shake again!</p><p>And that’s a wrap for this week! Take some time to relax, recharge, and get ready for more excitement next week. Enjoy your weekend to the fullest!🌴</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=077c7a26e905" width="1" height="1" alt=""><hr><p><a href="https://medium.com/younginnovations-blog/from-cake-to-culture-celebrating-februarys-big-moments-077c7a26e905">From Cake to Culture: Celebrating February’s Big Moments</a> was originally published in <a href="https://medium.com/younginnovations-blog">YoungInnovations&#39; Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subscribers (Entity Listeners) in TypeORM with NestJS For Audit Log]]></title>
            <link>https://medium.com/@thapasamresh9/subscribers-entity-listeners-in-typeorm-with-nestjs-for-audit-log-63b7813eb804?source=rss-9137a5102f52------2</link>
            <guid isPermaLink="false">https://medium.com/p/63b7813eb804</guid>
            <category><![CDATA[audit-logs]]></category>
            <category><![CDATA[postgres-typeorm-nestjs]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[typeorm-trigger]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Samresh Thapa]]></dc:creator>
            <pubDate>Sat, 25 Jan 2025 03:59:52 GMT</pubDate>
            <atom:updated>2025-01-25T03:59:52.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Subscribers (Entity Listeners) in TypeORM with NestJS</h3><h3>Introduction</h3><p>Recently, I was assigned a task in my team to capture audit logs for changes made in the database. This includes tracking the creation, updating, and deletion of different entities to monitor changes effectively. I was given a reference to the Laravel Audit Log package, which made it easy to log these actions in Laravel applications.</p><p>Curious about similar solutions for Node.js, I searched for libraries that could provide this functionality. However, I didn’t find anything that met my needs. This led me to explore NestJS event subscribers, which can be utilized to implement an audit log system. By using subscribers, I could listen for changes in the database and log them accordingly, giving me the flexibility to track all necessary actions.</p><p>In modern web applications, managing side effects related to database operations is crucial for maintaining data integrity and enhancing user experience. TypeORM provides a powerful feature known as <strong>Subscribers</strong> (or <strong>Entity Listeners</strong>) that allows you to listen to specific events triggered by entity lifecycle changes. This post explores how to implement subscribers in a NestJS application using TypeORM, enhancing your application’s data management capabilities.</p><h3>What are Subscribers in TypeORM?</h3><p>Subscribers are special classes in TypeORM that can listen to various events related to entity lifecycle changes. They allow you to hook into events like:</p><ul><li>Before Insert</li><li>After Insert</li><li>Before Update</li><li>After Update</li><li>Before Remove</li><li>After Remove</li></ul><p>By using subscribers, you can execute custom logic before or after these events, making it a great tool for tasks like logging, validation, and automatic population of related entities.</p><h3>Example Subscriber Setup</h3><p>To create a subscriber, you need to define a class and register it in your module. Here’s a simple example:</p><pre>import { EntitySubscriberInterface, EventSubscriber, InsertEvent, UpdateEvent, RemoveEvent } from &#39;typeorm&#39;;<br>import { User } from &#39;./user.entity&#39;; // Replace with your entity<br><br>@EventSubscriber()<br>export class UserSubscriber implements EntitySubscriberInterface&lt;User&gt; {<br>  /**<br>   * This subscriber listens to the User entity events.<br>   */<br>  listenTo() {<br>    return User; // Specify the entity you want to listen to<br>  }<br><br>  async afterInsert(event: InsertEvent&lt;User&gt;) {<br>    console.log(`A user has been created: ${event.entity}`);<br>    // Log or handle the insert event<br>  }<br><br>  async afterUpdate(event: UpdateEvent&lt;User&gt;) {<br>    console.log(`A user has been updated: ${event.entity}`);<br>    // Log or handle the update event<br>  }<br><br>  async afterRemove(event: RemoveEvent&lt;User&gt;) {<br>    console.log(`A user has been removed: ${event.entity}`);<br>    // Log or handle the remove event<br>  }<br>}</pre><h3>Listening to All Entities with a General Subscriber</h3><p>In TypeORM, subscribers are typically used to respond to events for specific entities. However, you can create a general subscriber to listen to events for all entities by manually registering it with the DataSource. Below is an example of how to implement this:</p><pre>import { DataSource, EventSubscriber, InsertEvent, UpdateEvent, RemoveEvent } from &#39;typeorm&#39;;<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { AuditlogService } from &#39;./auditlog.service&#39;; // Import your audit log service<br><br>@Injectable()<br>export class GeneralSubscriber implements EntitySubscriberInterface {<br>  constructor(<br>    dataSource: DataSource, // Inject the DataSource<br>  ) {<br>    dataSource.subscribers.push(this); // Register the subscriber manually<br>  }<br><br>  // Handle after insert event<br>  afterInsert(event: InsertEvent&lt;any&gt;) {<br>    console.log(&#39;After insert:&#39;, event.entity);<br> // Log the insert action<br>  }<br><br>  // Handle after update event<br>  afterUpdate(event: UpdateEvent&lt;any&gt;) {<br>    console.log(&#39;After update:&#39;, event.entity);<br>  // Log the update action<br>  }<br><br>  // Handle after remove event<br>  afterRemove(event: RemoveEvent&lt;any&gt;) {<br>    console.log(&#39;After remove:&#39;, event.entity);<br>    // Log the remove action<br>  }<br>}</pre><ul><li><strong>Manual Registration</strong>: By using dataSource.subscribers.push(this);, the GeneralSubscriber registers itself with the TypeORM DataSource. This allows TypeORM to recognize and invoke its event handling methods during insert, update, and remove events.</li><li><strong>Listening to All Entities</strong>: This approach enables the subscriber to handle events for all entities without needing to specify them individually. This is useful for implementing cross-cutting concerns, such as logging or auditing, in a centralized way.</li></ul><p>With this setup, any changes made to any entity will trigger the corresponding methods in the GeneralSubscriber, allowing you to efficiently manage entity lifecycle events across your application.</p><h3>Capturing User and Request Information for Audit Logs</h3><p>To create a comprehensive audit logging system in our NestJS application, it’s essential to capture both the user responsible for changes and relevant request information, such as the user’s IP address, request URL, method, and user agent. This information provides crucial context for each logged action.<br>To achieve this, we can use <strong>Async Local Storage</strong>. This feature enables us to store and access data across different parts of our application seamlessly. Here’s how to set it up:</p><ol><li><strong>Install the Required Package</strong>: Choose your preferred package manager and install the nestjs-cls package:</li></ol><pre>npm install nestjs-cls</pre><p>2. <strong>Configure in App Module</strong>: Next, configure the ClsModule in your app.module.ts to make it available throughout your application</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { ClsModule } from &#39;nestjs-cls&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot(), // Make sure to configure TypeORM<br>    ClsModule.forRoot({<br>      global: true, // Makes it available globally without extra imports<br>      middleware: {<br>        mount: true // Use this to mount middleware for handling requests<br>      }<br>    })<br>  ],<br>  providers: [ChangeAuditSubscriber], // Register your subscriber here<br>})<br>export default class AppModule {}</pre><p>3. <strong>Setting the Current User and Request Information:</strong> To track changes made by authenticated users, we can set the current user in our <strong>AuthGuard</strong>:</p><pre>import { CanActivate, ExecutionContext } from &#39;@nestjs/common&#39;;<br>import { ClsService } from &#39;nestjs-cls&#39;;<br><br>export class AuthGuard implements CanActivate {<br>  constructor(private clsService: ClsService) {}<br><br>  async canActivate(context: ExecutionContext) {<br>    const request = context.switchToHttp().getRequest();<br>    const user = this.getUserFromAuth(); // Implement this method as per your auth strategy<br><br>    // Capture relevant request information<br>    const requestInfo = {<br>      ip: request.ip,<br>      url: request.originalUrl,<br>      method: request.method,<br>      userAgent: request.headers[&#39;user-agent&#39;],<br>    };<br><br>    this.clsService.set(&#39;user&#39;, user); // Store the user in Async Local Storage<br>    this.clsService.set(&#39;requestInfo&#39;, requestInfo); // Store request information<br><br>    return true; // Proceed if authenticated<br>  }<br>}</pre><h3>Bringing It All Together: Simple Audit Logging in NestJS</h3><p>In this section, we consolidate the concepts and implementations discussed earlier to create a simple audit logging system using TypeORM subscribers in a NestJS application. We integrate the ability to listen for entity lifecycle events — such as creation, updating, and deletion — while capturing essential user and request information for each logged action. By employing Async Local Storage, we ensure that we can track the user responsible for changes and relevant request details seamlessly.</p><pre>import {<br>  EntitySubscriberInterface,<br>  EventSubscriber,<br>  InsertEvent,<br>  UpdateEvent,<br>  RemoveEvent,<br>  SoftRemoveEvent,<br>} from &#39;typeorm&#39;;<br>import { Injectable, Inject, Logger } from &#39;@nestjs/common&#39;;<br>import { DataSource } from &#39;typeorm&#39;;<br>import { ClsService } from &#39;nestjs-cls&#39;;<br>import { AuditlogService } from &#39;src/services/auditlog.service&#39;;<br>import { AuditLog } from &#39;src/entities/audit-log.entity&#39;;<br>import { AuditLogActionEnum } from &#39;src/enums/audit-log-action.enum&#39;;<br><br>@Injectable()<br>@EventSubscriber()<br>export class AuditLogSubscriber implements EntitySubscriberInterface {<br>  private excludedEntities = [<br>   AuditLogEntity.name, // must include the table name where we are inserting log<br>  //entites that we want to ignore logging<br>  ];<br><br>  constructor(<br>    @Inject(DataSource) dataSource: DataSource,<br>    private readonly cls: ClsService,<br>    private readonly auditlogService: AuditlogService,//service that actually creates log in database<br>  ) {<br>    dataSource.subscribers.push(this);<br>  }<br><br>  private get requestInfo() {<br>    return this.cls.get(&#39;requestInfo&#39;); // Retrieve request information<br>  }<br><br>  private get user() {<br>    return this.cls.get(&#39;user&#39;); // Retrieve the current user<br>  }<br><br>  async afterInsert(event: InsertEvent&lt;any&gt;) {<br>    await this.logChange(event, AuditLogActionEnum.CREATE);<br>  }<br><br>  async afterUpdate(event: UpdateEvent&lt;any&gt;) {<br>    await this.logChange(event, AuditLogActionEnum.UPDATE);<br>  }<br><br>  async afterRemove(event: RemoveEvent&lt;any&gt;) {<br>    await this.logChange(event, AuditLogActionEnum.DELETE);<br>  }<br><br>  private async logChange(<br>    event: InsertEvent&lt;any&gt; | UpdateEvent&lt;any&gt; | RemoveEvent&lt;any&gt;,<br>    action: AuditLogActionEnum,<br>  ): Promise&lt;AuditLog | void&gt; {<br>    try {<br>      const entityName = event.metadata.targetName;<br><br>      // Don&#39;t create log for excluded entities<br>      if (this.excludedEntities.includes(entityName)) return;<br><br>      const entityBefore = event[&#39;databaseEntity&#39;];<br>      const entityAfter = event.entity;<br><br>      const [previousValue, updatedValue, recordId] = this.getPreviousAndUpdatedValues(event, action, {<br>        entityBefore,<br>        entityAfter,<br>      });<br><br>      const auditLog: AuditLog = {<br>        author: (await this.user) || entityAfter?.created_by || entityBefore?.created_by,<br>        action: action,<br>        entity_name: entityName,<br>        previous_value: previousValue &amp;&amp; Object.keys(previousValue).length ? previousValue : null,<br>        updated_value: updatedValue &amp;&amp; Object.keys(updatedValue).length ? updatedValue : null,<br>        record_id: recordId,<br>        ip_address: this.requestInfo?.ip,<br>        user_agent: this.requestInfo?.userAgent,<br>      };<br><br>      return await this.auditlogService.createLog(auditLog);<br>    } catch (err) {<br>      new Logger().error(err);<br>    }<br>  }<br><br> private getPreviousAndupdatedValues(<br>    event: InsertEvent&lt;any&gt; | UpdateEvent&lt;any&gt; | RemoveEvent&lt;any&gt;,<br>    action: AuditLogActionEnum,<br>    entityValues: {<br>      entityBefore: Record&lt;string, any&gt;;<br>      entityAfter: Record&lt;string, any&gt;;<br>    },<br>  ): [Record&lt;string, any&gt;, Record&lt;string, any&gt;, recordId: number] {<br>    let previousValue: Record&lt;string, any&gt; = {};<br>    let updatedValue: Record&lt;string, any&gt; = {};<br><br>    const { entityBefore, entityAfter } = entityValues;<br>    const recordId = entityAfter?.id || entityBefore?.id;<br>    switch (action) {<br>      case AuditLogActionEnum.CREATE:<br>        updatedValue = entityAfter;<br><br>        break;<br>      case AuditLogActionEnum.UPDATE:<br>        previousValue[&quot;id&quot;] = entityBefore ? entityBefore.id : null;<br>        updatedValue[&quot;id&quot;] = entityAfter ? entityAfter.id : null;<br><br>        event[&quot;updatedColumns&quot;].forEach((column) =&gt; {<br>          previousValue[column.propertyName] =<br>            entityBefore[column.propertyName];<br>          updatedValue[column.propertyName] = entityAfter[column.propertyName];<br>        });<br><br>        event[&quot;updatedRelations&quot;].forEach((relation) =&gt; {<br>          previousValue[relation.propertyName] =<br>            entityBefore[relation.propertyName];<br>          updatedValue[relation.propertyName] =<br>            entityAfter[relation.propertyName];<br>        });<br>        break;<br>      case AuditLogActionEnum.DELETE:<br>        previousValue = { ...event.entity, ...event[&quot;databaseEntity&quot;] };<br>        break;<br>    }<br>    return [previousValue, updatedValue, recordId];<br>  }</pre><h3>Conclusion</h3><p>While this approach provides a foundational method for implementing audit logging in a NestJS application, it’s important to note that it may not be the best or ultimate solution for every scenario. It serves well for smaller applications with simple logging requirements, but there are opportunities for optimization and enhancement.</p><p>One crucial aspect to remember is to always interact with the database using entity instances when saving, updating, or deleting data in TypeORM. Failing to follow this practice can result in subscribers being triggered without the proper entity values, leading to incomplete or misleading logs.</p><p>I also encountered some challenges during implementation, such as the @AfterUpdate lifecycle hook consistently indicating that an array or JSON field was updated, which can obscure the specific changes made. Additionally, integrating logging with queue services can introduce complexities, as these operations may not easily lend themselves to traditional logging mechanisms.</p><p>As you explore and refine your logging strategy, I encourage you to consider alternative methods or tools that may provide more robust solutions, particularly for larger or more complex applications. Continuous improvement in logging practices will help ensure that your application’s audit trail remains clear and comprehensive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63b7813eb804" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>