Code Explainers

Intermediate code explainers

php
<?php
 
namespace App\Models\Concerns;
 

How an Auditable trait logs Eloquent changes in Laravel

traits model-events polymorphic-relations
Intermediate 8 steps
java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
 

Real-time chat over STOMP WebSockets in Spring

websockets stomp messaging
Intermediate 8 steps
python
import hashlib
import json
from fastapi import APIRouter, Request, Response, Depends, HTTPException, status
 

HTTP ETag caching in a FastAPI route

http-caching etag conditional-requests
Intermediate 9 steps
javascript
import { NextResponse } from 'next/server';
 
const locales = ['en', 'fr', 'de', 'es'];
const defaultLocale = 'en';

Locale routing with Next.js middleware

middleware i18n content-negotiation
Intermediate 10 steps
ruby
class ProjectsController < ApplicationController
  before_action :set_project, only: %i[show update destroy]
 
  def create

Scoping a Rails API controller to Current.account

multitenancy strong-parameters nested-attributes
Intermediate 7 steps
rust
use crossbeam_channel::{Receiver, Sender, select, tick};
use std::time::Duration;
 
pub enum Command {

A channel-driven worker loop in Rust

channels select message-passing
Intermediate 9 steps
typescript
import { Component } from '@angular/core';
import {
  trigger,
  transition,

Staggered list animations in Angular

animations stagger enter-leave
Intermediate 10 steps
java
@Configuration
@EnableRedisHttpSession(namespace = "myapp:sessions", maxInactiveIntervalInSeconds = 1800, flushMode = FlushMode.IMMEDIATE)
public class SessionConfig {
 

Backing HTTP sessions with Redis in Spring

session-management redis distributed-state
Intermediate 7 steps
python
from django.db import models
from django.db.models import Q
from django.conf import settings
 

Enforcing one default address per user in Django

data modeling database constraints partial index
Intermediate 7 steps
javascript
const express = require('express');
const cookieParser = require('cookie-parser');
 
const router = express.Router();

Remember-me login with signed cookies in Express

authentication signed-cookies sessions
Intermediate 9 steps
ruby
class SearchController < ApplicationController
  def index
    @query = params[:q].to_s.strip
  end

Live search suggestions in a Rails controller

controllers sql-injection query-building
Intermediate 6 steps
go
package health
 
import (
	"context"

Building a health check endpoint in Go

health-check context-timeout dependency-probing
Intermediate 8 steps
typescript
type Handler = (event: KeyboardEvent) => void;
 
interface Binding {
  combo: string;

Building a keyboard shortcut manager in TypeScript

event-handling normalization closures
Intermediate 7 steps
php
namespace App\Providers;
 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

Catching N+1 queries with Eloquent strict mode in Laravel

n+1 queries strict mode eager loading
Intermediate 7 steps
java
public List<User> findUsersByEmailDomain(String domain, int minAge) {
    String sql = """
        SELECT id, username, email, age, created_at
        FROM users

Safe parameterized JDBC queries in Java

jdbc sql-injection prepared-statement
Intermediate 7 steps
python
from typing import Any
 
_MISSING = object()
 

Recursively diffing two JSON structures

recursion sentinel tree-traversal
Intermediate 8 steps
javascript
const TOKEN_SPECS = [
  ["comment", /^\/\/[^\n]*|^\/\*[\s\S]*?\*\//],
  ["string", /^"(?:\\.|[^"\\])*"|^'(?:\\.|[^'\\])*'|^`(?:\\.|[^`\\])*`/],
  ["number", /^0[xX][\da-fA-F]+|^\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/],

Building a syntax highlighter tokenizer

tokenizer regular-expressions lexing
Intermediate 8 steps
javascript
export async function compressImage(file, { maxWidth = 1600, maxHeight = 1600, quality = 0.8, mimeType = 'image/jpeg' } = {}) {
  const bitmap = await createImageBitmap(file);
 
  let { width, height } = bitmap;

Compressing images in the browser with canvas

canvas image-processing promises
Intermediate 7 steps