codesnips

852 code snips · on codesnips 3 months
typescript
import { createContext, useContext, useEffect, useMemo, useState, ReactNode } from 'react';
import { authApi, User } from './authApi';

type Status = 'loading' | 'authenticated' | 'anonymous';

interface AuthValue {

Protect React Routes with an Auth Context and a RequireAuth Wrapper

react react-router authentication
by codesnips 4 tabs
php
<?php

namespace App\Services;

use App\Mail\VerifyEmail;
use App\Models\ContactEmail;

Signed URL Email Verification in Laravel Without the Built-in MustVerifyEmail Contract

laravel php signed-urls
by codesnips 4 tabs
rust
use serde::Serialize;
use serde_json::Value;

#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ChangeKind {

Diffing Two Config Snapshots Into a Typed Change List in Rust

rust serde config
by codesnips 3 tabs
php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

Apply and Validate Coupon Codes with a Cart Totals Service in Laravel

laravel eloquent service-layer
by codesnips 4 tabs
javascript
const { pool } = require('./db');

async function recordEvent(client, { eventId, type, payload }) {
  const { rows } = await client.query(
    `INSERT INTO webhook_events (event_id, type, payload, status)
     VALUES ($1, $2, $3, 'received')

Idempotent Stripe Webhook Processing With an Express Event-Store Middleware

express webhooks idempotency
by codesnips 3 tabs
typescript
import { useCallback, useEffect, useRef, useState } from "react";

export function useIntersectionObserver(options?: IntersectionObserverInit) {
  const [isIntersecting, setIsIntersecting] = useState(false);
  const nodeRef = useRef<Element | null>(null);
  const optionsKey = JSON.stringify(options ?? {});

Infinite-Scroll Feed with a React IntersectionObserver Hook and Cursor Pagination

react hooks intersection-observer
by codesnips 3 tabs
go
package worker

import "context"

func (p *Pool) Submit(job Job) error {
	// Reject fast if draining, otherwise enqueue with backpressure.

Graceful Drain of In-Flight Jobs Before Worker Shutdown in Go

go graceful-shutdown concurrency
by codesnips 3 tabs
java
package com.shop.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;

Guard a Checkout Endpoint with @PreAuthorize and a Custom PermissionEvaluator in Spring Boot

spring-boot spring-security authorization
by codesnips 3 tabs
python
import time
from dataclasses import dataclass
from typing import Optional

import requests

Bounded Concurrent HTTP Fan-Out With ThreadPoolExecutor and Retries

python concurrency threadpool
by codesnips 2 tabs
ruby
class ShippedEmailJob
  include Sidekiq::Job
  sidekiq_options queue: :mailers, retry: 5

  def perform(order_id)
    order = Order.find_by(id: order_id)

Fan Out Notifications to Email and SMS Using an ActiveRecord Observer

rails activerecord observer
by codesnips 3 tabs
rust
use std::collections::VecDeque;

pub struct RollingAverage {
    buf: VecDeque<f64>,
    capacity: usize,
    sum: f64,

Rolling Average Over a Sliding Window of Sensor Readings in Rust

rust sliding-window streaming
by codesnips 2 tabs
php
<?php

namespace App\Message;

final class SyncCustomerMessage
{

Retrying Flaky HTTP Calls with a Symfony Messenger Retry Strategy and Failure Handler

symfony messenger retry
by codesnips 3 tabs