Building a bridge
Gradient background

Connect to Astra DB using the client

Page 3 out of 10

Learn more about the Astra DB client, how to create it and how to pass environment variables to it.

Clarice Bouwer

Software Engineering Team Lead and Director of Cloudsure

Sunday, 23 October 2022 Β· Estimated 1 minute read
Modified on Tuesday, 1 November 2022

Objectives

  1. Understand what the Astra DB Client is.
  2. Understand the need to pass environment variables to the client.
  3. Create the client in JavaScript.

Astra DB Client

You will need to be able to connect to our Astra DB collection. To do this you will create an Astra Client that will use your secret environment variables file to pass in the ID, region and app token.

When you get the collection, you need to provide the keyspace and the collection name (in this case it's the hardcoded - πŸ˜’ - sag_todos but this can be configurable).

./netlify/functions/astraClient.js
Copy
const { createClient } = require("@astrajs/collections");

let astraClient = null;

const getAstraClient = async () => {
  if (astraClient === null) {
    astraClient = await createClient(
      {
        astraDatabaseId: process.env.ASTRA_DB_ID,
        astraDatabaseRegion: process.env.ASTRA_DB_REGION,
        applicationToken: process.env.ASTRA_DB_APPLICATION_TOKEN,
      },
      30000
    );
  }
  return astraClient;
};

const getCollection = async () => {
  const documentClient = await getAstraClient();
  return documentClient
    .namespace(process.env.ASTRA_DB_KEYSPACE)
    .collection("sag_todos");
};

module.exports = { getAstraClient, getCollection };