快速开始

1. 安装

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. 设置

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

3. 定义

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

// Line 2 : 定义一个 Schema
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 : 需要类型 Type 时,通过 Static 定义。
export type User = Static<typeof UserSchema>;

// Line 4 : 定义 Table 对象
export const User = new Table('public.user', UserSchema);

4. 操作

// 获取全部的用户
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));           
// 将会同时修改 age 和 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. 完成

一个CRUD已经跑起来了,更多内容可参考后面章节。