Skip to content

RevealBi/sdk-samples-mongodb

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Reveal SDK Samples - MongoDB

This repository contains comprehensive examples demonstrating how to implement Reveal SDK with MongoDB as your data source. You'll find both server-side implementations (Node.js with JavaScript and TypeScript) and client-side examples to help you quickly build powerful analytics applications.

What's in This Repository

This repository provides everything you need to learn and implement a Reveal SDK application with MongoDB, including working code samples, configuration examples, and best practices.

Server Examples

  • Read [Setting up a Reveal Server](https://help.revealbi.io/web/

  • Node.js (JavaScript) - Located in server/node-js/

    • Implementation using JavaScript with MongoDB integration
    • Includes examples for custom queries, aggregation pipelines, and user-based filtering
    • Features authentication, data source providers, and row-level security
  • Node.js (TypeScript) - Located in server/node-ts/

    • Type-safe implementation using TypeScript
    • Comprehensive examples with MongoDB aggregation pipelines
    • Includes dashboard management and user context handling

Client Examples

  • HTML with Dashboard Selector - client/index-ds.html

    • Add new dashboards with a MongoDb datasource
  • HTML with Dashboard Selector - client/index-dsi.html

    • Add new dashboards with a MongoDb datasource + datasource item with UserContext
  • HTML with Direct Dashboard Loading - client/load-dashboard.html

    • Loading dashboards

Reveal Overview & Important Notes for MongoDB Integration

Dependencies

The essential dependencies for a Node.js application using Reveal with MongoDB are:

  • Reveal SDK Node.js package (reveal-sdk-node)
  • MongoDB Node.js Driver (included with Reveal SDK)
  • Express.js for server implementation
  • dotenv for environment configuration

Integrating Reveal with MongoDB

Reveal is integrated into a Node.js application via the NPM package. The configuration is set up in your main server file (main.js or main.ts):

const revealOptions = {
    userContextProvider: userContextProvider,
    authenticationProvider: authenticationProvider,
    dataSourceProvider: dataSourceProvider,
    dataSourceItemProvider: dataSourceItemProvider,
    dataSourceItemFilter: dataSourceItemFilter,
    dashboardProvider: dashboardProvider,
    dashboardStorageProvider: dashboardStorageProvider
}

app.use('/', reveal(revealOptions));

In this setup:

  • User Context Provider: Manages user authentication and role-based access
  • Authentication Provider: Handles MongoDB credentials securely
  • Data Source Provider: Configures MongoDB connection strings and database names
  • Data Source Item Provider: Defines custom queries, aggregation pipelines, and data filtering
  • Data Source Item Filter: Controls which collections users can access based on roles
  • Dashboard Provider/Storage: Manages dashboard loading and saving

Core Server Functions for MongoDB

1. Authentication

Authentication is handled by implementing the authentication provider for MongoDB. Username and password credentials are securely managed using environment variables:

const authenticationProvider = async (userContext, dataSource) => {
  if (dataSource instanceof reveal.RVMongoDBDataSource) {
    const username = process.env.MONGO_USERNAME;
    const password = process.env.MONGO_PASSWORD;
    
    return new reveal.RVUsernamePasswordDataSourceCredential(username, password);
  }
};

Resources:

2. Data Source Provider

The Data Source Provider specifies MongoDB connection details including connection string and database name:

const dataSourceProvider = async (userContext, dataSource) => {
  if (dataSource instanceof reveal.RVMongoDBDataSource) {
    dataSource.connectionString = process.env.CONNECTION_STRING;
    dataSource.database = process.env.DATABASE_NAME;
  }
  return dataSource;
};

Resources:

3. Data Source Items with MongoDB Aggregation Pipelines

MongoDB's powerful aggregation framework can be leveraged through custom queries. This example shows how to create dynamic queries based on user context:

const dataSourceItemProvider = async (userContext, dataSourceItem) => {
  if (dataSourceItem instanceof reveal.RVMongoDBDataSourceItem) {
    await dataSourceProvider(userContext, dataSourceItem.dataSource);

    if (dataSourceItem.id === "Custom_Query_Filtered") {
      const username = userContext.userId;
      dataSourceItem.collection = "customers";
      dataSourceItem.customQuery = JSON.stringify([
        {
          $lookup: {
            from: "accounts",
            localField: "accounts",
            foreignField: "account_id",
            as: "accounts"
          }
        },
        {
          $match: {
            username: username
          }
        },
        {
          $project: {
            username: "$username",
            accounts: "$accounts"
          }
        }
      ]);
    }
  }
  return dataSourceItem;
};

Resources:


Optional but Important Server Functions

User Context

The User Context Provider manages user information and roles, enabling row-level security:

const userContextProvider = (request) => {
  const userId = request.headers["x-header-one"];
  const props = new Map();
  props.set("userId", userId);

  // Set Role based on userId
  const role = userId === "glopez" ? "Admin" : "User";
  props.set("Role", role);

  return new reveal.RVUserContext(userId, props);
};

Resources:

Data Source Item Filter (Collection-Level Security)

The Data Source Item Filter controls which MongoDB collections users can access based on their roles:

const dataSourceItemFilter = async (userContext, dataSourceItem) => {
  if (dataSourceItem instanceof reveal.RVMongoDBDataSourceItem) {
    const includedList = ["customers", "accounts"];
    const role = userContext?.properties.get("Role") || "User";

    if (role === "User") {
      // Allow only items in the included list for "User" role
      if (dataSourceItem.collection && includedList.includes(dataSourceItem.collection)) {
        return true;
      }
    } else {
      // Allow everything for non-"User" roles
      return true;
    }
  }
  return false;
};

Resources:

Dashboard Provider & Storage

The Dashboard Provider and Storage Provider manage dashboard loading and saving:

const dashboardProvider = async (userContext, dashboardId) => {
    const filePath = path.join(dashboardDefaultDirectory, `${dashboardId}.rdash`);
    
    if (fs.existsSync(filePath)) {
        return fs.createReadStream(filePath);
    } else {
        throw new Error(`Dashboard file not found: ${filePath}`);
    }
};

Setting up the Client

HTML Client Setup

The HTML client requires three dependencies:

  1. jQuery
  2. Day.js (for date handling)
  3. Reveal JavaScript library

These can be accessed locally or through a CDN:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://dl.revealbi.io/reveal/libs/[version]/infragistics.reveal.js"></script>

Loading Dashboards

Dashboards are loaded using the RevealView component:

$.ig.RevealSdkSettings.setBaseUrl("http://localhost:5111/");

var revealView = new $.ig.RevealView("#revealView");
revealView.dashboardId = "Sales";

Additional Headers Provider

Pass custom headers (like userId) to the server for authentication and filtering:

$.ig.RevealSdkSettings.setAdditionalHeadersProvider(function (url) {
    var headers = {};
    headers["x-header-one"] = "glopez"; // or dynamically get from user session
    return headers;
});

Resources:


Environment Configuration

Create a .env file in your server directory with the following variables:

# MongoDB Configuration
CONNECTION_STRING=mongodb+srv://your-connection-string
DATABASE_NAME=your_database_name
MONGO_USERNAME=your_username
MONGO_PASSWORD=your_password

# Server Configuration
PORT=5111

Getting Started

1. Clone the Repository

git clone https://github.com/RevealBi/sdk-samples-mongodb.git
cd sdk-samples-mongodb

2. Set Up the Server (Node.js JavaScript)

cd server/node-js
npm install
# Create and configure your .env file
npm start

3. Set Up the Server (Node.js TypeScript)

cd server/node-ts
npm install
# Create and configure your .env file
npm start

4. Open the Client

Open any of the HTML files in the client/ directory in your web browser, or serve them using a local web server.


Video Training

Explore these video resources to help you set up and configure Reveal BI:

For a comprehensive learning path, check out the Reveal SDK Videos:
Reveal SDK Videos


MongoDB-Specific Features

Aggregation Pipeline Support

Reveal SDK fully supports MongoDB's aggregation pipeline, allowing you to:

  • Perform complex data transformations
  • Join collections using $lookup
  • Filter data with $match
  • Project specific fields with $project
  • Unwind arrays with $unwind

Sample MongoDB Data Structure

This repository includes examples based on a sample financial database with:

  • customers collection: User account information
  • accounts collection: Financial account details

The examples demonstrate joining these collections and filtering based on user context.


Licensing

A trial license key is valid for 30 days and can be extended upon request. When a license is purchased, the key is valid for the duration of the contract. It's important to keep track of the license expiry date to avoid disruptions. The license key can be set in code, configuration files, or the home directory.


Resources

The following resources are available to help with your implementation:


Support

If you encounter any issues or have questions:

  1. Check the documentation
  2. Review existing GitHub issues
  3. Join our Discord community
  4. Post in GitHub Discussions

Contributing

We welcome contributions! Please feel free to submit issues, feature requests, or pull requests.


License

This project is licensed under the MIT License - see the LICENSE file for details.


Ready to get started? Choose your preferred server implementation (JavaScript or TypeScript), configure your MongoDB connection, and start building powerful analytics dashboards!

About

End-to-end MongoDb samples for Node, Java & .NET Core

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published