Unable to set database URL dynamically in Sails.js

30 Views Asked by At

I am working on a Sails.js application where I need to dynamically set the database URL for my Mongodb database in the datastore configuration at runtime. The idea is to get the database URL with username and password from a common service. The database URL is fetched from an external service (Infisical) during the application's bootstrap phase. However, despite successfully fetching and setting the database URL in the sails.config.datastores.default.url , it seems like Sails does not recognize or apply this dynamic configuration, and my application fails to connect to the database with the dynamically set URL.

Here's the relevant part of my bootstrap configuration in config/bootstrap.js:

module.exports.bootstrap = async function (done) {
  console.log('Fetching database URL from Infisical');
  try {
    const dbConfig = await InfisicalService.fetchDatabaseUrl();
    console.log('Fetched database URL from Infisical', dbConfig.secret.secretValue);

    // Update the Sails datastore configuration with the fetched URL
    sails.config.datastores.default.url = dbConfig.secret.secretValue; // Assumes matching response structure from Infisical
    return done();
  } catch (error) {
    console.error('Failed to fetch database URL from Infisical', error);
    return done(error);
  }
};

And my config/datastores.js initially looks like this, prepared for dynamic updates:

module.exports.datastores = {
  default: {
    adapter: 'sails-mongo',
    // url: `mongodb://localhost:27017/mydatabase`, // This is supposed to be set dynamically in bootstrap
  },
};

Issue: When I lift the Sails application,and the URL is datastore.js is wrong or commented, it fails to connect to the database and doesn't recognize the newly set database URL at all, acting as if no URL was set. I have confirmed through logs that the URL is being fetched correctly and that the code to set the url in sails.config.datastores.default.url is executed.

Questions:

  1. Is there a specific reason why Sails.js might not recognize or apply a dynamically set database URL in the datastore configuration?
  2. Are there any known workarounds or correct approaches to dynamically setting the database URL in Sails.js after fetching it at runtime?

Any insights or guidance on how to correctly implement this functionality in Sails.js would be greatly appreciated.

0

There are 0 best solutions below