Creating a Node.js Application Using the Caching REST API in Oracle Application Container Cloud Service


Options



Before you Begin

Purpose

This tutorial shows you how to develop a standalone web service with Node.js and the Express framework, and how integrate the caching feature of Oracle Application Container Cloud Service using the REST API.

Time to Complete

30 minutes approximately

Background

The new caching capability of Oracle Application Container Cloud Service allows applications to accelerate access to data, share data among applications, and offload state management.

The caching feature of Oracle Application Container Cloud Service can be access from your application through the REST API.  The REST API defines the following endpoints: 

Method URL Description
GET /ccs/{cacheName}/{key} Retrieves the value associated with the specified key.
PUT /ccs/{cacheName}/{key} Stores the value and associates it with the specified key.
POST /ccs/{cacheName}/{key} Issues one of the following: putIfAbsent, replace, or removeValue.
DELETE /ccs/{cacheName}/{key} Deletes a key/value pair from a cache.
GET /ccs/{cacheName} Returns the server-side metrics for the specified cache.
DELETE /ccs/{cacheName} Clears the specified cache.

The caching REST API uses JSON as data exchange format.

Scenario

In this tutorial you create a REST service in Node.js using the Express framework. The application implements the CRUD (Create, Read, Update, and Delete) operations on a employee object. Each operation implements the caching feature of Oracle Application Container Cloud Service to store the employee data in memory. You test the REST service using an HTML client developed with Angular and Bootstrap. This tutorial doesn't cover how to implement the client, the client project is provided in the What do You Need? section.

What Do You Need?

Creating a Caching Service

  1. Open the Oracle Application Container Cloud Service console.

  2. Click Menu and select Application Cache.

  3. Click Create Service.

  4. Enter the following information, and then click Next.

    • Service Name: MyCachingService

    • Service Description (optional)

    • Deployment Type: Basic

    • Cache Capacity (GB): 1

  5. In the confirmation page, click Create.

    You see the status: Creating service... and the hourglass icon.

  6. Click the Refresh Refresh icon. The status and hourglass icon disappear when the instance is ready. It could take a few minutes.

    Note: The cache won't be visible to any applications until it is ready.

    Services list page
    Description of this image

Creating the REST Service

  1. Open a console window and go to the folder where you want to store the Node.js application server.

  2. Run npm init to create the package.json file. At the prompt, enter the following values, confirm the values, and then press Enter:

    • Name: node-server
    • Version: 1.0.0 (or press Enter.)
    • Description: Employee RESTful application
    • Entry point: server.js
    • Test command (Press Enter.)
    • Git repository (Press Enter.)
    • Keywords (Press Enter.)
    • Author (Enter your name or email address.)
    • License (Press Enter.)

    The package.json file is created and stored in the current folder. You can open it and modify it, if needed.

  3. In the console window, download, build, and add the Express framework dependency.

     npm install --save express 
  4. Install the body-parser dependency.

    npm install --save body-parser

    The body-parser dependency is a Node.js middleware for handling JSON, Raw, Text and URL encoded form data.

  5. Install the node-rest-client dependency.

    npm install --save node-rest-client
  6. Create a server.js file, open it in a text editor, and add the following require modules:

    var express = require('express');
    var bodyParser = require('body-parser');
    var Client = require("node-rest-client").Client;
  7. Create the MYPORT variable to store the port that your application will be listening on, and the CCSHOST variable to store the host name of the caching feature.

    The PORT environment variable is set automatically by Oracle Application Container Cloud Service when you create an application. The CACHING_INTERNAL_CACHE_URL is set when you add the caching cluster to your application.

    var MYPORT = process.env.PORT || '8080'; 
    var CCSHOST = process.env.CACHING_INTERNAL_CACHE_URL; 
  8. Create an app variable to use the express framework.

    var app = express();
  9. Configure your application to use bodyParser(), so that you can get the data from a POST request.

    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json({ type: '*/*' }));
  10. Enable the public directory to store the static content.

    app.use(express.static('public'));
  11. Set up a router for handling rest requests.

    var router = express.Router();
  12. Create a client to consume the caching REST API.

     var client = new Client(); 
  13. Create the baseCCS_URL variable to store the base URL of the caching REST API.

    var baseCCSURL = 'http://' + CCSHOST + ':8080/ccs';
  14. Create the cacheName variable to store the name of our cache.

    var cacheName = 'ccstest';
  15. Create the countEmployees variable and initialize it with 100. This variable help us to generate the employee ID.

    var countEmployees = 100;
  16. Create the GET method to get the employee by ID:

    // GET
    router.route('/:keyString').get(function (request, response) {
        
        var keyString = request.params.keyString;
        
        // Issue the GET -- our callback function will return the response
        // to the user
        client.get(baseCCSURL.concat('/').concat(cacheName).concat('/').concat(keyString),
            function(valString, rawResponse){
                var responseBody = { };
                // If nothing there, return not found
                if(rawResponse.statusCode == 404){
                    responseBody['error'] = 'Key not found error.';
                }
                else{
                    // Create the response to the caller.
                    // Note: valString is a Buffer object.
                    responseBody['key'] = keyString;				
                    responseBody['value'] = valString.toString();     		
                }          
                // Send the response
                response.json(responseBody).end();  
            });
    });
  17. Create the POST method to add new employees:

    // POST
    router.route('/').post(function (request, response) {
        var keyString = countEmployees++;
        var body = request.body;	
    	var employee ={ id: keyString, firstName: body.firstName,
    				   lastName: body.lastName, email: body.email, 
    				   phone: body.phone, birthDate: body.birthDate,  
    				   title: body.title, dept: body.dept};									   
        // Build the args for the request
        var args = {
            data: employee,
            headers: { "Content-Type" : "application/json" }
        };
        
        // Issue the PUT -- the callback will return the response to the user
        client.put(baseCCSURL.concat('/').concat(cacheName).concat('/').concat(keyString),
            args,
            function (employee, rawResponse) {   
                // Proper response is 204, no content.
                var responseBody = { };            
                if(rawResponse.statusCode == 204){
                    responseBody['status'] = 'Successful.';
                }
                else{
                    responseBody['error'] = 'PUT returned error '.concat(rawResponse.statusCode.toString());
                }      
                // Send the response
                response.json(responseBody).end(); 
        });  
    });
  18. Create the PUT method to update the employee by ID:

    // PUT
    router.route('/:keyString').put(function (request, response) {    
        // Get the key and value
        var keyString = request.params.keyString;
        var body = request.body;	
    	var employee ={ id: keyString, firstName: body.firstName,
    				   lastName: body.lastName, email: body.email, 
    				   phone: body.phone, birthDate: body.birthDate,  
    				   title: body.title, dept: body.dept};
        // Build the args for the request
        var args = {
            data: employee,
            headers: { "Content-Type" : "application/octet-stream",
                       "X-Method" : "replace"}//Important! specify the x-Method for replacing the value
        };
      
        client.post(baseCCSURL.concat('/').concat(cacheName).concat('/').concat(keyString),
            args,
            function (employee, rawResponse) {
                
                // Proper response is 204, no content.
                var responseBody = { };
                
                if(rawResponse.statusCode == 204){
                    responseBody['status'] = 'Successful.';
                }
                else{
                    responseBody['error'] = 'PUT returned error '.concat(rawResponse.statusCode.toString());
                }      
                // Send the response
                response.json(responseBody).end(); 
        });  
    });
                                  
  19. Create the DELETE method to remove employees by ID:

    // DELETE
    router.route('/:keyString').delete(function (request, response) {    
        // Fetch the key to delete
        var keyString = request.params.keyString;
        
        client.delete(baseCCSURL.concat('/').concat(cacheName).concat('/').concat(keyString),
            function(valString, rawResponse){    
                var responseBody = {  };            
                responseBody['status'] = 'Successful.';              
                response.json(responseBody).end();  
            });
    });
  20. Start the server:

    app.use('/employees', router);
    app.listen(MYPORT);
  21. Save and close the file.

  22. In the root project directory, create the public directory.

  23. Unzip the employees-client.zip file directly under the public directory.

