Nexorm
  • Getting Started
  • Schema
    • What is Schema?
    • Decorator's
  • Column
    • What is Column?
    • Decorator's
  • Core
  • Method's
    • Finder Method's
      • $search
      • $searchOne
      • $searchFirst
      • $searchById
      • $searchByIds
      • $searchAndCount
      • $distinct
      • $everything
      • $count
      • $query
    • Updater Method's
      • $update
      • $updateMany
      • $upsert
      • $restore
    • Creation Method's
      • $build
      • $buildMany
    • Deletion Method's
      • $delete
      • $deleteMany
      • $softDelete
      • $softDeleteMany
      • $truncate
  • Operator's
    • Search Operator's
      • $eq
      • $ne
      • $gt
      • $gte
      • $lt
      • $lte
      • $between
      • $notBetween
      • $in
      • $notIn
      • $like
      • $notLike
      • $startsWith
      • $endsWith
      • $substring
      • $and
      • $or
      • $is
      • $not
      • $overlap
      • $contains
      • $contained
      • $any
      • $regexp
      • $notRegexp
      • $iLike
      • $notILike
      • $adjacent
    • Update Operator's
      • String Operator's
        • $append
        • $prepend
        • $replace
        • $trim
        • $substr
        • $capitalize
        • $reverse
        • $slice
        • $lowercase
        • $uppercase
        • $camelcase
        • $kebabcase
        • $snakecase
        • $titlecase
      • Number Operator's
        • $inc
        • $dec
        • $mul
        • $div
        • $min
        • $max
        • $sqrt
        • $floor
        • $random
        • $abs
        • $ceil
        • $pow
        • $toFixed
        • $toExponential
        • $toPrecision
        • $round
        • $trunc
        • $mod
      • Boolean Operator's
        • $toggle
      • Object Operator's
        • $omit
        • $merge
        • $mapKeys
        • $mapValues
        • $invert
      • Array Operator's
        • $push
        • $pop
        • $pull
        • $addToSet
        • $sliceArray
        • $concat
      • Global Operator's
        • $set
        • $unset
        • $clear
    • Rules Operator's
    • Options Operator's
  • Hook's
    • $beforeCreate
    • $afterCreate
    • $beforeFind
    • $afterFind
    • $beforeUpdate
    • $afterUpdate
    • $beforeDestroy
    • $afterDestroy
    • $beforeSave
    • $afterSave
    • $beforeBulkCreate
    • $afterBulkCreate
    • $beforeBulkUpdate
    • $afterBulkUpdate
    • $beforeBulkDestroy
    • $afterBulkDestroy
Powered by GitBook
On this page
  • Features
  • Installation
  • TypeScript Configuration
  • Quick Start
  • Configuration File Options
  • Create Model
  • Updating in the database
  • Searching in the database
  • Deleting in the database

Getting Started

NextSchema

Last updated 2 months ago

NexORM is a powerful ORM designed to simplify database management while delivering high performance and flexibility. Inspired by , , and , it combines the best features of these tools, offering advanced operators (like $set and $inc with more), a built-in caching system, and a decorator-based schema definition for clean and intuitive modeling.

With full TypeScript support, Nexorm ensures type-safe , modern development using JavaScript (ES2021). It supports MySQL, PostgreSQL, SQLite, MariaDB, and MSSQL, making it suitable for projects of any scale, from small apps to complex enterprise systems.

Start building with NexORM to enjoy effortless, scalable, and maintainable database interactions.

Features

  • Full Type Support: Seamless TypeScript integration for type-safe development.

  • Decorator-Based Schema Definition: Clean and intuitive schema modeling using decorators.

  • Multi-Database Support: Compatible with MySQL, PostgreSQL, SQLite, MariaDB, and MSSQL.

  • Full JSON Support: Easily handle arrays and objects in JSON format.

  • Hooks Support: Lifecycle hooks for enhanced control over database events.

  • Encryption, Decryption, and Hashing: Built-in utilities for secure data management.

  • Validation Support: Ensure data integrity with powerful validation tools.

  • Multi-Connection Support: Manage multiple database connections effortlessly.

  • CLI Support: Command-line tools for streamlined database operations.

  • Cache Support: Built-in caching for faster queries and improved performance.

  • Index Support: Optimize queries with advanced indexing capabilities.

  • Advanced Operator Support: Extendable operators for flexible database operations.

  • Debug and Logging Support: Track and troubleshoot with detailed logs and debug tools.

