Guest Post by:
Dave Rubin, Senior Director, NoSQL, and Embedded Database Development, Oracle

I recently posted a hello world example coded in Python and showed how easy it was for Python developers to get started with the Oracle NoSQL Database cloud.  In this post, I will show the same hello world example coded in JavaScript, and if you are a Javascript developer and already have access to the Oracle Cloud, I believe you will also be able to be up and running in 10 minutes or less by using the Oracle NoSQL Database Cloud service with the JavaScript SDK.

In the very first “hello world” post, I also talked about why you might want to use a NoSQL Database for certain applications.   For that discussion, you can check out the post here 15-minutes-to-hello-world.  The remainder of this post will focus on writing JavaScript code for your first Oracle NoSQL Database cloud application.

Getting Started with the Oracle NoSQL Database Cloud Service

The Oracle NoSQL Database Cloud Service is a server-less, fully managed data store that delivers predictable single-digit response times and allows the application to scale on-demand via provisioning API calls.  There are five simple steps to getting started with the Oracle NoSQL Database Cloud Service.

  1. Download the Oracle NoSQL Database SDK

  2. Create a compartment for your table (if you do not want your table in the root compartment)

  3. Connect to the Oracle NoSQL Database cloud service

  4. Create a table with provisioned reads/sec, writes/sec, and GB storage

  5. Write data to the table and read data from the table

Furthermore, you can use free cloud credits to do all of this and not pay a single penny. 

Once you have created a cloud account, you can either navigate to the Oracle NoSQL Database table management console or if you are like most developers, quickly move onto writing your first hello world code.  For this release of the Oracle NoSQL Database Cloud Service, you can write your first hello world program using Python, Node.js, Java, or Go.  Future releases of the service will support C++, C#, and other popular programming languages.  I will use JavaScript, running in Node.js for the remainder of this blog.

Download the Oracle NoSQL Database SDK

Since access to the Oracle NoSQL Cloud Service is via HTTP, you can run your application directly on your laptop and connect to the database service over the internet.  While I would never recommend using the internet as a network transport for performance-sensitive applications, it works perfectly for our hello world example.  In fact, it is likely that you would want to deploy a real application by running inside your own tenancy, co-located in the same Oracle Cloud Infrastructure region as your Oracle NoSQL table, and use the Oracle Cloud Infrastructure Service Gateway to connect to the NoSQL Cloud Service.

Like other open-source JavaScript packages, you can find the Oracle NoSQL Database JavaScript SDK at npm.  NOTE that the JavaScript SDK is intended for server-side development, hence it requires that you run it inside of Node.js. 

When you search for Oracle NoSQL, you will see that the latest Oracle NoSQL Driver that lets you connect to the cloud service, or the Oracle NoSQL Database running anywhere, is called oracle-nosqldb and its current version is 5.2.2, so I will choose to install this one locally on my laptop.  Also, note that the SDK requires Node.js version 12.0.0 or higher.

Below, I am running sudo npm install –g oracle-nosqldb to install the Oracle NoSQL Database JavaScript SDK on my laptop and make it available globally.

Create a Compartment for Your Table

If you would like your table to be created in your own compartment (e.g. namespace) rather the root compartment, you can create a compartment by navigating to the compartments section of the Identity menu item in the Oracle cloud console.

Connect to the Oracle NoSQL Database Cloud Service

