fix(skeb): resolve Redis cache async issue and refactor request flow (#20111)
- Fix Redis cache async handling by adding await to cache.get() calls - Refactor request_key management into separate ensureRequestKey function - Simplify main data fetching flow by removing complex retry logic - Add proper error type guards and logging for better debugging - Improve code readability and maintainability Fixes issue where Skeb works route failed with Redis cache due to cache.get() returning Promise object instead of string value, causing invalid request_key in API calls.
This commit is contained in:
+43
-25
@@ -4,6 +4,7 @@ import ConfigNotFoundError from '@/errors/types/config-not-found';
|
||||
import { baseUrl, processWork } from './utils';
|
||||
import cache from '@/utils/cache';
|
||||
import ofetch from '@/utils/ofetch';
|
||||
import logger from '@/utils/logger';
|
||||
|
||||
export const route: Route = {
|
||||
path: '/works/:username',
|
||||
@@ -46,32 +47,19 @@ async function handler(ctx): Promise<Data> {
|
||||
|
||||
const url = `${baseUrl}/api/users/${username.replace('@', '')}/works`;
|
||||
|
||||
const items = await cache.tryGet(url, async () => {
|
||||
const fetchData = async (retryCount = 0, maxRetries = 3) => {
|
||||
const data = await ofetch(url, {
|
||||
retry: 0,
|
||||
method: 'GET',
|
||||
query: { role: 'creator', sort: 'date', offset: '0' },
|
||||
headers: {
|
||||
'User-Agent': config.ua,
|
||||
Cookie: `request_key=${cache.get('skeb:request_key')}`,
|
||||
Authorization: `Bearer ${config.skeb.bearerToken}`,
|
||||
},
|
||||
}).catch((error) => {
|
||||
if (retryCount >= maxRetries) {
|
||||
throw new Error('Max retries reached');
|
||||
}
|
||||
const newRequestKey = error.response?._data?.match(/request_key=(.*?);/)?.[1];
|
||||
if (newRequestKey) {
|
||||
cache.set('skeb:request_key', newRequestKey);
|
||||
return fetchData(retryCount + 1, maxRetries);
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
return data;
|
||||
};
|
||||
await ensureRequestKey(url);
|
||||
|
||||
const data = await fetchData();
|
||||
const items = await cache.tryGet(url, async () => {
|
||||
const data = await ofetch(url, {
|
||||
retry: 0,
|
||||
method: 'GET',
|
||||
query: { role: 'creator', sort: 'date', offset: '0' },
|
||||
headers: {
|
||||
'User-Agent': config.ua,
|
||||
Cookie: `request_key=${await cache.get('skeb:request_key')}`,
|
||||
Authorization: `Bearer ${config.skeb.bearerToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!data || !Array.isArray(data)) {
|
||||
throw new Error('Invalid data received from API');
|
||||
@@ -86,3 +74,33 @@ async function handler(ctx): Promise<Data> {
|
||||
item: items as DataItem[],
|
||||
};
|
||||
}
|
||||
|
||||
function hasResponseData(error: unknown): error is { response: { _data: string } } {
|
||||
return error !== null && typeof error === 'object' && 'response' in error && typeof (error as { response?: { _data?: unknown } }).response?._data === 'string';
|
||||
}
|
||||
|
||||
async function ensureRequestKey(url: string) {
|
||||
if (await cache.get('skeb:request_key')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ofetch(url, {
|
||||
retry: 0,
|
||||
headers: {
|
||||
'User-Agent': config.ua,
|
||||
Authorization: `Bearer ${config.skeb.bearerToken}`,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (hasResponseData(error)) {
|
||||
const newRequestKey = error.response?._data?.match(/request_key=(.*?);/)?.[1];
|
||||
if (newRequestKey) {
|
||||
cache.set('skeb:request_key', newRequestKey);
|
||||
logger.debug(`Retrieved new request_key: ${newRequestKey}`);
|
||||
} else {
|
||||
logger.error('Failed to extract request_key from error response');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user