python
from alembic import op
import sqlalchemy as sa

revision = "20240612_add_status"
down_revision = "20240515_create_orders"
branch_labels = None

Zero-Downtime NOT NULL Column Backfill with Alembic and SQLAlchemy

alembic sqlalchemy migrations
by codesnips 2 tabs
ruby
class User < ApplicationRecord
  normalizes :phone, with: ->(value) { PhoneNormalizer.call(value) }, apply_to_nil: false

  validates :phone,
            presence: true,
            uniqueness: { case_sensitive: false },

Normalizing Phone Numbers on Assignment with Rails normalizes and a Custom Serializer

rails activerecord normalization
by codesnips 3 tabs
typescript
import { useMemo } from "react";

export type SortDir = "asc" | "desc";
export interface SortConfig<T> {
  key: keyof T;
  dir: SortDir;

Memoized Async Search With a Cached Selector Hook in React

react hooks usememo
by codesnips 3 tabs
java
public class ProductAggregator implements AutoCloseable {

    private final RemoteServices services;
    private final ExecutorService pool = Executors.newFixedThreadPool(8);

    public ProductAggregator(RemoteServices services) {

Coordinate Parallel Remote Lookups With CompletableFuture in Java

java completablefuture concurrency
by codesnips 3 tabs
rust
use std::time::Duration;
use tokio_util::sync::CancellationToken;

pub struct Worker {
    id: usize,
    token: CancellationToken,

Graceful Task Shutdown in Tokio Using CancellationToken

tokio async cancellation
by codesnips 3 tabs
typescript
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bull';
import { ScheduleModule } from '@nestjs/schedule';
import { DigestProducer } from './digest.producer';
import { DigestProcessor } from './digest.processor';

Scheduling and Processing Email Digests with a Bull Queue in NestJS

nestjs bull redis
by codesnips 3 tabs
php
<?php

use App\Http\Controllers\DocumentsController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth')->group(function () {

Soft Deletes with a Trash View and Restore Route in Laravel

laravel eloquent soft-deletes
by codesnips 4 tabs
python
from datetime import datetime, timedelta, timezone

from jose import jwt, JWTError
from jose.exceptions import ExpiredSignatureError

SECRET_KEY = "change-me-in-production"

FastAPI JWT Authentication with Access/Refresh Tokens and a Verification Dependency

fastapi jwt authentication
by codesnips 3 tabs
javascript
const crypto = require('crypto');

function computeSignature(secret, timestamp, payload) {
  return crypto
    .createHmac('sha256', secret)
    .update(`${timestamp}.${payload}`, 'utf8')

Verify Stripe-Style Webhook Signatures With HMAC in Express Before Processing

webhooks hmac security
by codesnips 2 tabs
rust
use chrono::NaiveDate;
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer};

#[derive(Debug, Clone, Deserialize)]
pub struct Transaction {

Aggregate CSV Transaction Totals per Category With Serde and csv Crate

rust csv serde
by codesnips 3 tabs
typescript
import { useEffect, useState } from "react";

export function useDebouncedValue<T>(value: T, delay = 300): T {
  const [debounced, setDebounced] = useState<T>(value);

  useEffect(() => {

Debounced Search Box With AbortController to Cancel Stale Fetches in React

react hooks debounce
by codesnips 3 tabs
php
<?php

declare(strict_types=1);

namespace App\Security;

PHP Login Rate Limiting with a Sliding-Window Throttle Middleware

php rate-limiting middleware
by codesnips 3 tabs