Backend & DB Validators

Backend validators for database queries, array operations, object manipulation, and function utilities.

41 code snippets available

Is Array Empty

backend

Checks if array is empty or not an array.

#array#validation
ts
const isArrayEmpty = (arr: any[]): boolean => !Array.isArray(arr) || arr.length === 0;

Unique Array

backend

Removes duplicates from array.

#array#utility
ts
const unique = <T>(arr: T[]): T[] => [...new Set(arr)];

Shuffle Array

backend

Randomly shuffles array elements.

#array#random
ts
const shuffle = <T>(arr: T[]): T[] => arr.sort(() => Math.random() - 0.5);

Chunk Array

backend

Splits array into chunks of specified size.

#array#utility
ts
const chunk = <T>(arr: T[], size: number): T[][] => {
  const result: T[][] = [];
  for (let i = 0; i < arr.length; i += size) result.push(arr.slice(i, i + size));
  return result;
};

Deep Clone Object

backend

Creates a deep copy of an object.

#object#utility#clone
ts
const deepClone = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));

Pick Object Keys

backend

Creates object with only specified keys.

#object#utility
ts
const pick = <T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> => 
  keys.reduce((acc, key) => (key in obj ? { ...acc, [key]: obj[key] } : acc), {} as Pick<T, K>);

Omit Object Keys

backend

Creates object excluding specified keys.

#object#utility
ts
const omit = <T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> => 
  Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k as K))) as Omit<T, K>;

Flatten Object

backend

Flattens nested object to dot notation keys.

#object#flatten#nested
ts
const flatten = (obj: object, prefix = ''): Record<string, any> => 
  Object.entries(obj).reduce((acc, [k, v]) => {
    const key = prefix ? `${prefix}.${k}` : k;
    return typeof v === 'object' && v !== null && !Array.isArray(v)
      ? { ...acc, ...flatten(v, key) }
      : { ...acc, [key]: v };
  }, {});

Deep Merge Objects

backend

Recursively merges objects.

#object#merge#utility
ts
const deepMerge = <T extends object>(target: T, source: Partial<T>): T => {
  const result = { ...target };
  for (const key of Object.keys(source) as Array<keyof T>) {
    if (source[key] && typeof source[key] === 'object') {
      result[key] = deepMerge(result[key] as any, source[key] as any);
    } else {
      result[key] = source[key] as any;
    }
  }
  return result;
};

Debounce Function

backend

Limits function calls to once after delay.

#function#performance#utility
ts
const debounce = <T extends (...args: any[]) => any>(fn: T, delay: number): ((...args: Parameters<T>) => void) => {
  let timeoutId: ReturnType<typeof setTimeout>;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...args), delay);
  };
};

Throttle Function

backend

Limits function calls to once per interval.

