Оптимизировать получение медиа

This commit is contained in:
ifraimka committed 2024-04-24 13:59:31 +03:00
1 parent 39c6ce0d57
commit 58b39d5119
3 files changed
+28 -21

No files matched your search

+1
View File
@@ -11,6 +11,7 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.0",
+1
View File
@@ -6,6 +6,7 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.0",
+26 -21
View File
@@ -1,4 +1,5 @@
import * as WPAPI from 'wpapi';
import { flatten } from 'lodash';
import reactPress from './reactPress';
@@ -12,34 +13,38 @@ const wp = new WPAPI(
: { endpoint: reactPress.api.rest_url, nonce: reactPress.api.nonce }
);
// Функция загрузки медабиблиотеки по категориям
async function loadMedia() {
// Пытаемся получить медиа, пока не получится
let response;
while (!response) {
try {
response = await wp.media();
} catch (e) {
console.error(e);
async function getAllMedia(request) {
return request.then(function (response) {
if (!response._paging || !response._paging.next) {
return response;
}
}
// Запрос к следующей странице и возврат ответов одной коллекцией
return Promise.all([
response,
getAllMedia(response._paging.next)
]).then(function (responses) {
return flatten(responses);
});
});
}
// Функция загрузки медабиблиотеки и сортировки по категориям
async function loadMedia() {
const response = await getAllMedia(wp.media());
// Нам потребуется id, категория и url
const result = {};
while (response) {
for (let { id, alt_text, source_url: image } of response) {
const [category, name] = alt_text.split('_');
// Создаем ключ с пустым массивом, если еще нет
if (!result[category]) {
result[category] = [];
}
for (let { id, alt_text, source_url: image } of response) {
const [category, name] = alt_text.split('_');
// Добавляем медиа в массив нужной категории
result[category].push({ id, name, image });
// Создаем ключ с пустым массивом, если еще нет
if (!result[category]) {
result[category] = [];
}
if (!response._paging.next) break;
response = await response._paging.next.get();
// Добавляем медиа в массив нужной категории
result[category].push({ id, name, image });
}
return result;