[英]How to move the code to set ut DB and collection out from my file and just requre it?
So, let's say I have this code that works perfectly.所以,假设我有这个完美运行的代码。
const { Database } = require("arangojs"); var db = new Database({ url: "http://localhost:8529" }); const database_name = "cool_database"; db.useBasicAuth("username", "password123"); db.listDatabases() .then(names => { if (names.indexOf(database_name) > -1) { db.useDatabase(database_name); db.get(); } else { db.createDatabase(database_name) .then(() => { db.useDatabase(database_name); db.collection("my-collection").create(); }); } }); const collection = db.collection("my-collection"); const getJobFromQueue = () => { return db.query({ query: "FOR el IN @@collection FILTER DATE_TIMESTAMP(el.email.sendAfter) < DATE_NOW() AND el.status != 'processed' AND el.status != 'failed' SORT el.email.sendAfter LIMIT 1 RETURN el", bindVars: { "@collection": "my-collection" } }) .then(cursor => cursor.all()); }
But I want to move the top code out to another file and just require db and collection, how do I make that work?但是我想将最上面的代码移到另一个文件中,只需要 db 和集合,我该如何工作? Have been struggling to make it work for too long now.长期以来一直在努力使其工作。
const { db, collection } = require("./db"); const getJobFromQueue = () => { return db.query({ query: "FOR el IN @@collection FILTER DATE_TIMESTAMP(el.email.sendAfter) < DATE_NOW() AND el.status != 'processed' AND el.status != 'failed' SORT el.email.sendAfter LIMIT 1 RETURN el", bindVars: { "@collection": "my-collection" } }) .then(cursor => cursor.all()); }
just do exactly what you proposed.只是完全按照你的建议去做。 move the upper part of your code to db.js
and expose db
and collection
using exports
:将代码的上半部分移动到db.js
并使用exports
公开db
和collection
:
db.js:数据库.js:
const {
Database
} = require("arangojs");
var db = new Database({
url: "http://localhost:8529"
});
const database_name = "cool_database";
db.useBasicAuth("username", "password123");
db.listDatabases()
.then(names => {
if (names.indexOf(database_name) > -1) {
db.useDatabase(database_name);
db.get();
} else {
db.createDatabase(database_name)
.then(() => {
db.useDatabase(database_name);
db.collection("my-collection").create();
});
}
});
exports.collection = db.collection("my-collection");
exports.db = db;
index.js:索引.js:
const {
db,
collection
} = require("./db");
const getJobFromQueue = () => {
return db.query({
query: "FOR el IN @@collection FILTER DATE_TIMESTAMP(el.email.sendAfter) < DATE_NOW() AND el.status != 'processed' AND el.status != 'failed' SORT el.email.sendAfter LIMIT 1 RETURN el",
bindVars: {
"@collection": "my-collection"
}
})
.then(cursor => cursor.all());
}
WARNING :警告:
keep in mind, there is a potential race condition in your code.请记住,您的代码中存在潜在的竞争条件。 you may end up using db
and collection
, before they hat been initialized.在初始化之前,您可能最终会使用db
和collection
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.