mongodb#AuthMechanism TypeScript Examples

The following examples show how to use mongodb#AuthMechanism. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: db.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
export async function connect(): Promise<void> {
  const {
    DB_USERNAME,
    DB_PASSWORD,
    DB_AUTH_MECHANISM,
    DB_AUTH_SOURCE,
    DB_URI,
    DB_NAME,
  } = process.env;

  if (!DB_URI || !DB_NAME) {
    throw new Error("No database configuration provided");
  }

  const connectionOptions: MongoClientOptions = {
    connectTimeoutMS: 2000,
    serverSelectionTimeoutMS: 2000,
    auth: !(DB_USERNAME && DB_PASSWORD)
      ? undefined
      : {
          username: DB_USERNAME,
          password: DB_PASSWORD,
        },
    authMechanism: DB_AUTH_MECHANISM as AuthMechanism | undefined,
    authSource: DB_AUTH_SOURCE,
  };

  const mongoClient = new MongoClient(
    (DB_URI as string) ?? global.__MONGO_URI__, // Set in tests only
    connectionOptions
  );

  try {
    await mongoClient.connect();
    db = mongoClient.db(DB_NAME);
  } catch (error) {
    Logger.error(error.message);
    Logger.error(
      "Failed to connect to database. Exiting with exit status code 1."
    );
    process.exit(1);
  }
}