Answer №1

Check out the Node.js driver for Cassandra.

Take a look at this code snippet that demonstrates how to connect to Amazon Keyspaces:

const cassandra = require('cassandra-driver');
const fs = require('fs');
const auth = new cassandra.auth.PlainTextAuthProvider('ServiceUserName', 'ServicePassword');
const sslOptions1 = {
    ca: [
        fs.readFileSync('path_to_file/sf-class2-root.crt', 'utf-8')],      
            host: 'cassandra.us-west-2.amazonaws.com',
                rejectUnauthorized: true
        };
const client = new cassandra.Client({
    contactPoints: ['cassandra.us-west-2.amazonaws.com'],
        localDataCenter: 'us-west-2',
        authProvider: auth,
        sslOptions: sslOptions1,
        protocolOptions: { port: 9142 }
    });

const query = 'SELECT * FROM system_schema.keyspaces';
 
client.execute(query)
    .then( result => console.log('Row from Keyspaces %s', result.rows[0]))
    .catch( e=> console.log(`${e}`));

Make sure to download the certificate for your database. For detailed instructions, refer to this guide.

If you're interested, we offer free tutorials on developing apps for Cassandra at datastax.com/dev, including example apps + complete code in Javascript and other languages. Enjoy!

Answer №2

Roshni, you can find examples on how to connect to Keyspaces in the programming language of your choice at this GitHub repository - https://github.com/aws-samples/amazon-keyspaces-example. Below is a snippet of sample code for your reference:

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0

// Define Variables
const cassandra = require('cassandra-driver');
const fs = require('fs');
const sigV4 = require('aws-sigv4-auth-cassandra-plugin');
// Custom retry policy for AmazonKeyspaces to retry on the same host
const custom_retry = require('./retry/AmazonKeyspacesRetryPolicy.js');
// Maximum number of retry attempts for custom retry
const Max_retry_attempts = 10;
require('dotenv').config();
const region = process.env.AWS_REGION;
const accessKey = process.env.AWS_ACCESS_KEY_ID;
const secretKey = process.env.AWS_SECRET_ACCESS_KEY;

// Check if environment variables are defined
if (!region) {
    console.log("Region is not set. Please set the environment variable AWS_REGION");
    process.exit(1);
}

if (!accessKey) {
    console.log("Access key is not set. Please set the environment variable AWS_ACCESS_KEY_ID");
    process.exit(1);
}

if (!secretKey) {
    console.log("Secret key is not set. Please set the environment variable AWS_SECRET_ACCESS_KEY");
    process.exit(1);
}

const auth = new sigV4.SigV4AuthProvider({
    region: region,
    accessKeyId: accessKey,
    secretAccessKey: secretKey
});

const host = 'cassandra.' + region + '.amazonaws.com';
const sslOptions = {
    ca: [
        fs.readFileSync(__dirname + '/resources/sf-class2-root.crt')
    ],
    host: host,
    rejectUnauthorized: true
};

const client = new cassandra.Client({
    contactPoints: [host],
    localDataCenter: region,
    authProvider: auth,
    sslOptions: sslOptions,
    queryOptions: { isIdempotent: true, consistency: cassandra.types.consistencies.localQuorum },
    policies: { retry: new custom_retry.AmazonKeyspacesRetryPolicy(Max_retry_attempts) },
    protocolOptions: { port: 9142 }
});

const query = 'SELECT * FROM system_schema.keyspaces';

const result = client.execute(query).then(
    result => console.log('Row from Keyspaces %s', result.rows[0])
).catch(
    e => console.log(`${e}`)
);

Promise.allSettled([result]).finally(() => client.shutdown());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The HTML modal window is experiencing loading issues

I am attempting to implement a modal box that appears on click in an HTML document. The HTML code looks like this: <a href="#openModal">Open Modal</a> <div id="openModal" class="modalDialog"> </div> <a href="#openModal">O ...

Comparing the size of a MongoDB array to another field in a document: how can it be done?

