codesnips

852 code snips · on codesnips 3 months
go
package api

import "fmt"

type Resource struct {
	Type       string                 `json:"type"`

Serving Paginated JSON:API Collection Responses in Go

go jsonapi pagination
by codesnips 3 tabs
rust
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CancelReason {
    pub reason: String,
    pub feedback: Option<String>,

Internally Tagged Enum JSON Serialization for a Rust Webhook API

rust serde json
by codesnips 3 tabs
javascript
const express = require('express');
const AppError = require('./AppError');
const asyncHandler = require('./asyncHandler');
const errorMiddleware = require('./errorMiddleware');
const UserRepo = require('./UserRepo');

Centralized Express Error Handling with Typed AppError and Async Wrapper

express error-handling middleware
by codesnips 4 tabs
ruby
class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record

Enforcing Controller Authorization with a Pundit-Style Policy Object in Rails

rails authorization pundit
by codesnips 4 tabs
python
import hashlib
from datetime import datetime, timezone

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

Efficient Bulk Insert in SQLAlchemy with a Reusable Chunking Helper

sqlalchemy postgres bulk-insert
by codesnips 3 tabs
typescript
import { z } from "zod";

export const rowSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1, "name is required"),
  age: z.coerce.number().int().min(0, "age must be >= 0"),

Parse a CSV Upload into Typed Rows with Per-Row Validation Errors

typescript csv validation
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
python
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models, transaction

from .middleware import get_current_user

Auditing Django Model Field Changes in an Overridden save() Method

django audit-log orm
by codesnips 3 tabs
rust
mod chunker;mod parallel_hash;

use parallel_hash::{hash_buffer, root_hash};

const CHUNK_SIZE: usize = 64 * 1024;

Content-Defined Chunking With Parallel BLAKE3 Hashing Using Rayon

rust rayon parallelism
by codesnips 3 tabs
javascript
'use strict';

const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const crypto = require('crypto');

Stream a Multipart Upload Through Gzip to Disk with stream.pipeline

nodejs streams backpressure
by codesnips 2 tabs
typescript
import { RefObject, useEffect, useRef } from "react";

type Handler = (event: MouseEvent | TouchEvent) => void;

export function useClickOutside<T extends HTMLElement>(
  ref: RefObject<T>,

Reusable useClickOutside Hook for Closing Dropdowns in React

react hooks typescript
by codesnips 3 tabs
javascript
function escapeCell(value) {
  if (value === null || value === undefined) return '';
  const str = String(value);
  if (/[",\n\r]/.test(str)) {
    return '"' + str.replace(/"/g, '""') + '"';
  }

Stream a Large CSV Export in Express with Backpressure and an Async Row Generator

express streaming csv
by codesnips 3 tabs