ID Generator

Generates unique, prefixed IDs for database records

The withIdGenerator mixin adds capabilities for generating unique, prefixed IDs for your database records. This is especially useful for systems that need human-readable IDs or where exposing sequential numeric IDs is not desirable.

Usage

import { withIdGenerator } from '@doubletie/query-builder/mixins';
import { createDatabase, createModel } from '@doubletie/query-builder';
 
// Create a database and model
const db = createDatabase<Database>(/* config */);
const UserModel = createModel(db, 'users', 'id');
 
// Apply the ID generator mixin with a prefix
const UserWithIds = withIdGenerator(UserModel, { 
  prefix: 'user',
  autoGenerate: true
});
 
// Generate a unique ID
const uniqueId = UserWithIds.generateId();
console.log(uniqueId); // "user_az7GpL9..."
 
// Insert with auto-generated ID
const user = await UserWithIds.insertInto()
  .values({
    name: 'Jane Doe',
    email: 'jane@example.com'
    // id will be automatically generated
  })
  .returningAll()
  .executeTakeFirstOrThrow();
 
console.log(user.id); // "user_bK3mP8q..."
 
// Insert with explicitly generated ID
const explicitUser = await UserWithIds.insertWithGeneratedId({
  name: 'John Smith',
  email: 'john@example.com'
});

API Reference

withIdGenerator()

function withIdGenerator<
  TDatabase extends Record<string, any> = any,
  TTableName extends keyof TDatabase & string = string,
  TIdField extends keyof TDatabase[TTableName] & string = string
>(
  model: ModelFunctions<TDatabase, TTableName, TIdField>,
  options: IdGeneratorOptions = { prefix: 'id' }
): ModelFunctions<TDatabase, TTableName, TIdField> & IdGeneratorMethods

Enhances a model with ID generation capabilities.

Parameters

  • model - The base model to enhance
  • options - Configuration options for ID generation

IdGeneratorOptions

interface IdGeneratorOptions {
  /**
   * The prefix to use for generated IDs
   */
  prefix: string;
 
  /**
   * The column name to use for the ID (defaults to model's primary key)
   */
  idColumn?: string;
 
  /**
   * Whether to automatically generate IDs during insert operations
   */
  autoGenerate?: boolean;
}

Added Methods

generateId()

generateId(): string

Generates a unique ID with the configured prefix.

insertWithGeneratedId()

insertWithGeneratedId(
  data: Omit<InsertObjectOrList<TDatabase, TTableName>, TIdField>
): Promise<Selectable<TDatabase[TTableName]>>

Inserts a record with an automatically generated ID.

isGeneratedId()

isGeneratedId(id: string): boolean

Checks if an ID matches the pattern of IDs generated by this mixin.

Features

  • Customizable Prefixes: Generate IDs with meaningful prefixes (e.g., user_, post_)
  • Automatic Generation: Optionally auto-generate IDs for all insert operations
  • Custom ID Column: Specify which column should contain the generated IDs
  • Unique and Random: Generated IDs are unique and use a cryptographically strong random base

Examples

Configuration Options

// Basic configuration
const ProductModel = withIdGenerator(baseModel, { 
  prefix: 'prod'
});
 
// Advanced configuration
const OrderModel = withIdGenerator(baseModel, {
  prefix: 'order',
  idColumn: 'orderId',
  autoGenerate: true
});

Working with Generated IDs

// Generate multiple IDs
const ids = Array.from({ length: 5 }, () => UserWithIds.generateId());
 
// Check if an ID was generated by this mixin
const isGenerated = UserWithIds.isGeneratedId('user_abc123');
console.log(isGenerated); // true or false

Batch Insert with Auto-Generated IDs

const products = await ProductModel.insertInto()
  .values([
    { name: 'Product 1', price: 29.99 },
    { name: 'Product 2', price: 49.99 },
    { name: 'Product 3', price: 19.99 }
  ])
  .returningAll()
  .execute();
 
// Each product gets a unique ID
products.forEach(product => {
  console.log(`${product.name}: ${product.id}`);
});

Combining with Other Mixins

import { withIdGenerator, withUpdatedAt } from '@doubletie/query-builder/mixins';
 
// Apply multiple mixins
const ProductWithFeatures = withUpdatedAt(
  withIdGenerator(ProductModel, { prefix: 'prod' }),
  'updatedAt'
);
 
// Use methods from both mixins
const product = await ProductWithFeatures.insertWithGeneratedId({
  name: 'New Product',
  price: 99.99
});
 
console.log(product.id);        // Generated ID
console.log(product.updatedAt); // Current timestamp

On this page

doubletie.com