首页 > 解决方案 > Realm,React Native 嵌入对象示例

问题描述

我正在寻找使用 Realm 和 React Native + TypeScript 使用嵌入式对象的任何具体示例。

通常,您可以提供部分属性对象以发送到领域以进行 CRUD 操作:

realm.write(() => {
  realm.create<SomeSchemaObject>(
    SchemaObject.schema.name,
    {
        id: 1,
        someListType: ??? // where someListType is an embedded schema object.
    },
    UpdateMode.Modified
  )
}

使用打字稿并为嵌入对象提供一组部分属性,我得到类型错误。我已经浏览了 Realm-JS 存储库和文档,但似乎没有任何使用打字稿和嵌入式对象的示例。

标签: typescriptreact-nativerealm

解决方案


在问这个问题之前,我应该自己更努力地挖掘。无论如何,我设法弄清楚了。对于一个小设置,我不直接在我的应用程序中使用领域实体,我实际上将这些实体转换为 DTO。我的 DTO 都实现了一个接口,该接口定义了一种方法来获取插入/更新操作的属性对象。以前我将返回对象键入为 Partial,而实际上我应该使用 RealmInsertionModel。

希望这对其他人有一些帮助。

toRealmInsertionModel(): RealmInsertionModel<UserSessionEntity> {
    // In my schema UserSessionEntity has an embedded list of ScopeEntity.
    const entities: RealmInsertionModel<ScopeEntity>[] = this.scopes.map(
      scopeDto => scopeDto.toRealmInsertionModel(),
    );

    return {
      id: this.id,
      accessToken: this.accessToken,
      refreshToken: this.refreshToken,
      idToken: this.idToken,
      tokenType: this.tokenType,
      scopes: entities,
    };
}

推荐阅读