NormalJS : Node Object Relational Mapper Abstraction Layer
npm install normaljsThe simple, straightforward, and most advanced Node.js ORM — without the bloat.
Build data-rich apps with clean models, powerful relations, and first-class DX. NormalJS blends a tiny API with serious capabilities: schema sync, relations (1:n, n:m), transactions, model extension, and active-record-style instances. All in plain JavaScript.
- Simple: minimal surface area. Define models with a static fields object and go.
- Transaction-first: fully isolated repos inside transactions without leaking state.
- Advanced caching: centralized in-memory cache shared across child processes, with UDP-based clustering for peer invalidation.
- Powerful: relations (1:n, n:m), transactions, model mixins/extension, inheritance with discriminators, relation proxies.
- Productive: active records you can call methods on; lazy, ID-first reads that auto-hydrate fields; request-level caching with invalidation markers.
- Portable: works with Postgres and SQLite. Uses Knex under the hood.
- Extensible field system: add custom field types that control serialization, JSON output, schema, and lifecycle hooks.
- Model extension and overwrite: register multiple classes with the same static _name to merge fields and attach static/instance behavior over time.
- Inheritance with discriminators: share a base model schema and behavior; allocate correct child records automatically.
- Schema sync (base synchronization): generate and evolve tables from model fields with migration-safe helpers.
- Clear split of responsibilities: simple static APIs for model-level operations, and instance methods/getters for active records.



