Fueling Curiosity, One Insight at a Time

At Codemancers, we believe every day is an opportunity to grow. This section is where our team shares bite-sized discoveries, technical breakthroughs and fascinating nuggets of wisdom we've stumbled upon in our work.

Jun 20, 2025
Understanding ExecutionContext in NestJS Guards

Today I learned how ExecutionContext works in NestJS — it's a powerful tool for accessing low-level request details within Guards, Interceptors, and Custom Decorators.
While building a custom AuthGuard, I used ExecutionContext to extract the request object and retrieve the authenticated user like so:



import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;

    return !!user; // or apply custom authorization logic
  }
}


Why It Matters:
ExecutionContext wraps the current request lifecycle and gives you flexible access to request-specific information.
• You can switch between different transport layers (HTTP, RPC, WebSockets) using methods like switchToHttp(), switchToRpc(), etc.
• It's essential for building dynamic and context-aware logic in guards, interceptors, and decorators.
Pro Tip:
Use context.getClass() and context.getHandler() to access metadata about the controller and handler being executed — especially useful for implementing role-based access control or custom permission systems.

#CCT1JMA0Z #NestJS
sudeep.hipparge
sudeep.hipparge
Jun 19, 2025
the term Cannibalization in warehouse terms meaning taking components or parts from one unit (often damaged, unused, or scrapped) to use in repairing or completing another unit.
In simple terms we can understand it as refubrished items where later the warehouse can send that to a buyer and then the buyer decide which store to sell these items in a discounted price.

#warehouse #outbound
satya
satya
Jun 18, 2025
JavaScript Temporal — A Modern Approach to Date & Time

Today I explored the Temporal API in JavaScript — a long-awaited, modern alternative to the built-in Date object.
The traditional Date API is known for its limitations: it’s mutable, difficult to work with across time zones, and error-prone when performing date arithmetic. Temporal addresses these issues with a clean, consistent, and powerful API.

Key Advantages of Temporal
Immutable: All Temporal objects are immutable, avoiding side effects
Time zone-aware: Native support via ZonedDateTime
Consistent parsing & formatting
Clear duration handling with Temporal.Duration
More intuitive syntax — no more 0-based months
Practical Examples


// Get current date-time
const now = Temporal.Now.plainDateTimeISO();
console.log(now.toLocaleString()); // "6/18/2025, 6:01:52 PM"

// Time zone conversion
const nyMeeting = Temporal.ZonedDateTime.from('2025-06-18T10:00[America/New_York]');
const kolkataTime = nyMeeting.withTimeZone('Asia/Kolkata');
console.log(kolkataTime.toLocaleString()); // "6/18/2025, 7:30:00 PM GMT+5:30"


Working with Durations


const start = Temporal.PlainDate.from('2025-01-01');
const end = Temporal.PlainDate.from('2025-06-18');
const diff = start.until(end);
console.log(diff.toLocaleString()); // "168 days"


Why This Matters ?
Whether you're building scheduling systems, handling international time zones, or performing complex date calculations — the Temporal API offers accuracy, clarity, and reliability that the current Date API lacks.

#CCT1JMA0Z
sudeep.hipparge
sudeep.hipparge
Jun 17, 2025
The difference between Active Model association call, joins and includes. Consider two tables: order_requests and orders, where each order_request has many orders.

1. order_request.orders
Purpose: You’re accessing the associated orders from a single order_request object.
Behavior: This will trigger a separate SQL query unless the association was already loaded (using includes).


SELECT "orders".* FROM "orders" WHERE "orders"."order_request_id" = 123;


• Use Case: When you’re working with one order_request and want to fetch its orders.

2. order_requests.joins(:orders)
Purpose: Adds an INNER JOIN in the SQL between order_requests and orders.
Behavior: Doesn't load orders into memory, just uses them for filtering or sorting in SQL.


SELECT "order_requests".* 
FROM "order_requests"
INNER JOIN "orders" ON "orders"."order_request_id" = "order_requests"."id";


• Use Case: When you want to query order_requests based on conditions in orders (e.g., where(orders: { status: 'active' })), but don’t need to access orders in Ruby.

3. order_requests.includes(:orders)
Purpose: Performs eager loading via a LEFT OUTER JOIN + separate query, or just a separate query depending on ActiveRecord's optimization.
Behavior: Loads orders for each order_request to prevent N+1 queries when looping.


SELECT "order_requests".* FROM "order_requests" WHERE ...
SELECT "orders".* FROM "orders" WHERE "order_request_id" IN (1, 2, 3, ...)


• Use Case: When you plan to access order_request.orders for many records in a loop and want to avoid repeated SQL calls (N+1 issue).

#Rails
nitturu.baba
Nitturu Baba
System Analyst
Jun 13, 2025
How Decorators Work in NestJS

Decorators in NestJS are a powerful way to attach metadata to routes, classes, or parameters. Today, I implemented a custom @Roles() decorator to control access to certain routes based on user roles.

Example:

Custom Decorator: @Roles()


// roles.decorator.ts
import { SetMetadata } from '@nestjs/common';

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);


This attaches metadata like roles = ['Admin'] to the route handler.

Guard to Read Metadata


// roles.guard.ts
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.get<string[]>(
      'roles',
      context.getHandler()
    );

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    return requiredRoles?.includes(user?.role); // Check if user has the role
  }
}


