0

I have a method for creating a database connection, and want to keep it generic to allow calling separate query methods from it. Tried doing:

async function connectAndQuery(functionCall, config) {
  const mongoUri = `mongodb+srv://` + config.mongoUser + `:` + config[`${config.environment}MongoPassword`] + `@company-user-` + config.mongoEnvUriSection + `.mongodb.net/db-name-` + config.environment + `?retryWrites=true&w=majority`;
  const client = new MongoClient(mongoUri);

  try {
    await client.connect();
    return await functionCall(client);

Where functionCall is the name of the method with the query, but functionCall is not recognized as a function.

EDIT: Added calling code which uses the task function from Cypress IO. From plugins/index.js

module.exports = (on, config) => {

  on('task', {
    queryDb({functionCall, config}) {

      return connectAndQuery(functionCall, config)
    }
  })

  config = dotenvPlugin(config)
  return config
}

From support/index.js

cy.task('queryDb', {functionCall: 'getPasswordLink', config: Cypress.env()})
anutter
  • 366
  • 2
  • 17
  • 1
    Does this answer your question? [How to execute a JavaScript function when I have its name as a string](https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string) – O. Jones Jun 25 '20 at 22:20
  • Please show how you are calling this `connectAndQuery()` function. That's likely where the issue is. – jfriend00 Jun 25 '20 at 22:21
  • @O.Jones I did see something similar with the brackets, wasn't able to get that to work. – anutter Jun 25 '20 at 23:18
  • @jfriend00 I'm calling it using `task` function as this is a Cypress IO project: https://docs.cypress.io/api/commands/task.html#Syntax – anutter Jun 25 '20 at 23:24
  • Well, the error is that you're not properly passing a function reference to the function you show. I don't think we can help you unless we see the actual code that is calling it. – jfriend00 Jun 25 '20 at 23:50
  • Fair point, added. – anutter Jun 26 '20 at 00:15

0 Answers0