【问题标题】:Typesafe implementation of Firebase Firestore's `where`Firebase Firestore 的 `where` 的类型安全实现
【发布时间】:2021-07-17 05:59:15
【问题描述】:

我正在编写一个类型安全的构建器包来包装名为 Fireproof 的 Firestore 原语。我目前正在用我自己的自定义FireQuery.where 包装Query.where ,我希望它是完全类型安全的。 Firestore where 的函数声明为

Query where(
    dynamic field, {
    dynamic isEqualTo,
    dynamic isNotEqualTo,
    dynamic isLessThan,
    dynamic isLessThanOrEqualTo,
    dynamic isGreaterThan,
    dynamic isGreaterThanOrEqualTo,
    dynamic arrayContains,
    List<dynamic>? arrayContainsAny,
    List<dynamic>? whereIn,
    List<dynamic>? whereNotIn,
    bool? isNull,
  }) {/*...*/}

但是当我围绕一个特定模型或文档生成代码时,我知道所有可能的字段及其类型,所以我不希望任何东西是动态的。但是,我想不出一种方法来利用它或函数调用的样子。

考虑到我有一个用户文档,这是一个示例

class UserDoc {
  final int age;

  final String city;

  UserDoc(this.age, this.city);
}

还有一个用户查询:

/// Generated Code
class UserQuery implements FireQuery {
  // ...

  UserQuery where(
    // I know the only fields possible are age and city therefore
    // I want the comparators to be typed to whatever is the selected field.
    //
    // E.g. If the user somehow selects age, isEqualTo should be isEqualTo<String>
  ) {
    // TODO
  }
}

有什么想法可以做到这一点吗?

编辑

我弃用了该软件包,转而支持 Firestore 的原生 withConverters,并得出了相同的结论,即如果没有部分类或对 api 进行重大更改,这是不可能的

【问题讨论】:

    标签: flutter google-cloud-firestore code-generation


    【解决方案1】:

    您的第一个链接无效。您是否删除了项目?

    您引用的代码的动态部分可以适应您想要执行的任何查询。因此,如果用户选择年龄,您只需要以下内容:

    CollectionReference colref = Firestore.instance
        .collection("usersCollection");
    
    Query nameQuery = colref.where('age', isEqualTo: 'TheAgeYouWant');
    
    

    它会自动设置为 Age 的值。使用 FlutterFire 代码的意义在于不必创建自己的自定义查询,我认为它不会真正产生任何好处或优势。

    【讨论】:

    • 是的,该软件包已被弃用,取而代之的是 withConverters。更改背后的作者同意,如果没有目前正在开发的一些语言功能,目前就不可能拥有我的想法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多