如何移动代码以从我的文件中设置 ut DB 和集合并只需要它?

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


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

}

慕丝7291255
浏览 125回答 1
1回答

MMMHUHU

完全按照你的建议去做。将代码的上半部分移动到db.js并公开db和collection使用exports:数据库.js:const {&nbsp; &nbsp; Database} = require("arangojs");&nbsp;&nbsp;var db = new Database({&nbsp; &nbsp; url: "http://localhost:8529"});const database_name = "cool_database";&nbsp;&nbsp;db.useBasicAuth("username", "password123");db.listDatabases()&nbsp; .then(names => {&nbsp; &nbsp; if (names.indexOf(database_name) > -1) {&nbsp; &nbsp; &nbsp; db.useDatabase(database_name);&nbsp; &nbsp; &nbsp; db.get();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; db.createDatabase(database_name)&nbsp; &nbsp; &nbsp; &nbsp; .then(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; db.useDatabase(database_name);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; db.collection("my-collection").create();&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; });exports.collection = db.collection("my-collection");exports.db = db;索引.js:const {&nbsp; db,&nbsp; collection} = require("./db");const getJobFromQueue = () => {&nbsp; return db.query({&nbsp; &nbsp; &nbsp; 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",&nbsp; &nbsp; &nbsp; bindVars: {&nbsp; &nbsp; &nbsp; &nbsp; "@collection": "my-collection"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp; .then(cursor => cursor.all());}警告:请记住,您的代码中存在潜在的竞争条件。在它们被初始化之前,您可能最终会使用dband 。collection
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript