pg-jpa-lite
v1.0.5
Published
A lightweight, TypeScript-first JPA-style ORM for PostgreSQL, utilizing decorators for elegant data mapping and generic repositories for robust CRUD operations.
Maintainers
Readme
pg-jpa-lite 🚀
pg-jpa-lite is a high-performance, lightweight Object-Relational Mapping (ORM) library for PostgreSQL and TypeScript. It leverages the power of decorators and metadata reflection to provide a seamless, JPA-like development experience without the overhead of massive frameworks.
📑 Table of Contents
- Core Features
- Installation
- TypeScript Configuration
- Architecture Overview
- Quick Start
- Advanced Validations
- API Reference
- License
✨ Core Features
Decorator-Based Mapping: Define your database schema directly within your TypeScript classes using
@Entityand@Column.Automated Naming Strategy: Seamlessly translates camelCase class properties to snake_case database columns.
Metadata-Driven CRUD: A generic
BaseRepository<T>that understands your entity's primary keys, unique constraints, and relationships.Application-Level Safety:
- Primary Key Detection: Automatically identifies the PK for
findById,update, anddeleteoperations. - Uniqueness Guard: Prevents duplicate entry errors by pre-validating
@Column({ unique: true })fields. - Integrity Checks: Validates
@Column({ notNull: true })constraints before the query reaches the database. - Foreign Key Validation: Ensures referenced IDs exist in the parent table for
@Column({ references: { ... } }).
- Primary Key Detection: Automatically identifies the PK for
📦 Installation
Install the core package along with the required reflection library:
npm install pg-jpa-lite reflect-metadata⚙️ TypeScript Configuration
This library requires experimental decorators and metadata reflection to be enabled in your tsconfig.json. Use the following configuration for optimal performance:
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"lib": ["ES2020", "ESNext.AsyncIterable"],
"rootDir": "src",
"outDir": "dist",
/* JPA Magic (Required) */
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
/* Strictness & NPM Readiness */
"strict": true,
"strictPropertyInitialization": false,
"esModuleInterop": true,
"declaration": true,
"sourceMap": true,
"moduleResolution": "node",
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}🏗 Architecture Overview
The library operates on a Metadata Store pattern. When your application starts, the decorators register the structure of your classes. The BaseRepository then uses this store to build dynamic SQL queries at runtime.
🚀 Quick Start
1. Initialize Database Connection
First, establish a connection to your PostgreSQL database.
import { Connection } from 'pg-jpa-lite';
Connection.connect({
host: 'localhost',
user: 'shubham',
password: 'shubham123',
database: 'pgrm',
port: 5432
});2. Define Your Entity
Create a class and decorate it with entity and column metadata.
import { Entity, Column } from 'pg-jpa-lite';
@Entity("students")
export class Student {
@Column({ primary: true })
id: number;
@Column({ notNull: true })
name: string;
@Column({ unique: true, notNull: true })
email: string;
// Relational Link: courseId must exist in the 'courses' table 'id' column
@Column({
references: { table: 'courses', column: 'id' }
})
courseId: number;
}3. Implement the Repository
Initialize the repository with your entity class to perform CRUD operations.
import { BaseRepository } from 'pg-jpa-lite';
import { Student } from './entities/Student';
const studentRepo = new BaseRepository(Student);
async function manageStudents() {
try {
// SAVE: Runs all unique and foreign key checks before inserting
const newStudent = await studentRepo.save({
name: "Rahul Kumar",
email: "[email protected]",
courseId: 5
});
// FIND: Fetch by ID (detects 'id' as primary key from metadata)
const student = await studentRepo.findByID(1);
// UPDATE: Automatically excludes the primary key from the SET clause
await studentRepo.updateById(1, { name: "Rahul K. Sharma" });
// DELETE: Removes the record
await studentRepo.deleteById(1);
} catch (error) {
console.error("ORM Error:", error.message);
}
}🛡 Advanced Validations
The library provides robust error handling to ensure data integrity:
Duplicate Detection: If you attempt to save an email that already exists, the library throws a detailed
[PGORM] Duplicate Error.Foreign Key Safety: If a
courseIdis provided that doesn't exist in thecoursestable, it throws a[PGORM] Foreign Key Errorbefore the SQL execution fails.
🛠 API Reference
@Column(options: ColumnOptions)
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| primary | boolean | false | Marks the column as the primary identifier. |
| unique | boolean | false | Enforces uniqueness validation before saving. |
| notNull | boolean | false | Enforces mandatory field check. |
| name | string | snake_case | Custom database column name override. |
| references | object | undefined | Defines FK relations: { table: string, column: string }. |
📜 License
Distributed under the MIT License. See LICENSE for more information.