Controller Usage


@UseGuards(RolesGuard)
@Roles('Admin')
@Patch(':id')
updateOrg() {
  // This route is accessible only to users with the 'Admin' role
}


Under the hood, decorators use Reflect.defineMetadata to attach metadata, and NestJS’s Reflector service helps retrieve that metadata in guards or interceptors.

Takeaway: Custom decorators make your code cleaner, declarative, and easier to manage — especially when dealing with role-based access in multi-user systems.

#typescript #NestJs
sudeep.hipparge
sudeep.hipparge
Jun 13, 2025
Using emit in NestJS

In NestJS, event-based communication can be implemented using @nestjs/event-emitter package, which is built on top of eventemitter2 . It's particularly useful for decoupling the parts of our application — for example, sending notifications, logging, or triggering async jobs after certain actions.

How to use it?

Install the necessary package:


npm install --save @nestjs/event-emitter


Register the module in the app:


// app.module.ts
import { EventEmitterModule } from '@nestjs/event-emitter';

@Module({
  imports: [
    EventEmitterModule.forRoot(),
  ],
})
export class AppModule {}


Emit an event from anywhere in the app:


// user.service.ts
import { EventEmitter2 } from '@nestjs/event-emitter';

@Injectable()
export class UserService {
  constructor(private eventEmitter: EventEmitter2) {}

  async createUser(userDto: CreateUserDto) {
    const user = await this.userRepository.save(userDto);
    
    this.eventEmitter.emit('user.created', user); // 🔥

    return user;
  }
}


Handle the event using a listener:


// user.listener.ts
import { OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class UserListener {
  @OnEvent('user.created')
  handleUserCreatedEvent(payload: any) {
    console.log('User created!', payload);
    // Trigger welcome email, analytics, etc.
  }
}


Why use emits?

Decouples the core logic from side-effects
Makes it easier to add/remove behaviours like notifications, logging
Encourages modular architecture

#CCT1JMA0Z #nestJs #event_based_communication
puneeth.kumar
Puneeth kumar
System Analyst
Jun 10, 2025
Difference Between jest.fn() and jest.spyOn() in Jest

🧪 While writing tests in Jest, I came across two commonly used utilities: jest.fn() and jest.spyOn(). They may seem similar, but they serve different purposes:

🔹 jest.fn()
• Creates a new mock function from scratch
• Ideal when you want to replace a function with a mock implementation entirely
• Commonly used to inject mocked dependencies in unit tests


const mockFn = jest.fn();
mockFn('arg'); 
expect(mockFn).toHaveBeenCalledWith('arg');


🔹 jest.spyOn()
• Spies on an existing method of an object
• Allows you to observe calls to the method or mock its implementation, while retaining the original object structure


const obj = {
  greet: () => 'Hello',
};

const spy = jest.spyOn(obj, 'greet');
obj.greet();
expect(spy).toHaveBeenCalled();


👉 Use jest.fn() when creating mocks from scratch.
👉 Use jest.spyOn() to observe or override existing methods.

#jest #CCT1JMA0Z #testing
sudeep.hipparge
sudeep.hipparge
Jun 4, 2025
Recover Lost Data in PostgreSQL

Most SQL databases, like PostgreSQL, let us restore the database to a specific point in time — this is called Point-In-Time Recovery (PITR). PostgreSQL makes this possible using something called the Write-Ahead Log (WAL).

The WAL keeps a log of every change made to the database, like adding, updating, or deleting the data. Each of these log has a unique ID called as Log Sequence Number (LSN). This allows PostgreSQL to rebuild the database exactly as it was at any moment in the past.

However, PostgreSQL doesn’t keep these logs forever. A background process automatically removes old WAL files when they’re no longer needed to save space.

#postgreSQL #databases
puneeth.kumar
Puneeth kumar
System Analyst
Jun 4, 2025
How to Revoke (Undo) a Git Rebase

If you’ve run a git rebase and need to undo it due to issues, here’s a simple way to revert back:

1.Check your reflog to find the commit before rebase started:


git reflog


Look for the commit hash just before the rebase (usually marked with rebase started).

2.Reset your branch back to that commit:


git reset --hard <commit-hash>


This will reset your branch to the exact state before the rebase.

Important:
• Use git reset --hard with caution, as it will discard any uncommitted changes.
#Git
sudeep.hipparge
sudeep.hipparge
Jun 2, 2025
React Query

It simplifies data fetching, caching, syncing, and updating — without manually managing loading or error states.
Here’s a small snippet I worked on today:



import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

const fetchOrganisations = async () => {
  const { data } = await axios.get('/api/organisations');
  return data;
};

const Users = () => {
  const { data, isLoading, error } = useQuery(['organisations'], fetchOrganisations);

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error fetching organisations</p>;

  return (
    <ul>
      {data.map(organisation => (
        <li key={organisation.id}>{organisation.name}</li>
      ))}
    </ul>
  );
};


💡 What I love:
• Built-in caching
• Automatic background refetching
• Easy-to-use API with powerful features
#CCT1JMA0Z #FrontendDevelopment
sudeep.hipparge
sudeep.hipparge

Showing 1 to 5 of 79 results

Ready to Build Something Amazing?

Codemancers can bring your vision to life and help you achieve your goals