Ent Framework

2.26.1 · active · verified Wed Apr 22

Ent Framework is a TypeScript-first library designed for interacting with PostgreSQL databases, presenting a graph-like representation of entities rather than a traditional ORM approach. It is currently stable at version 2.26.1 and appears to be actively maintained with regular updates. Key differentiators include its robust solution for the 'N+1 selects' problem through query batching and coalescing, built-in support for microsharding and intelligent replication lag tracking to optimize read operations, and a comprehensive row-level security (privacy layer) system that defines access based on entity relationships. The framework also emphasizes immutability for entity properties and offers a pluggable architecture, allowing integration into existing database setups. It aims to simplify scaling and security concerns for complex business logic by abstracting away much of the underlying SQL complexities.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a basic 'User' Ent class, initializing the EntContext, creating a new user entity, and then loading it by ID, showcasing fundamental interaction patterns.

import { Ent, EntContext, Field, UUID, PrimaryKey, UUIDField, StringField, BooleanField, EntCreationOptions, EntQueryContext } from 'ent-framework';

interface UserData {
  id: UUID;
  name: string;
  isActive: boolean;
}

class User extends Ent<UserData> {
  @Field(UUIDField())
  id: UUID = PrimaryKey.empty();

  @Field(StringField())
  name: string = '';

  @Field(BooleanField({ defaultValue: true }))
  isActive: boolean = true;

  static create(context: EntQueryContext, data: Partial<UserData>, options?: EntCreationOptions): User {
    return super.create(context, data, options) as User;
  }

  static load(context: EntQueryContext, id: UUID): Promise<User | null> {
    return super.load(context, id) as Promise<User | null>;
  }
}

async function runExample() {
  // In a real application, DATABASE_URL would point to your PostgreSQL instance.
  // For this example, we simulate a context setup.
  const entContext = new EntContext({
    // Replace with actual database connection configuration
    // For demonstration, we'll use a placeholder URL.
    connectionUri: process.env.DATABASE_URL ?? 'postgresql://user:password@host:port/database',
    // Other configuration like sharding rules, logging, etc.
    logLevel: 'debug'
  });

  try {
    await entContext.init();
    console.log('EntContext initialized.');

    // Assume schema migration/sync is handled externally or by framework setup

    const newUser = await User.create(entContext, { name: 'Alice', isActive: true });
    console.log(`Created user: ${newUser.name} (ID: ${newUser.id})`);

    const loadedUser = await User.load(entContext, newUser.id);
    if (loadedUser) {
      console.log(`Loaded user: ${loadedUser.name}, Active: ${loadedUser.isActive}`);
    } else {
      console.log('User not found.');
    }

    // Example of another operation (e.g., updating)
    if (loadedUser) {
      const updatedUser = await loadedUser.update(entContext, { isActive: false });
      console.log(`Updated user: ${updatedUser.name}, Active: ${updatedUser.isActive}`);
    }

  } catch (error) {
    console.error('Error during example run:', error);
  } finally {
    await entContext.close();
    console.log('EntContext closed.');
  }
}

runExample();

view raw JSON →