Skip to main content

Custom HTTP client

You can customize ServerStorage class and use your own HTTP client (or SDK) to send the HTTP calls. Simply use data property and return a Promise object that conforms to StorageResponse format (https://github.com/carry0987/Paginator-JS/blob/master/src/interface/response.ts#L8-L11).

In this example, we are implementing our own HTTP client (instead of default fetch API that ServerStorage provides):

Live Editor
const paginator = new Paginator({
    columns: ['Name', 'Language', 'Released At', 'Artist'],
    pageSize: 5,
    server: {
        url: 'https://api.scryfall.com/cards/search?q=Inspiring',
        data: (opts) => {
            return new Promise((resolve, reject) => {
                // let's implement our own HTTP client
                const xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function () {
                    if (this.readyState === 4) {
                        if (this.status === 200) {
                            const resp = JSON.parse(this.response);

                            // make sure the output conforms to StorageResponse format:
                            // https://github.com/carry0987/Paginator-JS/blob/master/src/interface/response.ts#L8-L11
                            resolve({
                                data: resp.data.map((card) => [
                                    card.name,
                                    card.lang,
                                    card.released_at,
                                    card.artist,
                                ]),
                                total: resp.total_cards,
                            });
                        } else {
                            reject();
                        }
                    }
                };
                xhttp.open('GET', opts.url, true);
                xhttp.send();
            });
        },
    },
    dataRender: (response) => {
        let dataHtml = '<ul>';
        response.forEach((item, index) => {
            dataHtml += '<li><span>' + item.join(' : ') + '</span></li>';
        });
        dataHtml += '</ul>';
        document.querySelectorAll('div.list-container')[0].innerHTML = dataHtml;
    }
});
Result
Loading...