And more...

With NexORM your schemas & models look like this:

/* ./schemas/user.ts */
import Model from 'nexorm/model';
import { 
  Schema, Timestamps, 
  Column, Default, Required 
} from 'nexorm/decorators';

@Schema
@Timestamps /* UpdatedAt And CreatedAt Sections */
class UserSchema {

@Column
@Required
static personName = String; /* Required String Column */

@Column
@Required
static personSurname = String; /* Required String Column */

@Column
@Default(16)
static personAge = Number; /* Number Column If Value Is Not Available */
                            /* Value Is Set To '16' */

@Column
@Default(['Personal'])
static tags = Array(String); /* String[] Column If Value Is Not Available */
                                 /* Value Is Set To '["Personal"]' */

@Column
static audit = Object; /* Object Column */

};

/* Integrating The Schema Into The Model And Exporting */
export default new Model(UserSchema);

And your domain logic will look this way:

import User from './schemas/user';

const allUsers = await User.$everything();
const firstUser = await User.$searchFirst();

const filteredUsers = await User.$search({
   $where: {
         personName: 'John',
         personAge: {
             $gte: 18
         }
   }
});

const findUser = await User.$searchOne({
    $where: {
        tags: {
            $in: [['Personal']]
        }
    },
    $options: {
        $sort: {
            personAge: -1
        }
    }
});

Installation

  1. Install the npm package: npm install nexorm --save

  2. You may need to install reflect-metadata: npm install reflect-metadata --save and import it somewhere in the global place of your app (for example in src/index.ts): import 'reflect-metadata';

  3. You may need to install node typings: npm install @types/node --save-dev

  4. Install a database driver:

    • for MySQL npm install mysql2 --save

    • for PostgreSQL npm install pg --save

    • for SQLite npm install sqlite3 --save

    • for Microsoft SQL Server npm install tedious --save

    • for MariaDB npm install mariadb --save

TypeScript Configuration

Also, make sure you are using TypeScript version 4.5 or higher, and you have enabled the following settings in tsconfig.json:

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

You may also need to enable es6 in the lib section of compiler options, or install es6-shim from @types.

Quick Start

The quickest way to get started with NexORM is to use its CLI commands to generate a nexorm.config.ts or nexorm.config.js file.

nexorm init /* With Selection Prompts */
nexorm init -y /* Skip All Prompts */
nexorm init --database sqlite --language ts --babel false /* For Manuel */

After edit the nexorm.config.ts or nexorm.config.js file and put your own database connection configuration options in there:

/* nexorm.config.ts */

/* eslint-disable @typescript-eslint/no-var-requires */
/** @type {import('nexorm').NexormConfig} */
import type { NexormConfig } from "nexorm";

export default [{
    $provider: "nexorm",
    $database: "sqlite",
    $databaseEngine: "InnoDB",
    $filePath: "./nexorm.sqlite",
    $autoConnect: true,
    $onConnection: () => {
        console.log("[Nexorm] Database ready!");
    },
    $onError: (error: Error) => {
        console.error("[Nexorm] Error connecting to database:", error);
    },
}] satisfies NexormConfig;

Configuration File Options

You can adjust the configuration file according to your needs using the table below.

Value
Type
Default

$provider*

'nexorm' | String

nexorm

$database*

'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql'

sqlite

$dialectModule?

any

(Empty)

$autoConnect?

Boolean

true

$filePath?

String

./nexorm.sqlite

$databaseEngine?

String

B-tree

$ssl?

Boolean

(Empty)

$pool?

Object

(Empty)

$pool.$acquire?

Number

(Empty)

$pool.$idle?

Number

(Empty)

$pool.$max?

Number

(Empty)

$pool.$min?

Number

(Empty)

$pool.$evict?

Number

(Empty)

$onConnection?

Function

(() ⇒ {..});

$onDisconnect?

Function

(Empty)

$onError?

Function

(() ⇒ {..});

$host?

String

(Empty)

$port?

String

(Empty)

$username?

String

(Empty)

$password?

String

(Empty)

$connectionURI?

String

(Empty)

$cache?

Object

(Empty)

$cache.$type?

'memory'

(Empty)

$cache.$duration?

Number

(Empty)

Create Model

Working with a database starts with creating tables. How do you tell NexORM to create a database table? The answer is - through the models. Your models in your app are your database tables.

For example, you have a Member model:

