postgres

ruby
class TenantResolver
  RESERVED = %w[www app admin].freeze

  def initialize(app)
    @app = app
  end

Multi-Tenant Subdomain Isolation with Rack Middleware and Thread-Local Scoping

rails rack multi-tenancy
by codesnips 4 tabs
javascript
const MAX_LIMIT = 100;
const DEFAULT_LIMIT = 20;
const ALLOWED_ORDER = new Set(['asc', 'desc']);

function decodeCursor(raw) {
  const json = Buffer.from(raw, 'base64').toString('utf8');

Cursor-Based Pagination in Express With Query-Parsing Middleware

express pagination cursor-pagination
by codesnips 3 tabs
sql
CREATE TYPE outbox_status AS ENUM ('pending', 'retry', 'processing', 'done', 'dead');

CREATE TABLE outbox_events (
    id           BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    dedupe_key   TEXT        NOT NULL,
    topic        TEXT        NOT NULL,

Atomic “Read + Mark Processed” with UPDATE … RETURNING

postgres concurrency reliability
by codesnips 3 tabs
ruby
class CounterBuffer
  DELTA_HASH = "counter:deltas".freeze

  READ_RESET = <<~LUA.freeze
    local v = redis.call('HGET', KEYS[1], ARGV[1])
    if v then redis.call('HDEL', KEYS[1], ARGV[1]) end

Debounce Expensive Counter Cache Updates with a Throttled Redis Buffer in Rails

rails redis counter-cache
by codesnips 3 tabs
ruby
class InvoicesController < ApplicationController
  def index
    invoices = InvoicesQuery.new(current_account.invoices, filter_params).call

    @invoices = invoices.page(params[:page]).per(25)
    render :index

Building a Composable Query Object for Filtering Rails ActiveRecord Scopes

rails activerecord query-object
by codesnips 3 tabs
ruby
class AddSlugToPosts < ActiveRecord::Migration[7.1]
  def change
    add_column :posts, :slug, :string, null: false
    add_index :posts, :slug, unique: true
  end
end

Database-Backed Unique Slugs with Retry

rails postgres slugs
by codesnips 4 tabs
ruby
namespace :cleanup do
  desc "Enqueue a job to purge expired sessions"
  task expired_sessions: :environment do
    job = ExpiredSessionCleanupJob.perform_later
    Rails.logger.info("[cleanup:expired_sessions] enqueued job #{job.job_id}")
  end

Recurring Cleanup with a Rake Task and an Idempotent Active Job in Rails

rails background-jobs active-job
by codesnips 4 tabs
ruby
class AddSoftDeleteToUsers < ActiveRecord::Migration[7.1]
  def change
    add_column :users, :deleted_at, :datetime

    add_index :users, :deleted_at, where: "deleted_at IS NULL", name: "index_users_on_live"

Soft-Delete with a Default Scope, Restore Action, and Unique Index Guard in Rails

rails activerecord soft-delete
by codesnips 3 tabs
ruby
class AddSlugToArticles < ActiveRecord::Migration[7.1]
  def change
    add_column :articles, :slug, :string
    add_index :articles, :slug, unique: true

    reversible do |dir|

Auto-Generating URL Slugs in Rails with a before_validation Callback and Friendly Finder

rails activerecord slugs
by codesnips 4 tabs
ruby
module HealthCheckable
  extend ActiveSupport::Concern

  CheckResult = Struct.new(:name, :ok, :message, keyword_init: true)

  private

Rails Health-Check Endpoint With a Controller Concern and Database Ping

rails health-check monitoring
by codesnips 3 tabs
javascript
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["input", "frame"]
  static values = { url: String, delay: { type: Number, default: 300 }, min: { type: Number, default: 2 } }

Debounced Search Suggestions With a Turbo Frame Lazy-Loaded Results Partial

rails hotwire turbo
by codesnips 4 tabs
plaintext
model User {
  id        String    @id @default(uuid())
  email     String    @unique
  name      String
  posts     Post[]
  deletedAt DateTime?

Soft-Delete and Restore in TypeScript with a Prisma Repository and Migration

prisma postgres soft-delete
by codesnips 4 tabs