Need guidance on querying MongoDB for documents that have a specific number of users in them. This needs to be done through both the mongo console and JavaScript in Node.js: db.turnys.find( { users:{$size:seats } } ) The structure of turnydb.turnys colle ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...

Running only failed tests in Protractor can be achieved by implementing a custom script that

I've encountered a problem in my JavaScript file where some of the test cases fail intermittently, and I want to rerun only those that have failed. Is there any feature or solution available that can help with this issue? It's quite frustrating a ...

Send two arguments to a personalized validation function using express-validation

I have a requirement to input two values in order to search for a subdocument using the main document ID and then another ID of the subdocument. These IDs are received as parameters, and I am utilizing express-validator with a custom function to ensure th ...

What is the process of making circle or square shapes with text inside using React, without the use of SVG images?

Is there a way to create circle and square shapes in React with custom text inside, without relying on SVG images? Check out this example: https://i.sstatic.net/iHZgy.png I attempted the code below but it did not render any shapes: import React from &apos ...

Use multer-ftp to change the name of a file

I've been working on uploading a file to an FTP server using multer-ftp. The file is successfully uploaded, but I need to change the name of the file. Is there a way to accomplish this? var upload = multer({ storage: new FTPStorage({ basepath: ...

Tips for increasing a cell in AG Grid React table:

Just starting out with the AG Grid library and encountering issues when updating the cells. To simplify, I will describe my problem using basic numbers instead of dates. Start is set to 1. Stop value is already established. End needs to be determined. Dur ...

Exploring face detection with Three.js

When I utilize an octree, I am able to generate an array of faces that are in close proximity to an object. However, I am unsure how to perform a ray cast to these faces. All the resources I have found only explain how to ray cast to a mesh, line or poin ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

`How can I trigger a JavaScript event when the content of an input field is modified?`

Currently, I am working on implementing validation in JavaScript. My goal is to provide the user with an alert whenever they modify the value of an input field. <input type="text" name="onchange" id="onchange" size="35" maxlength="50" /> ...

conceal the mustard-colored dots within the overlay

Whenever I trigger the link, a modal window pops up, but it comes with an unwanted black background color and yellow dots. How can I prevent the yellow dots from showing up on the overlay? http://jsfiddle.net/y88WX/18/embedded/result/ <nav class="da-d ...

"Seamlessly Integrating AngularJS with WebGL for Stunning Canvas Inter

I am new to AngularJS and curious about its compatibility with HTML5 Canvas or WebGL. Are there any tutorials available on how to integrate AngularJS into a view that uses these technologies? I have noticed some games claiming to be developed with Angular ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

Refreshing data in AngularJs is like pressing the reset button for

My database contains a list of customers who joined in different years. I have configured my API accordingly and it works smoothly. The issue I am facing is that when using AngularJS to pull the data with the same route (/customers/:id), it doesn't re ...

What is the proper way to invoke a variable-function in Node.js?

I have a function called `findPeopleByName` that queries the database for a specific username, but I'm not sure how to call it in my Node.js code. Here's what I have so far: // Retrieve user_name from POST request. app.post("/api/exercise/new-u ...

Can one verify if an Angular application currently has active app modules running?

I am developing a unique plugin for Angular that is designed to automatically initialize an Angular app module if none are found. However, if there is already a running or declared ng-app, my plugin will utilize that existing module instead. Here is an i ...

Transmit an unmodifiable array using JSON and Ajax

Is there a way to transmit arrays in a non-editable format? The data I wish to transmit looks like this: var items = []; //console.log(JSON.stringify(items)); allitems = JSON.stringify(items); [{ "assetid": "7814010469", "classid": "1797256701", ...

Enhancing vanilla HTML elements with custom props using React

const handleSelectChange = (e) => { console.log(e.target.getAttribute('id')); }; return ( <div> <select onChange={(e) => handleSelectChange(e)}> <option value="1-10" id=&qu ...

How can I prevent overwriting previous input data in LocalStorage using Draftjs?

I have implemented a draftjs rich text editor to store my text input in local storage. The current functionality allows me to enter text and save it to local storage by clicking the save button. See the code snippet below: import React from "react"; impor ...