New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

nesto-orm

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nesto-orm

A lightweight, fast ORM for Node.js and NestJS with fluent API

latest
Source
npmnpm
Version
1.0.10
Version published
Weekly downloads
0
-100%
Maintainers
1
Weekly downloads
 
Created
Source

Nesto ORM 🚀

A lightweight, fast ORM for Node.js and NestJS with fluent API, built with TypeScript.

npm version License: MIT

✨ Features

  • 📝 Fluent API: Intuitive query builder with SQL-like syntax
  • 🔧 TypeScript First: Full TypeScript support with decorators
  • 🔄 NestJS Integration: Seamless integration with NestJS dependency injection
  • 🗄️ Multi-Database: Support for PostgreSQL, MySQL, and SQLite
  • 🛠️ CLI Tools: Powerful command-line interface for development
  • 📊 Migration System: Robust database migration management
  • 🌱 Seeding: Easy data seeding for development and testing

📦 Installation

npm install nesto-orm

🚀 Quick Start

Basic Usage

import { Nesto } from 'nesto-orm';

// Initialize Nesto
const nesto = new Nesto({
  host: 'localhost',
  port: 5432,
  database: 'myapp',
  username: 'postgres',
  password: 'password',
  dialect: 'postgresql'
});

// Connect to database
await nesto.connect();

// Simple query
const users = await nesto.table('users')
  .select('id', 'name', 'email')
  .where({ isActive: true })
  .orderBy('created_at', 'DESC')
  .limit(10)
  .get();

// Insert data
await nesto.table('users').insert({
  name: 'John Doe',
  email: 'john@example.com',
  isActive: true
});

Using Decorators

import { Table, Column, PrimaryKey, String, Integer, Date } from 'nesto-orm';

@Table('users')
export class User {
  @PrimaryKey()
  id: number;

  @String(255)
  name: string;

  @String(255)
  email: string;

  @Integer()
  age: number;

  @Date()
  createdAt: Date;
}

NestJS Integration

import { Module } from '@nestjs/common';
import { NestoModule } from 'nesto-orm';

@Module({
  imports: [
    NestoModule.forRoot({
      host: 'localhost',
      port: 5432,
      database: 'myapp',
      username: 'postgres',
      password: 'password',
      dialect: 'postgresql'
    })
  ]
})
export class AppModule {}

��️ CLI Commands

Initialize Project

npx nesto init

This command creates a new project structure with:

  • src/models/ - Directory for model files
  • src/migrations/ - Directory for migration files
  • src/config/ - Database configuration
  • package.json with required dependencies

Generate Models and Sync Database

# Generate basic model
npx nesto generate User

# Generate model with custom fields
npx nesto generate User --fields "name:string:100,email:string:unique,age:integer,is_active:boolean:default:true"

# Generate model and auto-sync to database
npx nesto generate User --auto

# Generate model with migration file
npx nesto generate User --migration

# Force sync (drop and recreate table)
npx nesto generate User --auto --force

Field Syntax:

field_name:type:length:options

Supported Types:

  • string / varchar - VARCHAR(255)
  • text - TEXT
  • integer / int - INT
  • float - FLOAT
  • decimal - DECIMAL(10,2)
  • boolean / bool - BOOLEAN
  • date - DATE
  • timestamp - TIMESTAMP
  • datetime - DATETIME
  • json - JSON
  • uuid - VARCHAR(36)

Supported Options:

  • primary - Primary key
  • auto - Auto increment
  • unique - Unique constraint
  • index - Create index
  • notnull - NOT NULL constraint
  • default:value - Default value
  • fk:table:column - Foreign key

Examples:

# User model with full fields
npx nesto generate User --fields "id:integer:primary:auto,name:string:100:notnull,email:string:unique,age:integer,created_at:timestamp:default:now,updated_at:timestamp:default:now"

# Product model with foreign key
npx nesto generate Product --fields "id:integer:primary:auto,name:string:200:notnull,price:decimal:10:2,user_id:integer:fk:users:id,created_at:timestamp:default:now"

Migration Commands

# Run all migrations and sync models
npx nesto migrate up --auto

# Run migrations only
npx nesto migrate up

# Rollback last migration
npx nesto migrate down

# Show migration status
npx nesto migrate status

# Sync models to database
npx nesto migrate sync

# Force sync (drop and recreate tables)
npx nesto migrate sync --force

# Generate migration files from models
npx nesto migrate generate

Database Studio

# Start database studio
npx nesto studio

# Specify custom port
npx nesto studio --port 3001

Database Studio provides:

  • View table lists
  • CRUD operations
  • Create new tables
  • Execute SQL queries
  • Export/Import data

📝 Usage in Code

1. Create Models

// src/models/User.ts
import { Column, Table } from 'nesto-orm';

@Table('users')
export class User {
  @Column({ type: 'integer', primaryKey: true, autoIncrement: true })
  id!: number;

  @Column({ type: 'varchar', length: 100, nullable: false })
  name!: string;

  @Column({ type: 'varchar', length: 255, unique: true, nullable: false })
  email!: string;

  @Column({ type: 'integer', nullable: true })
  age?: number;

  @Column({ type: 'boolean', default: true })
  isActive!: boolean;

  @Column({ type: 'timestamp', default: 'CURRENT_TIMESTAMP' })
  createdAt!: Date;

  @Column({ type: 'timestamp', default: 'CURRENT_TIMESTAMP' })
  updatedAt!: Date;
}

2. Database Configuration

// src/config/database.ts
import { DatabaseConfig } from 'nesto-orm';

