TILs - 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.

Published
Author
user-image
Satya
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
Published
Author
user-image
Sudeep Hipparge
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

Code

// 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

Code

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
Published
Author
user-image
Nitturu Baba
System Analyst
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).

Code

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.

Code

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.

Code

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
Published
Author
user-image
Sudeep Hipparge
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()

Code

// 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

Code

// 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

Code

@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
Published
Author
user-image
Puneeth kumar
System Analyst
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:

Code

npm install --save @nestjs/event-emitter


Register the module in the app:

Code

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

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


Emit an event from anywhere in the app:

Code

// 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:

Code

// 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
Published
Author
user-image
Sudeep Hipparge
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

Code

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

Code

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
Published
Author
user-image
Puneeth kumar
System Analyst
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
Published
Author
user-image
Sudeep Hipparge
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:

Code

git reflog


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

2.Reset your branch back to that commit:

Code

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
Published
Author
user-image
Sudeep Hipparge
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:


Code

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
Published
Author
user-image
Sudeep Hipparge
Typescript as const turns everything into readonly.


Code

const user = {
  role: 'admin',
} as const;

user.role = 'editor'; // ❌ Error: Cannot assign to 'role' because it is a read-only property.


💡 as const is great for making values literal and immutable — useful in Redux, Enums, etc.

#Typescript #CCT1JMA0Z

Showing 4 to 5 of 82 results

Ready to Build Something Amazing?

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