#function#performance#utility
ts
const throttle = <T extends (...args: any[]) => any>(fn: T, limit: number): ((...args: Parameters<T>) => void) => {
  let inThrottle = false;
  return (...args) => {
    if (!inThrottle) {
      fn(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

Memoize Function

backend

Caches function results for same inputs.

#function#cache#performance
ts
const memoize = <T extends (...args: any[]) => any>(fn: T): T => {
  const cache = new Map<string, ReturnType<T>>();
  return ((...args) => {
    const key = JSON.stringify(args);
    if (!cache.has(key)) cache.set(key, fn(...args));
    return cache.get(key);
  }) as T;
};

Retry Function

backend

Retries async function n times on failure.

#async#error-handling#utility
ts
const retry = async <T>(fn: () => Promise<T>, retries = 3, delay = 1000): Promise<T> => {
  try {
    return await fn();
  } catch (err) {
    if (retries === 0) throw err;
    await new Promise(r => setTimeout(r, delay));
    return retry(fn, retries - 1, delay);
  }
};

Compose Functions

backend

Composes multiple functions right to left.

#function#fp#utility
ts
const compose = <T>(...fns: ((arg: T) => T)[]): ((arg: T) => T) => 
  (arg) => fns.reduceRight((acc, fn) => fn(acc), arg);

Pipe Functions

backend

Pipes value through functions left to right.

#function#fp#utility
ts
const pipe = <T>(...fns: ((arg: T) => T)[]): ((arg: T) => T) => 
  (arg) => fns.reduce((acc, fn) => fn(acc), arg);

Is Plain Object

backend

Checks if value is a plain object.

#type#check#validation
ts
const isObject = (val: unknown): val is Record<string, unknown> => 
  val !== null && typeof val === 'object' && !Array.isArray(val);

Is Function

backend

Checks if value is a function.

#type#check
ts
const isFunction = (val: unknown): val is Function => typeof val === 'function';

Is Null or Undefined

backend

Checks if value is null or undefined.

#type#check#null
ts
const isNullOrUndefined = (val: unknown): val is null | undefined => val == null;

Is Promise

backend

Checks if value is a Promise.

#type#async#promise
ts
const isPromise = <T>(val: unknown): val is Promise<T> => 
  val instanceof Promise || (!!val && typeof (val as any).then === 'function');

Camel to Snake Case

backend

Converts camelCase to snake_case.

#string#case#convert
ts
const camelToSnake = (str: string): string => 
  str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);

Snake to Camel Case

backend

Converts snake_case to camelCase.

#string#case#convert
ts
const snakeToCamel = (str: string): string => 
  str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());

Title Case

backend

Converts string to Title Case.

#string#case#format
ts
const titleCase = (str: string): string => 
  str.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());

Escape Regex

backend

Escapes special regex characters.

#string#regex#escape
ts
const escapeRegex = (str: string): string => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

Mask String

backend

Masks middle characters of string.

#string#privacy#mask
ts
const maskString = (str: string, visibleStart = 4, visibleEnd = 4): string => 
  str.slice(0, visibleStart) + '*'.repeat(Math.max(0, str.length - visibleStart - visibleEnd)) + str.slice(-visibleEnd);

MongoDB ObjectId

backend

24 hex characters.

#db#nosql
ts
const isValid = (s: string): boolean => /^[0-9a-fA-F]{24}$/.test(s);

UUID v4

backend

Standard UUID format.

#db#id
ts
const isValid = (s: string): boolean => /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(s);

CUID

backend

Collision-resistant Unique ID.

#id#db
ts
const isValid = (s: string): boolean => /^c[a-z0-9]{24}$/.test(s);

NanoID

backend

URL-friendly unique ID.

#id#db
ts
const isValid = (s: string): boolean => /^[A-Za-z0-9_-]{21}$/.test(s);

Postgres URL

backend

Connection string format.

#db#connection
ts
const isValid = (s: string): boolean => /^postgres:\/\/[^:]+:[^@]+@[^:]+:\d+\/[^\s]+$/.test(s);

Redis URL

backend

Connection string format.

#db#connection
ts
const isValid = (s: string): boolean => /^redis:\/\/[^:]+:\d+$/.test(s);

MySQL URL

backend

MySQL connection string.

#db#mysql
ts
const isValid = (s: string): boolean => /^mysql:\/\/[^:]+:[^@]+@[^:]+:\d+\/[^\s]+$/.test(s);

MongoDB URL

backend

MongoDB connection string.

#db#mongodb
ts
const isValid = (s: string): boolean => /^mongodb(\+srv)?:\/\/[^\s]+$/.test(s);

SQLite File

backend

SQLite database file.

#db#sqlite
ts
const isValid = (s: string): boolean => /^.+\.(db|sqlite|sqlite3)$/.test(s);

ULID

backend

Universally Unique Lexicographically Sortable ID.

#id#db
ts
const isValid = (s: string): boolean => /^[0-9A-HJKMNP-TV-Z]{26}$/.test(s);

KSUID

backend

K-Sortable Unique ID.

#id#db
ts
const isValid = (s: string): boolean => /^[0-9A-Za-z]{27}$/.test(s);

Snowflake ID

backend

Twitter/Discord Snowflake.

#id#distributed
ts
const isValid = (s: string): boolean => /^\d{17,19}$/.test(s);

TSID

backend

Time-Sorted Unique ID.

#id#db
ts
const isValid = (s: string): boolean => /^[0-9A-HJKMNP-TV-Z]{13}$/.test(s);

XID

backend

Globally unique identifier.

#id#db
ts
const isValid = (s: string): boolean => /^[0-9a-v]{20}$/.test(s);

Correlation ID

backend

Request correlation ID.

#tracing#id
ts
const isValid = (s: string): boolean => /^[a-f0-9]{32}$/.test(s);

Trace ID

backend

Distributed trace ID.

#tracing#distributed
ts
const isValid = (s: string): boolean => /^[a-f0-9]{32}$/.test(s);

Span ID

backend

Distributed span ID.

#tracing#distributed
ts
const isValid = (s: string): boolean => /^[a-f0-9]{16}$/.test(s);

About Backend & DB Validators

Our backend & db validation snippets are designed to handle the most common validation scenarios you'll encounter in modern software development. Each snippet is thoroughly tested, optimized for performance, and follows industry best practices.

All validators are available in multiple programming languages including JavaScript, TypeScript, Python, Go, PHP, C#, and Rust. Simply copy the code snippet, adapt it to your specific needs, and integrate it into your project. Every snippet is MIT licensed—free for personal and commercial use.

Browse Other Categories