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 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
✨ Example:
✅ Custom Decorator:
This attaches metadata like
✅ Guard to Read Metadata
✅ Controller Usage
Under the hood, decorators use
✅ 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
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
Jun 13, 2025
Using
In NestJS, event-based communication can be implemented using
How to use it?
• Install the necessary package:
• Register the module in the app:
• Emit an event from anywhere in the app:
• Handle the event using a listener:
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
emit
in NestJSIn 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
System Analyst
Jun 10, 2025
Difference Between
🧪 While writing tests in Jest, I came across two commonly used utilities:
🔹
• 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
🔹
• 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
👉 Use
👉 Use
#jest #CCT1JMA0Z #testing
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
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
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
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
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
System Analyst
Jun 4, 2025
How to Revoke (Undo) a Git Rebase
If you’ve run a
1.Check your reflog to find the commit before rebase started:
Look for the commit hash just before the rebase (usually marked with
2.Reset your branch back to that commit:
This will reset your branch to the exact state before the rebase.
Important:
• Use
#Git
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
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:
💡 What I love:
• Built-in caching
• Automatic background refetching
• Easy-to-use API with powerful features
#CCT1JMA0Z #FrontendDevelopment
✅ 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
May 30, 2025
Typescript
💡
#Typescript #CCT1JMA0Z
as const
turns everything into readonly.
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
sudeep.hipparge
May 28, 2025
JavaScript: Object.groupBy()
Grouping data used to be messy — relying on Array.reduce() with verbose logic. But JavaScript's new Object.groupBy() method has made things incredibly elegant and easy!
With just one line, you can group array items based on any property.
It’s clean, readable, and production-friendly.
📌 Example:
💡 Output:
✅ Cleaner. ✅ Less boilerplate. ✅ Much easier to read.
#CCT1JMA0Z #WebDevelopment
Grouping data used to be messy — relying on Array.reduce() with verbose logic. But JavaScript's new Object.groupBy() method has made things incredibly elegant and easy!
With just one line, you can group array items based on any property.
It’s clean, readable, and production-friendly.
📌 Example:
const products = [
{ name: "T-shirt", category: "clothes", price: 50 },
{ name: "Apple", category: "food", price: 5 },
{ name: "Shoes", category: "clothes", price: 35 },
{ name: "Orange", category: "food", price: 7.5 },
{ name: "Blueberry", category: "food", price: 4.5 }
];
const grouped = Object.groupBy(products, product => product.category);
console.log(grouped);
💡 Output:
{
clothes: [
{ name: "T-shirt", category: "clothes", price: 50 },
{ name: "Shoes", category: "clothes", price: 35 }
],
food: [
{ name: "Apple", category: "food", price: 5 },
{ name: "Orange", category: "food", price: 7.5 },
{ name: "Blueberry", category: "food", price: 4.5 }
]
}
✅ Cleaner. ✅ Less boilerplate. ✅ Much easier to read.
#CCT1JMA0Z #WebDevelopment
sudeep.hipparge
May 28, 2025
Using Makefile for tedious commands
A Makefile can be used to automate a commands, simplifying the execution process. Here’s a concise example:
Running the Makefile
1. Create a Makefile: Save the above content as Makefile in your project directory.
2. Run Make: In your terminal, navigate to the project directory and execute:
Benefits
• Simplicity: Easily run a long command without remembering the syntax.
• Automation: Reduces manual effort and potential errors.
#cli #automation #makefile #commands
A Makefile can be used to automate a commands, simplifying the execution process. Here’s a concise example:
.PHONY: run-script
# Target to run a long command
run-script:
@echo "Running a long command..."
sleep 5 # Simulate a long-running command
@echo "Command completed."
Running the Makefile
1. Create a Makefile: Save the above content as Makefile in your project directory.
2. Run Make: In your terminal, navigate to the project directory and execute:
make run-script
Benefits
• Simplicity: Easily run a long command without remembering the syntax.
• Automation: Reduces manual effort and potential errors.
#cli #automation #makefile #commands
Vaibhav Yadav
Senior System Analyst
May 26, 2025
💡 Why is
It all comes down to type coercion and how JavaScript evaluates expressions using the
Here’s the breakdown:
So the expression becomes:
When comparing an object (like
So:
✅ Hence,
#CCT1JMA0Z
[] == ![]
true in JavaScript?It all comes down to type coercion and how JavaScript evaluates expressions using the
==
(abstract equality) operator.Here’s the breakdown:
![]
evaluates to false because an empty array is truthy, and the !
operator negates it.So the expression becomes:
[] == false
When comparing an object (like
[]
) to a boolean
with==
, JavaScript converts both sides to numbers:+[] → 0
+false → 0
So:
[] == ![]
=> [] == false
=> +[] == +false
=> 0 == 0
=> true
✅ Hence,
[] == ![]
evaluates to true.#CCT1JMA0Z
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
- Address
2nd Floor, Zee Plaza,
No. 1678, 27th Main Rd,
Sector 2, HSR Layout,
Bengaluru, Karnataka 560102 - Contact
hello@codemancers.com
+91-9731601276