【问题标题】:(Node.js) Splitting JS class into modules(Node.js) 将 JS 类拆分为模块
【发布时间】:2020-12-06 04:32:46
【问题描述】:

我有一个“Firebase”类,我在其中编写了服务器端使用的所有功能(涉及此服务)。

起初,代码非常干净清晰,因为这个类中没有很多函数。现在,这个类超级庞大(100 多个函数不是很短)。这就是为什么我决定将课程分成模块(可能不正确)以提高项目的清晰度和组织性。

类似这样的:

/* eslint-disable no-empty */
const functions = require("firebase-functions");
const admin = require("firebase-admin");

// Lazy initialization of the admin SDK
try {
     const googleCloudServiceAccount = require("../../utils/json/googleCloudServiceAccount.json");
     admin.initializeApp({
       credential: admin.credential.cert(googleCloudServiceAccount),
       databaseURL: URL,
       storageBucket: BUCKET,
     });
} catch (e) {}

class Firebase {
  constructor() {
    Object.assign(this, {
      auth: admin.auth(),
      firestore: admin.firestore(),
      storage: admin.storage(),
    });
  }
}

Object.assign(Firebase.prototype, {
  /* Methods */
});

module.exports = Firebase;

我的想法是将代码组织在“firebase-auth.js”、“firebase-storage.js”、“firebase-firestore.js”等模块中......最后,需要所有模块方法(或者更好的东西,因为它可能是一个很长的导入列表)并将它们分配给我的 Firebase 类原型。

我的问题是:如果在模块的方法中我需要使用 Firebase.firestore、Firebase.auth...(它们是 Firebase 类的成员),我应该在每个模块中创建该类的实例吗?

有什么想法吗? 谢谢。

【问题讨论】:

    标签: javascript node.js module coding-style refactoring


    【解决方案1】:

    试试这个,不是最好的,但可以按预期工作

    在导出模块中创建一个包含函数的文件,例如:

    module.exports = function (app, dbConnection, firebase) {
           exampleFirebaseFunction(){
           }
    }
    

    在你的主文件中你称之为:

    require('./routes/firebase-routes.js')(app, dbConnection, firebase);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多