Loopback 4 什么是存储库?
Loopback 4 What is a Repository?
我很难理解 Loopback 4 中存储库的概念,文档说:
A Repository represents a specialized Service interface that provides strong-typed data access (for example, CRUD) operations of a domain model against the underlying database or service.
但是这个描述并不能帮助我完全理解它们背后的想法,有人可以简单地解释一下它到底是什么,并提供一些其他框架中类似概念的例子吗?
使用 ORM(对象关系映射器)框架时,我们将数据表示为模型类:
@model()
class Person {
@property()
name: string;
}
要持久化和查询数据,我们需要向我们的模型添加行为。 存储库 类 提供此类行为。
例如,LoopBack 的 EntityCrudRepository
接口描述了在 SQL tables/NoSQL 文档集合中创建、更新、删除和查询数据的方法。
// simplified version
interface EntityCrudRepository<T, ID> {
create(data: DataObject<T>): Promise<T>;
find(filter?: Filter<T>): Promise<T[]>;
updateById(id: ID, data: DataObject<T>): Promise<void>;
deleteById(id: ID): Promise<void>;
// etc.
}
KeyValueRepository
描述了 API 用于像 Redis 这样的键值存储:
interface KeyValueRepository<T> {
get(key: string): Promise<T>;
set(key: string, value: DataObject<T>): Promise<void>;
delete(key: string): Promise<void>;
}
另见 Patterns of Enterprise Application Architecture:
Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
我很难理解 Loopback 4 中存储库的概念,文档说:
A Repository represents a specialized Service interface that provides strong-typed data access (for example, CRUD) operations of a domain model against the underlying database or service.
但是这个描述并不能帮助我完全理解它们背后的想法,有人可以简单地解释一下它到底是什么,并提供一些其他框架中类似概念的例子吗?
使用 ORM(对象关系映射器)框架时,我们将数据表示为模型类:
@model()
class Person {
@property()
name: string;
}
要持久化和查询数据,我们需要向我们的模型添加行为。 存储库 类 提供此类行为。
例如,LoopBack 的 EntityCrudRepository
接口描述了在 SQL tables/NoSQL 文档集合中创建、更新、删除和查询数据的方法。
// simplified version
interface EntityCrudRepository<T, ID> {
create(data: DataObject<T>): Promise<T>;
find(filter?: Filter<T>): Promise<T[]>;
updateById(id: ID, data: DataObject<T>): Promise<void>;
deleteById(id: ID): Promise<void>;
// etc.
}
KeyValueRepository
描述了 API 用于像 Redis 这样的键值存储:
interface KeyValueRepository<T> {
get(key: string): Promise<T>;
set(key: string, value: DataObject<T>): Promise<void>;
delete(key: string): Promise<void>;
}
另见 Patterns of Enterprise Application Architecture:
Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.