Blog Building a Secure and Compliant Message Center with React and DataMotion

Building a Secure and Compliant Message Center with React and DataMotion

Prerequisites Setting up the Project Setting Up the Backend with DataMotion APIs Initiate the server  Installing Essential Libraries Setting up the Basic Server DataMotion API Integration in Server Fetching an Access Token: Fetching Emails: Verifying Backend Setup React Frontend: Fetching and Displaying Emails API Call with useEffect Displaying Emails Conclusion

DataMotion secure API development with developer coding encrypted data exchange solutions for industries on multiple colorful monitors.

Prerequisites

  • Familiarity with Node.js and React.
  • Node.js, git, and npm installed.
  • A text editor or IDE.
  • Access to DataMotion’s APIs.

Setting up the Project

git clone <url> 
cd DataMotion-SMC-starter-code
npm install
Markdown

Setting Up the Backend with DataMotion APIs

mkdir server
cd server
Markdown

Initiate the server

npm init -y
Markdown

 Installing Essential Libraries

  • express: A framework to build our server.
  • axios: To make HTTP requests.
  • cors: To enable Cross-Origin Resource Sharing.
  • dotenv: To manage environment variables from a .env file.
npm install express axios cors dotenv
Markdown

Setting up the Basic Server

touch server.js
Markdown
const express = require('express');
const axios = require('axios');
const cors = require('cors');

require('dotenv').config();

const app = express();
const PORT = 5000;

app.use(cors());  
app.use(express.json());

app.get('/', (req, res) => {
    res.send('Server is running!');
});

app.listen(PORT, () => {
    console.log(`Server is running on https://localhost:${PORT}`);
});
JavaScript
node server.js
Markdown

DataMotion API Integration in Server

Fetching an Access Token:

app.get('/token', async (req, res) => {
    try {
        const response = await axios.post('https://api.datamotion.com/SMC/Messaging/v3/token', {
            grant_type: "client_credentials",
            client_id: process.env.CLIENT_ID, // assuming you have named it CLIENT_ID in .env
            client_secret: process.env.CLIENT_SECRET // assuming you have named it CLIENT_SECRET in .env
        });
        res.json(response.data);
    } catch (error) {
        res.status(500).json({ message: "Error fetching token", error: error.response.data });
    }
});
JavaScript

Fetching Emails:

app.get('/messages', async (req, res) => {
    try {
        // First, get the token
        const tokenResponse = await axios.post('https://api.datamotion.com/SMC/Messaging/v3/token', {
            grant_type: "client_credentials",
            client_id: process.env.CLIENT_ID, // assuming you have named it CLIENT_ID in .env
            client_secret: process.env.CLIENT_SECRET // assuming you have named it CLIENT_SECRET in .env
        });

        // Use the token to get the message summaries
        const messagesResponse = await axios.get('https://api.datamotion.com/SMC/Messaging/v3/content/messages/?folderId=1&pageSize=10&pageNumber=1&sortDirection=DESC&metadata=true', {
            headers: {
                Authorization: `Bearer ${tokenResponse.data.access_token}`
            }
        });

        res.json(messagesResponse.data);
    } catch (error) {
        res.status(500).json({ message: "Error fetching messages", error: error.response.data });
    }
});
JavaScript

Verifying Backend Setup

React Frontend: Fetching and Displaying Emails

npm start 
Markdown
  • useState: A hook that gives a component its own data storage. It returns the data’s current value and a function to update it. When the data changes, the component re-renders.
  • useEffect: A hook that runs code after the component renders. We use it here to fetch emails once the component appears on screen.

API Call with useEffect

import React, { useState, useEffect } from 'react';
import { ListGroup } from 'react-bootstrap';

const Inbox = () => {
    const [emails, setEmails] = useState([]);

    useEffect(() => {
        // Call our server to get emails
        fetch('https://localhost:5000/messages')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                // Sort emails by createTime from newest to oldest
                const sortedEmails = data.items.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
                setEmails(sortedEmails);
            })
            .catch(error => {
                console.error('Error fetching messages:', error);
            });
    }, []);

   // Helper function to format the date or show the time if the email was received today
    const formatDate = (dateString) => {
      const date = new Date(dateString);
      const today = new Date();
      if (date.toDateString() === today.toDateString()) {
          return date.toLocaleTimeString();
      }
      return date.toLocaleDateString();
  };

    return (
        // Rendering logic here...
    );
};

export default Inbox;
JavaScript

Displaying Emails

// ... rest of the Inbox component ...

  return (
    <div className="col-md-9 pt-3">
        <ListGroup className='inbox-style'>
          {emails.map(email => (
              <ListGroup.Item key={email.messageId} className='email-item'>
                  <div>
                      {/* Email Address of Sender */}
                      <p className="sender-email">{email.senderAddress}</p>
                      {/* Email Subject */}
                      <p className="email-subject">{email.subject}</p>
                  </div>
                  {/* Email Received Date/Time */}
                  <div className="date-received">{formatDate(email.createTime)}</div>
              </ListGroup.Item>
          ))}
      </ListGroup>
   </div>
  );
};
JavaScript

Conclusion