truongbui.dev Blog and Bookmarks

website·Indexed 29 days ago

https://www.truongbui.dev/

A technical blog and curated collection of bookmarks by Truong Bui, featuring guides and tips on TypeScript, React (useEffect vs useLayoutEffect), Postgres (DISTINCT ON), Jest partial mocking, and various developer tools and patterns.

Tokens
5.7K
Snippets
47
Records
54
Agent score
47%

What's inside truongbui.dev

  1. Create custom type definitions for JavaScript modules

    When using a JavaScript library that lacks built-in TypeScript types (resulting in a 'Could not find a declaration file for module' error), you can create your own ambient module declaration. This allows you to define the types for the specific functions you use from that library without installing a third-party @types package.
    // File: types/lodash.d.ts
    declare module 'lodash' {
    	export function isString(value: any): boolean;
    }
  2. Manage RDS connections from AWS Lambda serverless functions

    Instructions and best practices for managing Amazon Relational Database Service (RDS) connections specifically within the context of AWS Lambda serverless environments.
  3. Analyze disk and cache usage with EXPLAIN BUFFERS

    Adding the BUFFERS option to EXPLAIN (ANALYZE, BUFFERS) allows you to see how many blocks were read from the PostgreSQL buffer cache versus the disk.

    • shared hit: Number of blocks read from the Postgres buffer cache.
    • read: Number of blocks read from disk.
    EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM tenk1 WHERE unique1 < 100 AND unique2 > 9000;
  4. Manage boolean flags using Python Enum Flag

    In Python (v3.6+), the enum.Flag class allows for the creation of bitwise flags to manage multiple boolean states (like permissions) within a single variable.

    • Set a flag: Use the bitwise OR operator (|=) to add a permission.
    • Check a flag: Use the bitwise AND operator (&) to verify if a specific permission is set.
    • Disable a flag: Use the bitwise XOR operator (^=) to toggle or remove a permission.
    from enum import Flag, auto
    
    class Permission(Flag):
    	NONE = 0
    	READ = auto()
    	EXECUTE = auto()
    	DELETE = auto()
    
    # Initialize
    permission = Permission.NONE
    
    # Set permissions (OR)
    permission |= Permission.READ
    permission |= Permission.EXECUTE
    permission |= Permission.DELETE
    
    # Check if READ permission is set (AND)
    is_read_set = (permission & Permission.READ == Permission.READ)  # True
    
    # Disable READ permission (XOR)
    permission ^= Permission.READ
    
    # Verify READ is now disabled
    is_read_set_now = (permission & Permission.READ == Permission.READ)  # False
  5. Use useEffect for non-blocking side effects

    Use useEffect for the majority of side effects, such as data fetching, setting up subscriptions, or manually changing the DOM where immediate visual synchronization is not required. useEffect runs asynchronously after the render is painted to the screen, ensuring that the browser can update the UI without being blocked, which maintains application responsiveness.
    import React, { useEffect, useState } from 'react'
    
    function RandomNumber () {
    	const [value, setValue] = useState(0)
    
    	useEffect(() => {
    		if (value === 0) {
    			setValue(Math.random())
    		}
    	}, [value])
    
    	return (
    		<div>
    			<h3>Random number: {value}</h3>
    			<button onClick={() => setValue(0)}>Generate</button>
    		</div>
    	)
    }
  6. Optimize PostgreSQL indexes for specific query patterns

    Follow these strategies to improve index efficiency:

    • Foreign Keys: Always create indexes for foreign keys, as PostgreSQL does not do this automatically. This optimizes nested loop joins.
    • Functional Indexes: If you query using a function (e.g., lower(column)), a standard index on the column will not be used. Create a functional index instead.
    • Pattern Matching (LIKE): B-tree indexes do not support the LIKE operator for prefix searches unless using text_pattern_ops.
    • Compound Index Order: The order of columns in a compound index matters. An index on (a, b, c) supports searches on a, (a, b), (a, b, c), and (a, c), but not on b alone or (b, c).
    • Covering Indexes: Use the INCLUDE clause to create covering indexes, enabling 'index-only scans' by storing extra data in the index and avoiding a trip to the table heap.
    -- Functional Index for case-insensitive search
    CREATE INDEX users_last_name_idx ON users (lower(last_name));
    
    -- Index for LIKE operator
    CREATE INDEX users_last_name_idx ON users (lower(last_name) text_pattern_ops);
  7. Partially mock a module function in Jest

    To mock a single function in a module while keeping the original implementation of all other exported functions, use jest.mock() in combination with jest.requireActual(). This allows you to replace a specific export with a jest.fn() while spreading the actual module's exports into the mock return object.
    import * as math from './math';
    import * as doMath from './do-math';
    
    // Partially mock the './math' module
    jest.mock('./math', () => {
      return {
        ...jest.requireActual('./math'), // Preserve original implementations
        add: jest.fn(), // Mock only the 'add' function
      };
    });
    
    describe('complexFormula', () => {
      // Create a spy on the mocked function to control its return value
      const addFunctionSpy = jest.spyOn(math, 'add');
    
      it('should return correct value', () => {
        addFunctionSpy.mockReturnValue(10);
        const result = doMath.complexFormula(1, 2);
        expect(result).toBe(8);
      });
    });