OData TUTORIAL

Connecting to OData Service from node.js or next.js

Updated: 30 Dec 2022

Exposing OData Service from Hybrid Data Pipeline

What is OData Service and how to expose one?

The Open Data Protocol is a data access protocol, typically built using RESTful Web Services over Http protocol.  Simply, it defines a way to access data from SQL databases, NoSQL and any other data exposed by SaaS applications. With the help of Hybrid Data Pipeline product it is possible to expose OData Services for any datastore that is running in cloud or on-premise with no-code to be written.

Follow this tutorial link to understand how quickly and easily one can expose OData Service using Hybrid Data Pipeline product.  Typical URL for your OData Service would be https://<hdp_server>:8443/api/odata4/<your_datasource_name>/

Connecting to OData Service from Node.js

How to access OData Service?

In the previous section, we have seen how to expose an OData Service from Hybrid Data Pipeline product.

In this tutorial, we will create a simple Node.js application and connect to OData Service exposed from Hybrid Data Pipeline to get access to data.

From a Node.js perspective, there is OData Client Library available to easily access any OData Services. This library is built using TypeScript and can be easily imported in a Node.js application. There are many other libraries that you are free to explore and use to suite your needs.

Creating a Node.js application to Connect to OData Service

  • Create a simple Node.js application and have the following libraries imported in the package.json
{
    "dependencies": { 
    "@odata/client": "^2.21.0-beta.0"
    }
 }
  •  Create a file named odata-hdp-client.ts and copy the following code
import { OData } from "@odata/client"
 
console.log('Accessing data using OData Client')
// Hybrid Data Pipeline's sample odata service
const oDataServiceURL = "https://XXXXXXXXXX:8443/api/odata4/sf-royal/$metadata"
const client1 = OData.New4({
  metadataUri: oDataServiceURL,
})

client1.setCredential({ username: "d2cadmin", password : "XXXXX" })

let selectLoginIPsByUserID = async () => {
  console.log('Executing Query: /LOGINIPS?$format=json$filter=USERSID eq \'00590000002w0IkAAI\'')
  // Query by filter
  const filter = client1.newFilter().property("USERSID").eq("00590000002w0IkAAI");
  
  let result = await client1.newRequest({ // ODataRequest object
    collection: "LOGINIPS", // entity set
    params: client1.newParam().filter(filter) // odata param
  })
  console.log('Executed OData Query (1) successfully.')
    console.log(JSON.stringify(result)) 
}
selectLoginIPsByUserID(); 
  • Compile the typescript code using the command tsc odata-hdp-client.ts
    This will produce javascript code.
  • Run the javascript code using the command node odata-hdp-client.js
  • Expect the output similar to the following
          Accessing data using OData Client
          Executing Query: /LOGINIPS?$format=json$filter=USERSID eq '00590000002w0IkAAI'
          Executed OData Query (1) successfully.
 {  "d": {
            "results": [
            {
        "__metadata": [
          "Object"
        ],
        "ID": "71090000016dPHRAA2",
        "USERSID": "00590000002w0IkAAI",
        "SOURCEIP": "202.65.136.5",
        "CREATEDDATE": "/Date(1475847693000)/",
        "ISAUTHENTICATED": true,
        "CHALLENGESENTDATE": null,
        "CHALLENGEMETHOD": null
      }
    ]
  }
}

 

 

Connecting to OData Service from Next.js

4

 

 

In the previous sections, we have seen how to expose an OData Service from Hybrid Data Pipeline and consume the same from Node.js.  This section outlines how to consume an OData Service from Next.js application.

We still use the same library to connect to OData service and show the results in a web page. 

Creating a Next.js application to Connect to OData Service

  • Create a simple Next.js application and have the following libraries imported in the package.json
{
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@odata/client": "^2.21.2",
    "next": "^13.1.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  }
}
  • Create a file named odata-results.js and copy the following code
        import React from "react";
        import { OData } from "@odata/client"

        const ODataResults = () => {
        const [data, setData] = React.useState(null);
        
        React.useEffect(() => {
        const serviceEndpoint = "https://XXXXXXX:8443/api/odata4/sf-royal/"
        const client = OData.New4({ serviceEndpoint });
        client.setCredential({ username: "d2cadmin", password : "XXXXXX" })

        let selectLoginIPsByUserID = async () => {
          console.log('Executing Query: /LOGINIPS?$format=json$filter=USERSID eq \'00590000002w0IkAAI\'')
          // Query by filter
          const filter = client.newFilter().property("USERSID").eq("00590000002w0IkAAI");
          
          let result = await client.newRequest({ // ODataRequest object
            collection: "LOGINIPS", // entity set            
          })
          console.log('Executed OData Query (1) successfully.')          
          setData(result.d.results)
        }
        selectLoginIPsByUserID();
        
        }, []);

        return (
            <div>
              {data ? (
                <ul>
                  {data.map(item => (
                    <li key={item.ID}>UsersID:{item.USERSID} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SourceIP:{item.SOURCEIP}</li>
                  ))}
                </ul>
              ) : (
                "Loading..."
              )}
            </div>
          );    
  };
  
  export default ODataResults;
  • Open the command prompt to the next.js application folder and run the project using the command npm run dev
  • With the default settings, typically the server will be running at http://localhost:3000/
  • Access the OData results page from the browser - http://localhost:3000/odata-results
  • You should see the OData results page showing the OData query results
  • UsersID:00590000001RVznAAG      SourceIP:149.37.135.161
  • UsersID:00590000001RVznAAG      SourceIP:149.204.219.122
  • UsersID:00590000001RVznAAG      SourceIP:170.34.58.20
  • UsersID:00590000001RVznAAG      SourceIP:123.22.172.110
  • UsersID:00590000001RVznAAG      SourceIP:121.239.31.209
  • UsersID:00590000001RVznAAG      SourceIP:141.60.222.61

References

Hybrid Data Pipeline Installation Guide
On-Premise Connector Installation Guide
Configuring Data Source for OData Access 

 

 

 

 

 

Connect any application to any data source anywhere

Explore all DataDirect Connectors

Need additional help with your product?

Get Customer Support