RDB.js 是适用于 Node.js 和 Typescript 的终极对象关系映射器,可与 Postgres、MS SQL、MySQL、Sybase SAP 和 SQLite 等流行数据库无缝集成。无论您是使用 TypeScript 还是 JavaScript(包括 CommonJS 和 ECMAScript)构建应用程序,RDB 都能满足您的需求。
RDB.js:https://rdbjs.org/
$ npm install rdb
这里我们选择 SQLite。
npm install sqlite3
map.js 地图.js
import rdb from "rdb";
const map = rdb
.map((x) => ({
customer: x.table("customer").map(({ column }) => ({
id: column("id")
.numeric()
.primary()
.notNullExceptInsert(),
name: column("name").string(),
balance: column("balance").numeric(),
isActive: column("isActive").boolean(),
})),
order: x.table("_order").map(({ column }) => ({
id: column("id")
.numeric()
.primary()
.notNullExceptInsert(),
orderDate: column("orderDate").date().notNull(),
customerId: column("customerId")
.numeric()
.notNullExceptInsert(),
})),
orderLine: x.table("orderLine").map(({ column }) => ({
id: column("id").numeric().primary(),
orderId: column("orderId").numeric(),
product: column("product").string(),
})),
deliveryAddress: x
.table("deliveryAddress")
.map(({ column }) => ({
id: column("id").numeric().primary(),
orderId: column("orderId").numeric(),
name: column("name").string(),
street: column("street").string(),
postalCode: column("postalCode").string(),
postalPlace: column("postalPlace").string(),
countryCode: column("countryCode").string(),
})),
}))
.map((x) => ({
order: x.order.map((v) => ({
customer: v.references(x.customer).by("customerId"),
lines: v.hasMany(x.orderLine).by("orderId"),
deliveryAddress: hasOne(x.deliveryAddress).by(
"orderId"
),
})),
}));
export default map;
update.js 更新.js
import map from "./map";
const db = map.sqlite("demo.db");
updateRow();
async function updateRow() {
const order = await db.order.getById(2, {
lines: true,
});
order.lines.push({
product: "broomstick",
});
await order.saveChanges();
}
filter.js 过滤器.js
import map from "./map";
const db = map.sqlite("demo.db");
getRows();
async function getRows() {
const filter = db.order.lines
.any((line) => line.product.contains("broomstick"))
.and(db.order.customer.name.startsWith("Harry"));
const orders = await db.order.getMany(filter, {
lines: true,
deliveryAddress: true,
customer: true,
});
console.dir(orders, { depth: Infinity });
}