How can I help you?
Applying Middleware logic in EJ2 JavaScript DataManager
15 Apr 20267 minutes to read
The Syncfusion® DataManager supports applying middleware logic to modify requests and responses during data processing. This capability is useful for handling tasks such as authentication, validation, logging, and transforming response data. Middleware can be applied through two methods: applyPreRequestMiddlewares and applyPostRequestMiddlewares, each serving a specific stage in the data handling workflow.
Pre-Request Middleware
The applyPreRequestMiddlewares method executes before a request is sent to the server. It enables modification of request headers, query parameters, or payloads. This is commonly used for adding authentication tokens, restructuring requests, or performing validations. The following code snippet demonstrates how to add an authorization token:
dataManager.applyPreRequestMiddlewares([
async (context) => {
context.request.headers['Authorization'] = 'Bearer your-access-token';
}
]);Post-Request Middleware
The applyPostRequestMiddlewares method runs after a response is received from the server but before the data is bound to a component. It allows filtering, formatting, or restructuring the response to meet application requirements. The following code snippet demonstrates how to format response data:
dataManager.applyPostRequestMiddlewares([
async (context) => {
context.response.result = context.response.result.map(item => ({
id: item.Id,
name: item.Name.toUpperCase(),
date: new Date(item.Timestamp).toLocaleDateString()
}));
}
]);Supported data adaptors
Middleware functions are supported across multiple DataManager adaptors, including the WebApiAdaptor, ODataAdaptor, and CustomAdaptor, and can be applied to both local and remote data operations. This enhances flexibility, security, and overall control of data processing.
The example demonstrates using the UrlAdaptor with middleware to adjust requests and responses. Before sending a request, applyPreRequestMiddlewares fetches an authentication token from an external server and adds it to the request headers. If the token retrieval fails, the DataManager failure event handles the error. Likewise, applyPostRequestMiddlewares processes the server response before it is bound to the UI, enabling any required transformations or filtering.
var template =
'<tr><td>${OrderID}</td><td>${CustomerID}</td><td>${EmployeeID}</td></tr>';
var compiledFunction = ej.base.compile(template);
var table = document.getElementById('datatable');
const data = new ej.data.DataManager({
url: 'https://services.syncfusion.com/js/production/api/UrlDataSource',
adaptor: new ej.data.UrlAdaptor(),
}).executeQuery(new ej.data.Query()).then(function (e) {
e.result.forEach(function (data) {
table.appendChild(compiledFunction(data)[0]);
});
});
// Method to apply middleware before sending a request to the server.
data.applyPreRequestMiddlewares = async function(request) {
// Fetch authentication token from an external service.
const response = await fetch('https://example.com/api/token', { // Replace with your actual endpoint. This URL is just for example purposes.
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Return the authentication token.
return { token: "your_token_value" };
};
data.dataManagerFailure = (e) => {
// Handle DataManager failure event.
}
// Method to apply middleware after receiving a response from the server.
data.applyPostRequestMiddlewares = async function(response) {
return response;
};<!DOCTYPE html><html lang="en"><head>
<title>EJ2 Grid</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Typescript Grid Control">
<meta name="author" content="Syncfusion">
<link href="index.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-base/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-grids/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-buttons/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-popups/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-navigations/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-dropdowns/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-lists/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-inputs/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-calendars/styles/material.css" rel="stylesheet">
<link href="https://cdn.syncfusion.com/ej2/33.2.3/ej2-splitbuttons/styles/material.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/33.2.3/dist/ej2.min.js" type="text/javascript"></script>
<style>
.e-table {
border: solid 1px #e0e0e0;
border-collapse: collapse;
font-family: Roboto;
}
.e-table td,
.e-table th {
border-style: solid;
border-width: 1px 0 0;
border-color: #e0e0e0;
display: table-cell;
font-size: 14px;
line-height: 20px;
overflow: hidden;
padding: 8px 21px;
vertical-align: middle;
white-space: nowrap;
width: auto;
}
</style>
</head>
<body>
<div id="container">
<table id="datatable" class="e-table">
<thead>
<tr>
<th>Order ID</th>
<th>Customer ID</th>
<th>Employee ID</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
var ele = document.getElementById('container');
if(ele) {
ele.style.visibility = "visible";
}
</script>
<script src="index.js" type="text/javascript"></script>
</body></html>