Skip to content

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.

  1. Swasthik
    Boost Query Performance with Prisma's Rust-free Engine(v6.7.0+)

    Why?
    • Quick Setup
    • Faster queries
    • 85–90% bundle size reduce
    • Smoother & Better DX
    Setup Steps :

    1. Update Your schema.prisma

    Code

    generator client {
      provider        = "prisma-client-js" // or `prisma-client`
      previewFeatures = ["queryCompiler", "driverAdapters"]
      output          = "../generated/prisma"
    }


    2. Re-Generate Prisma Client

    Code

    npx prisma generate


    3. Install Driver Adapter
    • For Postgres: npm install @prisma/adapter-pg
    • For other DBs: https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/no-rust-engine#3-install-the-driver-adapter|Prisma Adapter Docs
    4. Instantiate Prisma Client
    • For Postgres:

    Code

    import { PrismaPg } from '@prisma/adapter-pg'
    import { PrismaClient } from './generated/prisma'
    
    const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
    const prisma = new PrismaClient({ adapter })


    • For other DBs: https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/no-rust-engine#4-instantiate-prisma-client|Prisma Client Docs
    5. All done!🎉 Now your can query as usual.

    🔗 https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/no-rust-engine|Official Rust-free Prisma Docs
  2. Picture-in-Picture (PiP) API – Enabling Floating Video Playback

    The Picture-in-Picture (PiP) API enables developers to present an HTML <video> element in a small, floating, always-on-top window. This allows users to continue watching a video while interacting with other applications or browser tabs.

    How to use it (basic example):

    JavaScript

    html
    
    <video id="myVideo" src="video.mp4" controls></video>
    <button id="pipButton">Enter PiP</button>



    JavaScript

    js
    
    const video = document.getElementById('myVideo');
    const button = document.getElementById('pipButton');
    
    button.addEventListener('click', async () => {
      try {
        if (document.pictureInPictureElement) {
          await document.exitPictureInPicture();
        } else {
          await video.requestPictureInPicture();
        }
      } catch (err) {
        console.error(`Failed to toggle PiP: ${err}`);
      }
    });


    Key Concepts
    • video.requestPictureInPicture(): Initiates PiP mode for the video element.
    • document.exitPictureInPicture() : Exits PiP mode.
    • document.pictureInPictureElement : Returns the element currently in PiP, or null.
    • Associated Events:
    ◦ enterpictureinpicture
    ◦ leavepictureinpicture

    JavaScript

    video.addEventListener('enterpictureinpicture', () => {
      console.log('Video entered PiP mode');
    });
    
    video.addEventListener('leavepictureinpicture', () => {
      console.log('Video left PiP mode');
    });


    ⚠️ Limitations
    • Only applicable to native <video> elements.
    • Most browsers require the video to be playing before entering PiP.
    • Must be triggered through a user gesture (e.g., a click).
    • Safari has limited support and relies on its own implementation.
    🌐 Browser Support
    • Chrome
    • Edge
    • Opera
    • Firefox (with some restrictions)
    #CCT1JMA0Z
  3. File Preview in React — Beyond Just Images
    Building a file preview system in React can surface several helpful patterns — especially when working with images, PDFs, media, and plain text files.

    • You can preview any local file before upload using:

    JavaScript

    URL.createObjectURL(file)


    It works seamlessly with:
    • Images
    • PDFs
    • Audio files
    • Videos
    • Plain text
    Tip: Always call URL.revokeObjectURL() when the preview is no longer needed to prevent memory leaks.

    🔄 Handling Local and Server Files Together
    To support previews for both uploaded and already-stored files, use a union type:

    JavaScript

    // Local preview
    { isLocal: true, file: File }
    
    // Server-hosted file
    { url: '/api/files/:id', name: string, type: string }


    Then render conditionally based on file.type. Rendering Previews Based on File Type
    • <img> → for images
    • <iframe> → for PDFs or text files
    • <audio> / <video> → for media files
    #CCT1JMA0Z #react
  4. 📌 Using Alpine.js in Rails to Toggle Content Efficiently

    You can use Alpine.js in a Rails app to handle simple UI interactions like showing, hiding, or toggling content — with zero overhead and great maintainability.

    🧠 How it works:
    • Alpine adds lightweight reactivity directly in your HTML using attributes like x-data, @click, and x-show.
    • Clicking a button updates the type (or any reactive) value.
    • Alpine automatically re-evaluates all x-show (and related) bindings when that reactive value changes.
    • It then updates the UI by toggling styles like display: none, not by re-rendering or manipulating the DOM.
    • On clicking the "Urgent" button, Alpine applies display: none to the normal_partial and removes it from urgent_partial, effectively toggling visibility between the two.
    💡 Example in Rails ERB:

    Code

    <div x-data="{ type: 'normal' }">
      <button @click="type = 'normal'">Normal</button>
      <button @click="type = 'urgent'">Urgent</button>
    
      <div x-show="type === 'normal'">
        <%= render "normal_partial" %>
      </div>
    
      <div x-show="type === 'urgent'">
        <%= render "urgent_partial" %>
      </div>
    </div>


    • Both partials are rendered server-side on initial load
    • Alpine just toggles their visibility using CSS (e.g., display: none), it wont manipulate DOM.
    • No data loss or performance bottleneck — ideal for UI tab switching or inline modals
    ✅ Why it's great:
    • No page reloads or re-renders
    • No JavaScript DOM manipulation — just CSS toggling
    • Preserves state and DOM structure
    • Ideal for tabs, modals, section toggles, and lightweight UI
    #Rails #Alphine.js
  5. Creating Google Calendar Events with NestJS

    Integrating Google Calendar event creation in a NestJS backend can be done seamlessly using the googleapis package.
    Key Steps:
    • Set up OAuth2 with access and refresh tokens.
    • Use calendar.events.insert() to create events.
    • Always include the timeZone field to ensure accurate scheduling.
    Sample code:

    JavaScript

    const event = {
      summary: 'Team Sync',
      start: { dateTime: '2025-06-26T10:00:00+05:30', timeZone: 'Asia/Kolkata' },
      end: { dateTime: '2025-06-26T11:00:00+05:30', timeZone: 'Asia/Kolkata' },
    };
    
    await calendar.events.insert({
      calendarId: 'primary',
      requestBody: event,
    });


    Common Pitfalls:
    • Incorrect scopes → leads to permission denied errors.
    • Missing timeZone → causes unexpected event timings.
    • Expired tokens → results in 401 Unauthorized errors.
    #NestJS
  6. 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:


    Code

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

    JavaScript

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

    JavaScript

    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
  9. 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
  10. 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()

    TypeScript

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

    TypeScript

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

    TypeScript

    @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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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:


    JavaScript

    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
  16. Typescript as const turns everything into readonly.


    TypeScript

    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
  17. 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:


    JavaScript

    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:


    JavaScript

    {
      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
  18. Vaibhav YadavSenior System Analyst
    Using Makefile for tedious commands

    A Makefile can be used to automate a commands, simplifying the execution process. Here’s a concise example:


    Code

    .PHONY: run-script
    
    # Target to run a long command
    run-script:
    \t@echo "Running a long command..."
    \tsleep 5  # Simulate a long-running command
    \t@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:

    Code

    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
  19. 💡 Why is [] == ![] 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:

    JavaScript

    [] == ![]  
    => [] == false  
    => +[] == +false  
    => 0 == 0  
    => true


    ✅ Hence, [] == ![] evaluates to true.

    #CCT1JMA0Z
  20. Adithya HebbarSystem Analyst
    How Dependency Injection Works in NestJS

    NestJS uses Dependency Injection (DI) to manage the creation and lifecycle of classes like services, repositories, and providers. It leverages TypeScript's metadata to resolve dependencies automatically.

    🚀 How It Works:

    • Declare Providers: Services and other classes are marked with @Injectable() to make them available for dependency injection. They are then registered as providers in a module.

    TypeScript

    // user.service.ts
    @Injectable()
    export class UserService {
      getUsers() {
        return ['Alice', 'Bob'];
      }
    }


    • Register Providers in a Module

    TypeScript

    // user.module.ts
    @Module({
      controllers: [UserController],
      providers: [UserService],
    })
    export class UserModule {}


    • Use the Service via Constructor Injection

    TypeScript

    // user.controller.ts
    @Controller('users')
    export class UserController {
      constructor(private readonly userService: UserService) {}
    
      @Get()
      findAll() {
        return this.userService.getUsers();
      }
    }


    NestJS reads the constructor types and injects the required instances for you. No manual instantiation needed!

    ✅ Benefits:
    • Decouples components
    • Simplifies testing with mocks
    • Promotes cleaner, modular code

    #nestjs #dependencyinjection #typescript

Showing page 3 of 42

Your competitors are already using AI. The question is how fast you want to unlock the value.

  • Don't know where to start?

    AI is everywhere but it's unclear which investments will actually move your metrics and which are expensive experiments.

  • Your data isn't ready

    Most AI projects fail at the data layer. Pipelines, quality, access all need work before LLMs can deliver value.

  • Internal teams are stretched

    Your engineers are shipping product. They don't have capacity to also become AI specialists with production-grade experience.

  • Legacy systems block everything

    Aging, undocumented codebases make AI integration slow, risky, and expensive. They need to move first.

Don't worry. We've got you covered.

Start with the audit.

Book a free discovery call