【问题标题】:How to efficiently organise firestore methods and connections如何有效地组织 Firestore 方法和连接
【发布时间】:2019-06-13 03:54:43
【问题描述】:

我目前正在使用 Firebase firestore 和 Next JS。我已经用谷歌搜索了如何组织一个 firestore 项目,但其中大多数(实际上都是)不可扩展。

我尝试创建一个文件夹,其中包含所有与 Firebase 相关的组件,例如配置和实用程序方法。我发现最具挑战性的部分是编写一个通用函数来获取应用所有支持的方法的集合/文档引用,即.orderBy().limit().where().doc()。编写一个将数据库返回的数据转换为另一种格式的转换器也非常困难。

这是我已经实现的:

getDocRef.js 是一个辅助函数,将上述所有方法放在一起,getOnce.jsobserve.js 公开与数据库交互的方法,db.js 包含配置。

另外,对于任何感兴趣的人,这是我对 .getDocRef() 函数的幼稚解决方案:

import db from '../db';

/*
  Options:
  - ref: Specify the ref of a document
  - collectionName: Specify the collection name
  - queryArgs: Specify the arguments to be passed down to .where()
  - orderByArgs: Specify the arguments to be passed down to .orderBy()
  - limit: Specify the fetching limit
  - docName: Specify the document name/id
*/
export default options => {
  const { ref, collectionName, queryArgs, orderByArgs, limit, docName } = options;

  if (ref != null) return ref;

  const initRef = db.collection(collectionName);

  if (docName != null) return initRef.doc(docName);

  if (queryArgs != null) {
    if (orderByArgs != null) {
      if (limit != null)
        return initRef
          .where(...queryArgs)
          .orderBy(...orderByArgs)
          .limit(limit);
      return initRef.where(...queryArgs).orderBy(...orderByArgs);
    }
    return initRef.where(...queryArgs);
  }

  return initRef;
};

所以,我很想知道我当前的 Firebase 实现是否正常。如果不是,我应该应用什么项目结构?我应该如何改进我目前的结构以使其更有效?最后但并非最不重要的一点是,上面发布的我的幼稚 JS 解决方案是否有替代方案?提前致谢

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore next.js


    【解决方案1】:

    我个人的做法:

    • 使用dotenv 包将所有凭据提取到.env
    • 目录调用/lib/db 和两个文件:
      • init.js 初始化 Firebase/firestore
      • 另一个具有一些 CRUD 方法的类

    如果你的项目越来越大,我建议将每个集合的相关方法提取到/lib/db 中的一个文件中并在那里组织它们(有点像状态管理)。

    【讨论】:

    • 这是有道理的。在接受您的之前,我正在等待其他答案
    • 谢谢。是的,这就是我在大中型项目中所做的。在一个小文件中,如果你把它们都放在一个文件中,仍然有意义
    猜你喜欢
    • 2020-03-18
    • 1970-01-01
    • 2016-10-06
    • 2019-04-28
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    相关资源
    最近更新 更多