0

所以,假设我有这个完美运行的代码。

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());
}

但是我想将顶部代码移到另一个文件中,只需要 db 和 collection,我该如何让它工作?一直在努力让它工作太久了。

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());
}

4

1 回答 1

1

完全按照你的建议去做。将代码的上半部分移动到db.js并公开dbcollection使用exports

db.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:

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());
}

警告

请记住,您的代码中存在潜在的竞争条件。在初始化之前,您可能最终会使用dband 。collection

于 2020-09-10T08:38:49.163 回答