The Oracle NoSQL Database Cloud Service uses the Oracle Cloud Infrastructure native cloud Identity Access Manager (IAM) for authentication and authorization.  In the JavaScript API documentation, (https://oracle.github.io/nosql-node-sdk) for the SDK, you will notice a NoSQLClient class, which is what I will use to instantiate a connection to the cloud service and authenticate.  NOTE the IAMConfig configuration object, since this is what I will use to supply my credentials to the NoSQLClient class.

 

Before you can authenticate your application with the cloud service, you must generate a key pair and upload your public key to the Oracle Cloud.  The instructions here will guide you through generating an API signing key and uploading the public portion of that key to the Oracle Cloud https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/apisigningkey.htm#How

The following information will be needed for you to successfully authenticate with the cloud service:

The code below is structured as follows:

  1. The function getConnection – This is where you will fill in your specific credentials.  This method will perform authentication with the Oracle NoSQL Cloud Service and return a handle to the service. 
  2. The function createTable  – This function will create a table with two columns; an ID column of type LONG and a content column of type JSON.
  3. The method writeARecord – This method will write a single record to the hello world table.
  4. The method readARecord – This method will read a single record from the hello world table and return this record as a JSON string.
  5. The doHelloWorld – Will first get a connection to the service, create the table, write a single record, read that record back, and finally print that record to stdout.

 


'use strict';
 
const NoSQLClient = require('oracle-nosqldb').NoSQLClient;
const Region = require('oracle-nosqldb').Region;

/**
 * Call the main function tfor this example
 **/ 
doHelloWorld();

/** THis function will authenticate with the cloud service,
 * create a table, write a record to the table, then read that record back
 * 
 **/ 
async function doHelloWorld() {
    try {
        let handle = await getConnection(Region.US_ASHBURN_1);
        await createTable(handle);
        await writeARecord(handle, {
            id : 1,
            content : {
                'hello' : 'world'
                }
            }
        );

        console.log("Wrote a record with primary key 1")
        let theRecord = await readARecord(handle, 1);
        console.log('Successfully read the record: ' + 
            JSON.stringify(theRecord.row));
        process.exit(0);
    } catch (error) {
        console.log(e);
        process.exit(-1);
    }
}


/**
 * Create and return an instance of a NoSQLCLient object.  
 * NOTE that you need to fill in your cloud credentials and the 
 * compartment where you want your table created.  Compartments 
 * can be dot deperated paths.  For example: developers.dave.
 * 
 * @param {Region} whichRegion An element in the Region enumeration 
 *                             indicating the cloud
 *                             region you wish to connect to
 */
function getConnection(whichRegion) {
    return new NoSQLClient({
        compartment: 'Your compartment name goes here',
        region: whichRegion,
        auth: {
                iam: {
                    tenantId: 'The OCID of ryour tenancy goes here',
                    userId: 'Your user OCID goes here',
                    fingerprint: 'The fingerprint for your key pair goes here',
                    privateKeyFile: 'A fully qualified path to your private ' +
                            'key file goes here',
                    passphrase: 'The passphrase used to create your private ' +
                            'key goes here'
                }
            }
    });
}
/**
 * This function will creat the hello_world table with two columns, 
 * one long column which will be the primary key and one JSON column.
 * 
 * @param {NoSQLClient} handle An instance of NoSQLClient
 */
 async function createTable(handle) {
    const createDDL = 
        `CREATE TABLE IF NOT EXISTS hello_world (id LONG, content JSON, ` +
        `PRIMARY KEY(id))`;
    console.log('Create table: ' + createDDL);
    
        let res =  await handle.tableDDL(createDDL, {
            complete: true,
            tableLimits: {
                readUnits: 1,
                writeUnits: 1,
                storageGB: 1
            }
        });
       
    
    
}
/**
 * Writes a single record to the hello_world table
 * 
 * @param {NoSQLClient} handle an instance of NoSQLClient
 * @param {Object} record A JSON object representing record to 
 *                  write to hello_world.  
 */
async function writeARecord(handle, record) {
    await handle.put('hello_world', record);
}

/**
 * Reads and returns a record from the hello_world table
 * 
 * @param {NoSQLClient} handle an instance of NoSQLClient
 * @param {number} pk The primary key of the record to retrieve
 */
async function readARecord(handle, pk) {
    return await handle.get('hello_world', {
        'id' : pk
    })
}

If you take the code above and place it in a file entitled HelloWorld.js and fill in your credentials in the getConnection()function as well as the fully qualified name to the compartment where you want your table created,  you can run this file as specified below:

For more information about the JavaScript SDK and pointers to more example code on Github, take a look here https://www.npmjs.com/package/oracle-nosqldb.

Using the Native Oracle Cloud Infrastructure Console

You can also explore your tables using the Oracle Cloud Infrastructure console.  On the left-hand menu, simply navigate to the NoSQL Database menu item.

Once you click on the hello_world table link, you will see the following page:

Clicking on the Table rows control and then the clicking the Run query button control will display the record that you just inserted into the table:

If you have questions regarding this exercise, please send an email to oraclenosql-info_ww@oracle.com with “Hello World – JavaScript” in the subject line, and someone will get back to you as soon as possible.