npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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.

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

  • Decorator-Based Mapping: Define your database schema directly within your TypeScript classes using @Entity and @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, and delete operations.
    • 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: { ... } }).

📦 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 courseId is provided that doesn't exist in the courses table, it throws a [PGORM] Foreign Key Error before 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.