• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Plug the StellarDS.io REST-API into a JavaScript grid in 15 minutes

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,486
Баллы
155
At

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

, our goal is to enable creating web & native apps with central data in the back-end as quick and easy as possible. To demonstrate this, we integrated StellarDS.io with a popular JavaScript grid library to see how seamless the process could be. For this blog post, we chose the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

library, and had everything up and running in about 15 minutes.


TMS Software Delphi  Components


Step 1: Create Tables



The first step is to create the necessary tables. For this demo, we created tables for meetings, representatives, and customers, as shown below:


TMS Software Delphi  Components


We populated the tables with mock data to visualize the responses.


Step 2: Initialize the Project and Add Grid.js


Next, we created a simple project and added Grid.js, following the

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

. To get started, we initialized a grid and provided the URL to fetch our data. We also added a join query to retrieve customer and representative information for each meeting. Here's how you can do it:



const grid = new gridjs.Grid({
columns: [
{ name: "Representative" },
{ name: "Customer" },
{ name: "Start time" },
{ name: "End time" },
{ name: "Address" },
{ name: "Postal code" },
{ name: "Country" }
],
server: {
url: "

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

" + projectId,
headers: {
'Authorization': 'Bearer ' + token
},
handle: (res) => {
if (res.status === 404) return { data: [] };
if (res.ok) return res.json();
},
then: data => data.data.map(meeting => [
meeting.RepresentativesFirstName + ' ' + meeting.RepresentativesLastName,
meeting.CustomersFirstName + ' ' + meeting.CustomersLastName,
meeting.StartTime,
meeting.EndTime,
meeting.CustomersAddress,
meeting.CustomersPostalCode,
meeting.CustomersCountry
]),
total: data => data.count
}
}).render(document.getElementById("wrapper"));



In this setup, we pass the authorization header and handle the response, mapping the returned data to the corresponding columns. Finally, we render it in a <div> element, and that&#146;s it! The grid is now fully functional.

TMS Software Delphi  Components


Expanding the Demo: Pagination and Sorting


Since we had extra time, we also implemented pagination and sorting using Grid.js&#146;s built-in features.

For pagination, we followed the documentation and added the following code:


pagination: {
limit: 20,
summary: false,
server: {
url: (prev, page, limit) => `${prev}&take=${limit}&offset=${page * limit}`
}
}


This limits the number of items per page to 20 and appends the appropriate parameters to the URL to manage pagination.

For sorting, we adapted an example from the documentation to match StellarDS&#146;s sort query format. Here's the final result:


sort: {
multiColumn: false,
server: {
url: (prev, columns) => {
if (!columns.length) return prev;

const col = columns[0];
const dir = col.direction === 1 ? 'asc' : 'desc';
let colName = ['Representative.FirstName', 'Customer.FirstName', 'StartTime', 'EndTime', 'Customer.Address', 'Customer.PostalCode', 'Customer.Country'][col.index];

return `${prev}&sortquery=${colName};${dir}`;
}
}
}


With pagination and sorting in place, the grid now looks like this:

TMS Software Delphi  Components


If you'd like to experiment with this demo, you can download it here:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Conclusion


We&#146;re really pleased with the results. It didn&#146;t take long to learn how to use Grid.js, and once we got started, everything was smooth and efficient. By simply passing the URL, the grid handles all requests for us&#151;no need to manually use the Fetch API or other REST API libraries. StellarDS.io and Grid.js make a powerful combination for handling data grids effortlessly.

Launch Offer!


To celebrate the launch of

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

we are offering a 10% discount on your first year when purchasing a yearly license or a 10% discount for the first 6 months when purchasing a monthly license.



Use code LAUNCHYEAR or LAUNCHMONTH respectively at checkout to apply the discount.



Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу