python
import datetime as dt

from sqlalchemy import Column, DateTime, Integer, String, UniqueConstraint
from sqlalchemy.orm import declarative_base

Base = declarative_base()

Idempotent Webhook Ingestion With a Postgres Dedupe Store in FastAPI

fastapi webhooks idempotency
by codesnips 3 tabs
javascript
const { WebSocketServer } = require('ws');
const crypto = require('crypto');

const wss = new WebSocketServer({ port: 8080 });

function broadcast(payload, except) {

Reconnecting WebSocket Chat Client with a Broadcasting Node Server

websocket realtime reconnection
by codesnips 3 tabs
ruby
class Cart < ApplicationRecord
  belongs_to :user, optional: true
  has_many :cart_items, dependent: :destroy

  scope :for_session, ->(token) { where(session_token: token) }
  scope :active, -> { where(merged_at: nil) }

Merge a Guest Cart Into a User's Cart on Login With a Rails Service Object

rails service-object devise
by codesnips 3 tabs
typescript
export const TOTAL_STEPS = 3;

export interface WizardData {
  email: string;
  password: string;
  fullName: string;

Typed Multi-Step Wizard Form With a useReducer State Machine in React

react typescript usereducer
by codesnips 4 tabs
php
<?php

namespace App\Http\Controllers;

use App\Models\Wallet;
use App\Services\WalletService;

Debit a Wallet Balance Safely with Row Locking in Laravel

laravel eloquent transactions
by codesnips 4 tabs
javascript
const jwt = require('jsonwebtoken');

function authenticate(req, res, next) {
  const header = req.headers.authorization || '';
  const [scheme, token] = header.split(' ');

Role-Based Access Control in Express with a requireRole Middleware Factory

express middleware rbac
by codesnips 3 tabs
go
package upload

import (
	"bufio"
	"errors"
	"fmt"

Streaming Multipart Upload Handler With MIME Sniffing in Go

go http multipart
by codesnips 3 tabs
java
public record User(Long id, String email, String displayName, boolean active) {

    public static User of(String email, String displayName) {
        return new User(null, email, displayName, true);
    }

Efficient JDBC Batch Inserts With addBatch, executeBatch, and Generated Keys

jdbc batch-insert postgres
by codesnips 3 tabs
typescript
import sharp from 'sharp';

export interface Variant {
  name: string;
  width: number;
  quality: number;

Generate WebP Image Thumbnails on Upload with Sharp and Express

express sharp image-processing
by codesnips 3 tabs
javascript
import { useCallback, useMemo, useState } from 'react';

function compare(a, b) {
  if (typeof a === 'number' && typeof b === 'number') return a - b;
  return String(a ?? '').localeCompare(String(b ?? ''));
}

Building a Paginated, Sortable Data Table with a useTable Hook in React

react hooks pagination
by codesnips 3 tabs
python
import logging
from typing import Awaitable, Callable, List, Tuple

log = logging.getLogger("saga")

Compensation = Callable[[], Awaitable[None]]

Saga-Style Rollback With a Context-Managed Compensating Action Stack

saga rollback context-manager
by codesnips 3 tabs
rust
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum WebhookEvent {
    #[serde(rename = "payment.succeeded")]

Tagged Webhook Deserialization and Typed Handler Dispatch in Rust with Serde

webhooks serde axum
by codesnips 3 tabs