Preparing the Node.js Server Application for Cloud Deployment

For your server application to run properly on Oracle Application Container Cloud Service, it must comply with the following requirements:

  • The application must be bundled in a .zip file.
  • In addition to the server.js file, the .zip file must contain a manifest.json file that specifies what command Oracle Application Container Cloud Service should run.
  • Your application must listen to requests on a port provided by the PORT environment variable. Oracle Application Container Cloud uses this port to redirect requests made to your application.
  1. Create themanifest.json file.

  2. Open the manifest.json file in a text editor and add the following content:

    {
      "runtime":{
        "majorVersion":"6"
      },
      "command": "node server.js",
      "isClustered":"true",
      "release": {},
      "notes": ""
    }

    The manifest.json file contains the target platform and the command to be run.

  3. Compress all the project files together in a .zip file.

    Note: Make sure you include the public and node_modules directories in the zip file.

    Project files
    Description of this image

You'll use this .zip file to deploy the application to Oracle Application Container Cloud Service.

Deploying the Application to Oracle Application Container Cloud Service

To deploy the application to Oracle Application Container Cloud Service you use the .zip file that you created in the previous section. You use the administration console to upload and deploy the application.

  1. Go back to the Oracle Application Container Cloud Service console.

  2. Click Create Application and then select Node.

  3. In the Application section, enter NodeExampleCache for the name of your application, and then click Browse.

  4. In the File Upload dialog box, locate the file that you created in the previous section; select it and click Open.

  5. Keep the default values in the Instances and Memory fields.
  6. Click More Options. In the Application Cache field, select MyCachingService and click Create.

  7. Wait until the application is deployed.

    Application URL
    Description of this image

    The URL will be enabled when the creation process is completed.

Testing the Application

  1. In the Oracle Application Container Cloud Service console, click the URL of your application.

  2. Click Add New

    Employee client home page
    Description of this image
  3. Enter the First Name, Last Name, Email, Phone, Birthdate, Title, and Department values and click Save.

    Add New employee page
    Description of this image

    Note: The default starting value of ID is 100 and will increment by 1 for each record.

  4. Enter the ID of the new employee which is 100, select By ID, and click Search.

  5. Click the employee card.

    Employee client home page
    Description of this image
  6. Update the information of the employee and click Save.

    Employee client - update employee
    Description of this image
  7. Search again the employee to confirm the data was updated.

    Employee client - update employee
    Description of this image
  8. Click the employee card, and then click Delete.

    Employee client - update employee
    Description of this image
  9. Search again the employee to confirm the employee was deleted.

    Employee client - update employee
    Description of this image

Want to Learn More?