Leoric是一个类似 Active Record 的 JavaScript 的 ORM 模块,从一个内部版本中重构出的方案。先前在 reddit.com/r/node发过一则广告帖,要回答的第一个问题应该都是差不多的,就是“Leoric 和市面上现有的 JavaScript ORM 模块相比优势在哪?”
Leoric 非常新,在性能方面测试还不充分,就目前而言,它的优势在于它的 API 非常简单而且强大。例如在编写查询条件时,遇到 ||
复合条件的时候,用 mongoose 或者 knex 可能需要这样写:
Table.find({ $or: [ { foo: null }, { foo: values } ] })
// or with knex
Table.where({ foo: null }).orWhere({ foo: values })
用 Leoric 只需:
Table.find('foo = null or foo = ?', values)
如果还要考虑伪删除(不真正 DELETE 记录,而是使用 deleted_at
字段标记),在 mongoose 或者 knex 里是:
// MongoDB-like
Table.find({ $and: [ { $or: [ { foo: null }, { foo: values } ] }, { deletedAt: null }]
// formatted
Table.find({
$and: [
{
$or: [
{ foo: null },
{ foo: values }
]
}
]
})
// or with knex
Table.where(function() {
this.where({ foo: null }).orWhere({ foo: values })
}).andWhere({ deletedAt: null })
在 Leoric 里则是:
Table.find('(foo = null or foo = ?) and deletedAt is null', values)
另一个可以体现 Leoric 和其他 ORM 模块区别的地方是关联关系的配置与使用,以 Objection.js 为例,要设置一个 belongsTo
关联:
class Animal extends Model {
static relationMappings = {
owner: {
relation: Model.BelongsToOneRelation,
modelClass: Person,
join: {
from: 'animal.ownerId',
to: 'person.id'
}
}
}
}
在 Leoric 里则是:
class Animal extends Bone {
static describe() {
this.belongsTo('owner', { Model: 'Person' })
}
}
Leoric 是我在 2017 年交出的两份 Node.js 答卷之一,希望能给各位 Web developer 带来帮助。欢迎阅读官方介绍文档、以及 Github