Quick Start

1. Install

npm install --save oor pg                           # Postgresql
# npm install --save oor pg-native                  # Postgresql / native 
# npm install --save oor mysql2                     # MySql 
# npm install --save oor @elastic/elasticsearch     # ElasticSearch 

2. Global Config

import { setup } from 'oor';
setup({ provider: { host:'1.2.3.4', port:5432, user:'postgres' ... } });

3. Define Table

// Line 1 : import oor
import { Table, UType, Static } from 'oor';

// Line 2 : Build a Schema
//          Schema can be used for validate、check, @see @sinclair/typebox
//          Some web framework support this schema, like fastify 
export const UserSchema = UType.Table({
    id: UType.Integer(),
    name: UType.String({ maxLength: 32 }),
    age: UType.Integer({ minimum: 0, maximum: 128 }),
    sex: UType.Boolean(),
    profile: UType.String({ ignore: true }),
    address: UType.String({ maxLength: 128 }),
    salary: UType.Number(),
    registerDate: UType.Date({ column: 'register_date', isCreate: true }),
    lastModify: UType.Date({ column: 'last_modify', isModify: true })
});

// Line 3 : Define a Type, you can avoid if not need this type.
export type User = Static<typeof UserSchema>;

// Line 4 : Build a Table, it's ok for all
export const User = new Table('public.user', UserSchema);

4. Table Actions

// Fetch All User
const result = await User.all();
console.log(result);

// add a user
const addResult = await User.add({
    name: 'test',
    age: 23,
    sex: false,
    address: 'randmo',
    salary: 1221.2,
});
console.log('Add Result', addResult)
let userId = addResult.id as number;


const afterAdd = await User.getById(userId);
console.log('After Add', afterAdd)

// Update a user by Id
await new Promise(r => setTimeout(r, 1200));           
// the age will changed, BTW lastModify ↑
let isUpdate = await User.update({ id: userId, age: 60, });
console.log('Update is Success ? : ', isUpdate == 1);

const afterUpdate = await User.getById(userId);
console.log('After Update', afterUpdate)

// Delete a user by Id
let isDelete = await User.deleteById(userId);
console.log('Delete is Success ? : ', isDelete == 1);

const afterDelete = await User.getById(userId); 
console.log('After Delete', afterDelete); // NULL

5. OK

All is done. See other articles for advance features.