export const databaseConfig: DatabaseConfig = {
  type: 'mysql', // 'mysql', 'postgresql', 'sqlite'
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT || '3306'),
  username: process.env.DB_USERNAME || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'nesto_db',
  synchronize: false, // Don't auto-sync in production
  logging: true,
};

3. NestJS Integration

// app.module.ts
import { Module } from '@nestjs/common';
import { NestoModule } from 'nesto-orm/nestjs';

@Module({
  imports: [
    NestoModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: '',
      database: 'nesto_db',
    }),
  ],
})
export class AppModule {}
// user.service.ts
import { Injectable } from '@nestjs/common';
import { InjectNesto } from 'nesto-orm/nestjs';
import { Database } from 'nesto-orm';
import { User } from './models/User';

@Injectable()
export class UserService {
  constructor(
    @InjectNesto() private readonly database: Database
  ) {}

  async findAll(): Promise<User[]> {
    return await this.database.query('SELECT * FROM users');
  }

  async findById(id: number): Promise<User | null> {
    const users = await this.database.query('SELECT * FROM users WHERE id = ?', [id]);
    return users[0] || null;
  }

  async create(userData: Partial<User>): Promise<User> {
    const result = await this.database.query(
      'INSERT INTO users (name, email, age, is_active) VALUES (?, ?, ?, ?)',
      [userData.name, userData.email, userData.age, userData.isActive]
    );
    return { ...userData, id: result.insertId } as User;
  }

  async update(id: number, userData: Partial<User>): Promise<User | null> {
    await this.database.query(
      'UPDATE users SET name = ?, email = ?, age = ?, is_active = ? WHERE id = ?',
      [userData.name, userData.email, userData.age, userData.isActive, id]
    );
    return this.findById(id);
  }

  async delete(id: number): Promise<boolean> {
    const result = await this.database.query('DELETE FROM users WHERE id = ?', [id]);
    return result.affectedRows > 0;
  }
}

🔧 Development Workflow

1. Initialize Project

npx nesto init

2. Create Models

# Create User model
npx nesto generate User --fields "id:integer:primary:auto,name:string:100:notnull,email:string:unique,age:integer,created_at:timestamp:default:now"

# Create Product model with foreign key
npx nesto generate Product --fields "id:integer:primary:auto,name:string:200:notnull,price:decimal:10:2,user_id:integer:fk:users:id,created_at:timestamp:default:now"

3. Sync to Database

# Sync all models
npx nesto migrate up --auto

# Or sync individual models
npx nesto generate User --auto
npx nesto generate Product --auto

4. Development and Testing

# Start database studio for management
npx nesto studio

# Check migration status
npx nesto migrate status

5. Production Deployment

# Run migrations
npx nesto migrate up

# Sync models (if needed)
npx nesto migrate sync

📚 API Reference

Query Builder

// SELECT with JOIN
const posts = await nesto.table('posts')
  .join('users', 'posts.user_id = users.id')
  .select('posts.title', 'users.name')
  .where({ 'users.isActive': true })
  .get();

// UPDATE
await nesto.table('users')
  .where({ id: 1 })
  .update({ isActive: false });

// DELETE
await nesto.table('users')
  .where({ id: 1 })
  .delete();

// COUNT
const count = await nesto.table('users')
  .where({ isActive: true })
  .count();

Where Conditions

// Complex conditions
.where({ 
  $and: [
    { isActive: true },
    { age: { $gte: 18 } },
    { email: { $like: '%@gmail.com' } }
  ]
})

// Operators
.where({ 
  age: { $gt: 18 },           // Greater than
  email: { $like: '%@gmail%' }, // LIKE
  status: { $in: ['active', 'pending'] }, // IN
  deletedAt: { $isNull: true }  // IS NULL
})

Transactions

await nesto.transaction(async (tx) => {
  await tx.table('users').insert({ name: 'John', email: 'john@example.com' });
  await tx.table('profiles').insert({ userId: 1, bio: 'Hello World' });
});

Decorators

  • @Table(tableName) - Define model and table name
  • @Column(config) - Define column with configuration
  • @PrimaryKey() - Primary key (deprecated, use Column config)
  • @Index(name, columns) - Create index

Database Methods

  • database.connect() - Connect to database
  • database.disconnect() - Disconnect from database
  • database.query(sql, params?) - Execute query
  • database.transaction(callback) - Transaction

Sync Methods

  • sync.syncModel(model) - Sync single model
  • sync.syncAllModels(models) - Sync multiple models
  • sync.dropTable(tableName) - Drop table

🗄️ Database Support

DatabaseStatusDriver
PostgreSQL✅ Full Supportpg
MySQL/MariaDB✅ Full Supportmysql2
SQLite✅ Full Supportsqlite3

🔧 Configuration

interface ConnectionConfig {
  host: string;
  port: number;
  database: string;
  username: string;
  password: string;
  dialect: 'postgresql' | 'mysql' | 'sqlite';
  ssl?: boolean;
  pool?: {
    min?: number;
    max?: number;
    acquire?: number;
    idle?: number;
  };
  logging?: boolean;
}

🧪 Testing

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

  • Fork the repository
  • Create your feature branch (git checkout -b feature/amazing-feature)
  • Commit your changes (git commit -m 'Add some amazing feature')
  • Push to the branch (git push origin feature/amazing-feature)
  • Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🆘 Support

Made with ❤️ by the Nesto ORM Team

Keywords

orm

FAQs

Package last updated on 06 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts