[英](Node.js) Splitting JS class into modules
I have a class "Firebase" in which I write all the functions (that involve this service) used in my server side.我有一个 class “Firebase”,我在其中编写了服务器端使用的所有功能(涉及此服务)。
At first, the code was pretty clean and clear, as there were not a lot of functions in this class. Now, the class is super giant (more than 100 functions not very short).起初,代码非常干净清晰,因为这个 class 中的功能并不多。现在,class 非常庞大(超过 100 个功能,不是很短)。 This is why I have decided to divide the class into modules (maybe not correct) to improve the clarity and organization of the project.
这就是为什么我决定将 class 分成模块(可能不正确)以提高项目的清晰度和组织。
Something like this:像这样:
/* 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;
What I have in mind is to organize the code in modules like "firebase-auth.js", "firebase-storage.js", "firebase-firestore.js"... and finally, require all the modules methods (or something better, because it can be a really long list of imports) and assign them to my Firebase class prototype.我的想法是在“firebase-auth.js”、“firebase-storage.js”、“firebase-firestore.js”等模块中组织代码......最后,需要所有模块方法(或其他东西更好,因为它可能是一个非常长的导入列表)并将它们分配给我的 Firebase class 原型。
My question is: If in the methods of the modules I need to use Firebase.firestore, Firebase.auth... (which are members of the Firebase class), should I create an instance of the class in each module?我的问题是:如果在模块的方法中我需要使用 Firebase.firestore、Firebase.auth...(它们是 Firebase 类的成员),我应该在每个模块中创建 class 的实例吗?
Any ideas?有任何想法吗? Thank you.
谢谢你。
try this, is not best but works as expectly试试这个,不是最好的,但可以按预期工作
create a file with functions in export module like:在导出模块中创建一个具有函数的文件,例如:
module.exports = function (app, dbConnection, firebase) {
exampleFirebaseFunction(){
}
}
and in your main file you call it as:在您的主文件中,您将其称为:
require('./routes/firebase-routes.js')(app, dbConnection, firebase);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.