如何有效地组织 firestore 方法和连接

How to efficiently organise firestore methods and connections

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

我试图做的是拥有一个文件夹,其中包含所有与 Firebase 相关的组件,例如配置和实用程序方法。我发现最具挑战性的部分是编写一个通用函数来获取应用所有支持方法的 collection/document ref,即 .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 解决方案的方法?提前致谢

我个人的做法:

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

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