mirror of
https://git.rdcenter.ru/RDCenter/skb-kit.git
synced 2026-12-05 03:29:45 +00:00
Оптимизировать получение медиа
This commit is contained in:
1 parent
39c6ce0d57
commit
58b39d5119
3 files changed
+28
-21
No files matched your search
+26
-21
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user