@Schema
class Member {

@Column
@UUID()
static userId = String;

@Column
static username = String;

@Column
static displayName = String;

@Column
static age = Number;

@Column
static avatar = Buffer;

@Column
static banner = String;

@Column
static createdAt = Date;

@Column
static lastJoinedAt = Date;

@Column
@Hash('SHA256','hex')
static password = String;

@Column
@Default(false)
static isPremium = Boolean;

@Column
static badges = Array(String);

@Column
static logins = { timestamp: Number, ip: String };

};

export default new Model(Member);

And you want to store photos in your database. To store things in the database, first, you need a database table, and database tables are created from your models. Not all models, but only those you define as entities.

Updating in the database

Now let's update a member from the database:

import Member from './schemas/Member';
import * as fs from 'fs';



/* Update Or Create Row */
var upsertedMember = await Member.$upsert({
    $where: {
        isPremium: true
    },
    $update: {
        $toggle: {
            isPremium: true
        },
        $camelcase: {
            username: true
        }
    },
    $rules: {
        username: {
            $alphaNumeric: true
        }
    }
});


/* Update One Row */
await Member.$update({
    $where: {
        userId: '1234567890',
        username: 'fivesobes'
    },
    $update: {
        $set: {
            avatar: fs.readFileSync(path.join(__dirname, 'avatar.png')),
            lastJoinedAt: new Date()
        },
        $toggle: {
            isPremium: true
        },
    },
    $options: { $upsert: true }
});


/* Update Many Rows */
await Member.$updateMany({
    $where: {
        isPremium: true,
        badges: {
            $in: [['Verify', 'VIP']]
        }
    },
    $update: {
        $set: {
            badges: []
        },
        $toggle: {
            isPremium: true
        }
    },
});

Searching in the database

Now let's search a member from the database:

import Member from './schemas/Member';


/* Search All */
var allMembers = await Member.$everything();


/* Search One */
var member = await Member.$searchOne({
    $where: {
        userId: '1234567890',
    },
    $options: {
        $attributes: ['userId','username','displayName','avatar','banner'],
        $raw: true
    }
});


/* Search Many */
var memberList = await Member.$search({
    $where: {
        isPremium: true
    },
    $options: {
        $sort: {
            lastJoinedAt: -1,
            createdAt: -1
        },
        $limit: 30,
        $cache: true
    }
});


/* Search By Id */
var searchMemberById = await Member.$searchById('7ca9320b-1803-459c-a1ff-39b8d5e14a25');


/* Search By Ids */
var searchMembersByIds = await Member.$searchByIds([
    '7ca9320b-1803-459c-a1ff-39b8d5e14a25',
    '7ca9320b-1803-459c-a1ff-39b8d5e14a26',
    '7ca9320b-1803-459c-a1ff-39b8d5e14a27'
]);


/* Distinct Rows */
var memberListDistinct = await Member.$distinct({
    $field: ['userId','username','displayName'],
    $options: {
        $cache: { $key: 'memberList', $ttl: 60_000 }
    }
});


/* Get Count */
var count = await Member.$count({
    $where: {
        lastJoinedAt: {
            $gte: new Date('2021-01-01')
        }
    },
    $options: {
        $paranoid: true
    }
});


/* Search And Get Count */
var [ members, count ] = await Member.$searchAndCount({
    $where: {
        createdAt: {
            $lte: new Date('2021-01-01'),
            $gte: new Date('2020-01-01')
        }
    }
});

Deleting in the database

Now let's delete a member from the database:

import Member from './schemas/Member';


/* Delete All */
await Member.$truncate();


/* Delete One */
var deletedMember = await Member.$delete({
    $where: {
        userId: '1234567890',
        isPremium: {
            $eq: false
        }
    }
});


/* Delete Many */
var deletedMembers = await Member.$deleteMany({
    $where: {
        isPremium: false,
        banner: {
            $startsWith: '.png'
        }
    },
    $options: {
       $limit: 40,
       $logging(sql, benchmark) {
            console.log(`${sql} took ${benchmark}ms`);
       },
       $force: true
    }
});


/* Soft Delete One */
await Member.$softDelete({
    $where: {
        username: 'fivesobes'
    }
});


/* Soft Delete Many */
await Member.$softDeleteMany({
    $where: {
        isPremium: false
    },
    $options: {
        $limit: 5
    }
});
MongoDB
Prisma
TypeORM
Page cover image