简体   繁体   中英

Requiring the same module twice in Node.js

I'm trying to write a serverless function to get and set data on FaunaDB. The problem is, FaunaDB throws an error if a try to create a collection with a name that already exists. So, before getting or setting the data, I first need o check if a collection exists, and create it if it doesn't.

So, I've my setup like this:

setupFauna.js :

const faunaDB = require('faunadb')

module.exports = async function setupFauna(secret, collectionName) {

  const requiredDB = new faunaDB.Client({
    secret: secret
  })

}

// rest of the code

functions/setData.js and functions/getData.js :

const faunaDB = require('faunadb')
const setupFauna = require('../setupFauna')

const faunaSecret = process.env.FAUNADB

const requiredDB = new faunaDB.Client({
  secret: faunaSecret
})

exports.handler = async () => {

  return setupFauna(faunaSecret, collectionName).then(() => {

    // rest of the code

  }

}

setData.js and getData.js are independent of each other and thus, they require the independent import of FaunaDB module. Both of them need the FaunaDB module in the rest of the code. However, since both of them depend on setupFauna.js which is already importing the same Node Module, is there a way to avoid the duplication of import? I'm not sure if what I'm doing is correct or not. From my understanding, I'm basically importing the same thing twice in the resultant setData.js and getData.js . Also, I'm having to configure the FaunaDB client in all these 3 files. This does seem error prone to me.

Can someone confirm if what I've currently setup is a good way to go or is there something I can do to make this optimal? Is importing the same thing multiple times a good idea? I understand it's not a problem when you require the same thing multiple times in the same file, but does that stand true for my case too?

From all the comments, it seems like it's not really required, but to simplify the process and make it less error-prone, I followed @hor53's comment and created another export.

So now I've my files like this:

setupFauna.js :

const faunaDB = require('faunadb')

const requiredDB = new faunaDB.Client({
  secret: process.env.FAUNADB
})

async function setupFauna(collectionName) {

  // rest of the code

}

module.exports = {
  faunaDB,
  requiredDB,
  setupFauna
}

functions/setData.js and functions/getData.js :

const faunaDB = require('../setupFauna').faunaDB
const commentsDB = require('../setupFauna').requiredDB
const setupComments = require('../setupFauna').setupFauna

exports.handler = async () => {

  return setupFauna(collectionName).then(() => {

    // rest of the code

  }

}

I'd be up to know if there's a better process or if I've missed something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM