JSON received from web socket call. Caching is not working. It’s returning an empty cache object
Whole code:
// Set the URL of the WebSocket API endpoint
const apiUrl = 'wss://ws.';
const baseUrl = 'https://worker.onlineworldtrade.com';
const uniqueId = Date.now().toString();
// Define the cache key for the API response
const cacheKey = `${baseUrl}?id=${uniqueId}`;
// Define the expiration time in milliseconds for the cached API response
const expirationTime = 10000;
// Define the headers for the API response
const responseHeaders = {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,HEAD,POST,OPTIONS',
'Cache-Control': 'max-age=10, s-maxage=10'
};
// Define a function to fetch the API response
async function fetchApiResponse(region) {
// Check if the API response is already cached
const cachedResponse = await getCachedApiResponse();
if (cachedResponse) {
console.log(cachedResponse, 11)
return cachedResponse;
} else {
console.log(cachedResponse, 12)
// Make a new API request
const ws = new WebSocket(apiUrl);
return new Promise((resolve, reject) => {
ws.onopen = () => {
const requestData = {
trading_platform_asset_listing: 1,
platform: 'mt5',
type: 'brief',
region: region,
};
ws.send(JSON.stringify(requestData));
};
ws.onerror = reject;
ws.onmessage = (event) => {
try {
const responseData = JSON.parse(event.data);
// Cache the API response
cacheApiResponse(responseData);
resolve(responseData);
} catch (err) {
reject(err);
}
};
});
}
}
// Define a function to get the cached API response
async function getCachedApiResponse() {
const cache = caches.default;
const cachedResponse = await cache.match(cacheKey);
if (cachedResponse) {
const responseJson = await cachedResponse.json();
// Check if the cached response has expired
if (Date.now() - responseJson.timestamp < expirationTime) {
return new Response(JSON.stringify(responseJson.data), { headers: responseHeaders });
} else {
// Remove the expired cached response
await cache.delete(cacheKey);
return null;
}
} else {
return null;
}
}
// Define a function to cache the API response
async function cacheApiResponse(response) {
const cache = caches.default;
const cacheOptions = {
expirationTtl: expirationTime / 1000,
};
const cacheResponse = new Response(JSON.stringify({
data: response,
timestamp: Date.now(),
}), {
headers: responseHeaders,
});
console.log(cacheResponse, cacheOptions, 11)
await cache.put(cacheKey, cacheResponse, cacheOptions);
console.log(cache, 12)
}
// Define the main worker function
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
// Define the handleRequest function
async function handleRequest(request) {
const url = new URL(request.url)
const region = url.searchParams.get('region') || 'row'
try {
const apiResponse = await fetchApiResponse(region);
return new Response(JSON.stringify(apiResponse), { headers: responseHeaders });
} catch (err) {
return new Response(err.message, { status: 500 });
}
}
Data is returned perfectly
200 OK
access-control-allow-methods:GET,HEAD,POST,OPTIONS
access-control-allow-origin:*
cache-control:max-age=10, s-maxage=10
content-length:4915
content-type:application/json;charset=UTF-8
{"echo_req":{"platform":"mt5","region":"row","trading_platform_asset_listing":1,"type":"brief"},"msg_type":"trading_platform_asset_listing","trading_platform_asset_listing":{"mt5":{"assets":[{"ask":266650.22,"bid":266512.72,"day_percentage_change":"-6.70%","display_order":1,"market":"derived","shortcode":"R_75","spread":137.5,"symbol":"Volatility 75 Index"},{
This is returned in console,
null 12
worker.js:88 Response {…} {expirationTtl: 10} 11
worker.js:90 Cache {} 12
Note: I am using a custom domain. My clouldflare worker code is attached Thanks in Advance.