``bash`
npm install normaljs pg -y
NormalJS is written in TypeScript and includes full type definitions. TypeScript users get:
- Type-safe model definitions with autocomplete for fields and relations
- Type inference for query results and active records
- Generic types for models and records
- Declaration files (.d.ts) for all public APIs
`bash`
npm install normaljs pgTypeScript types are included - no @types package needed
`typescript`
class MyModel {
static table = 'my_table';
static fields = {
/ ... /
};
}
NormalJS supports these SQL databases via Knex:
Note: You only need the driver for the database(s) you use (e.g., pg for PostgreSQL, sqlite3 or better-sqlite3 for SQLite).
`typescript
// index.ts
import { Connection, Repository } from 'normaljs';
// 1) Create a connection (SQLite in-memory shown; Postgres or MySQL also supported)
const db = new Connection({ client: 'sqlite3', connection: { filename: ':memory:' } });
// 2) Define models
class Users {
static table = 'users';
static fields = {
id: 'primary' as const,
firstname: { type: 'string', required: true },
lastname: { type: 'string', required: true },
email: { type: 'string', unique: true, required: true },
created_at: { type: 'datetime', default: () => new Date() },
updated_at: { type: 'datetime', default: () => new Date() },
};
get name() {
return ${this.firstname} ${this.lastname};
}
}
// Override readonly 'name' property for NormalJS
Object.defineProperty(Users, 'name', { value: 'Users', configurable: true });
class Posts {
static table = 'posts';
static fields = {
id: 'primary' as const,
title: { type: 'string', required: true },
content: { type: 'string', required: true },
author_id: { type: 'many-to-one', required: true, model: 'Users' },
};
}
Object.defineProperty(Posts, 'name', { value: 'Posts', configurable: true });
// 3) Register & sync
const repo = new Repository(db);
repo.register({ Users, Posts });
await repo.sync({ force: true });
// 4) Use it
const u = await repo
.get('Users')
.create({ firstname: 'Ada', lastname: 'Lovelace', email: 'ada@example.com' });
const p = await repo.get('Posts').create({ title: 'Hello', content: 'World', author_id: u.id });
console.log(u.name); // "Ada Lovelace"
`
`js
// index.js
const { Connection, Repository } = require('normaljs');
// 1) Create a connection (SQLite in-memory shown; Postgres or MySQL also supported)
const db = new Connection({ client: 'sqlite3', connection: { filename: ':memory:' } });
// 2) Define models
class Users {
static table = 'users';
static fields = {
id: 'primary',
firstname: { type: 'string', required: true },
lastname: { type: 'string', required: true },
email: { type: 'string', unique: true, required: true },
created_at: { type: 'datetime', default: () => new Date() },
updated_at: { type: 'datetime', default: () => new Date() },
};
get name() {
return ${this.firstname} ${this.lastname};
}
}
// Override readonly 'name' property for NormalJS
Object.defineProperty(Users, 'name', { value: 'Users', configurable: true });
class Posts {
static table = 'posts';
static fields = {
id: 'primary',
title: { type: 'string', required: true },
content: { type: 'string', required: true },
author_id: { type: 'many-to-one', required: true, model: 'Users' },
};
}
Object.defineProperty(Posts, 'name', { value: 'Posts', configurable: true });
// 3) Register & sync
const repo = new Repository(db);
repo.register({ Users, Posts });
await repo.sync({ force: true });
// 4) Use it
const u = await repo
.get('Users')
.create({ firstname: 'Ada', lastname: 'Lovelace', email: 'ada@example.com' });
const p = await repo.get('Posts').create({ title: 'Hello', content: 'World', author_id: u.id });
console.log(u.name); // "Ada Lovelace"
`
Static methods live on models; instance methods live on records. You can extend models incrementally or inherit from a base model.
`js
// Extension: register the same model name again to add fields + behavior
class Users {
static _name = 'Users';
static fields = { id: 'primary' };
}
// Extend Users with fields and static/instance APIs
class UsersExt {
static _name = 'Users';
static fields = { email: 'string' };
static byEmail(email) {
return this.where({ email }).first(); // simple, model-scoped static API
}
get domain() {
return this.email?.split('@')[1] || null; // instance API on active record
}
}
// Inheritance: child model shares base structure and behavior
class Payment {
static _name = 'Payment';
static fields = { id: 'primary', amount: 'float' };
}
class CardPayment {
static _name = 'CardPayment';
static inherits = 'Payment';
static fields = { pan: 'string' };
}
repo.register(Users);
repo.register(UsersExt); // extension merged
repo.register({ Payment, CardPayment });
`
- Models
- Simple class with static _name, static table, static fields.static _name
- Extension system: register multiple times with same to add/override fields and behavior.default
- Inheritance with discriminators for polymorphic models.
- NEW: Model scopes for reusable query filters and eager loading patterns.
- Fields
- Built-ins: primary, integer/float, string/text, boolean, date/datetime, enum, json, reference.
- Constraints: , required, unique, index.static indexes = { idx_name: { fields: ['email', 'company'], unique: true } }
- Custom fields: implement serialization, JSON, schema, and lifecycle hooks.
- NEW: Model-level indexes for composite, unique, and partial indexes (e.g., ).one-to-many
- Relations
- 1:n via (e.g., comments: { type: 'one-to-many', foreign: 'Comments.post_id' }).many-to-many
- n:m via paired (auto-join table).add
- Relation proxies on instances: , remove, load.where({ 'author.organization.name': 'ACME' })
- NEW: Automatic join generation for relational filters (e.g., ).defaultScope
- Scopes
- Define reusable query patterns at the model level.
- Support for applied to all queries unless bypassed.docs/scopes.md
- Parameterized scopes via functions.
- Composable scopes with deterministic merging.
- NEW: See for comprehensive guide.repo.transaction(async (tx) => { / ... / })
- Transactions
- gives an isolated tx-bound repository.id
- Post-commit cache flush of changed records.
- Active records
- Rows are wrapped into instances; instance methods and getters work naturally.
- Default reads select only (fast), with lazy hydration from cache/DB..cache(ttl)
- Cache and discovery
- Request-level caching via and entry cache per Model:ID.$Model
- Per-model invalidation markers () to evict request caches without dropping entry caches.get_context(key, defaultValue)
- Centralized in-memory cache across processes with UDP-based clustering.
- Discovery protocol auto-syncs peer list for invalidations.
- Repository Context
- NEW: Repository-wide context accessible in transactions, models, and records.
- retrieves context values.set_context(key, value)
- stores context values.repo.sync()
- Transactions inherit parent context but modifications are isolated.
- Use cases: multi-tenancy, user context, feature flags, request metadata.
- Schema sync
- Create/update tables from model fields with .
- Migration-safe helpers for column replacement and index updates.
See full field reference in docs/fields.md.
- docs/models.md — Model definitions, inheritance, and extension system.docs/fields.md
- — Built-in field types and options.docs/scopes.md
- — NEW: Model scopes for reusable query filters.docs/requests.md
- — Request API, criteria DSL, and request-level caching.docs/relational-filters.md
- — NEW: Automatic joins for relational field filters.docs/cache.md
- — Cache architecture, connection options, discovery, and model cache options.docs/custom-fields.md
- — In-depth custom fields with hooks and a file-storage example.docs/adoption-sequelize.md
- — Step-by-step migration guide from Sequelize.
Explore demo/` for a working blog schema (Users, Posts, Tags, Comments) and a CRM and Stocks example.
The MIT License (MIT)