How to return blob item from localForage in service worker? - blob

in my service worker i store mp4 video in indexedDB with localforage library in a blob data. It's work ! but i don't know how can i return this blob data.
This is my fetchHandler code :
const fetchHandler = async (event) => {
const getResponse = async () => {
const request = event.request;
if( request.destination === 'video' ){
// Get from indexedDB
const value = await localforage.getItem('video');
// How return the video from indexedDB cache ?
if( value ) return value; // not working
// Add in indexedDB
var networkResponse = await fetch(event.request);
localforage.setItem('video', networkResponse.blob() ).then(function (value) {
// Do other things once the value has been saved.
console.log(value);
}).catch(function(err) {
// This code runs if there were any errors
console.log(err);
});
}else{
const openedCache = await caches.open(SW_CACHE_NAME);
const cacheResponse = await openedCache.match(request);
if (cacheResponse) return cacheResponse;
var networkResponse = await fetch(event.request);
const cachePutResponse = await openedCache.put(request, networkResponse.clone());
if (cachePutResponse) return cachePutResponse;
}
return networkResponse;
};
event.respondWith(getResponse());
};
thanks for your help

You need to pass a valid Response object to event.respondWith(). That entails a response body (which is what you get back from localforeage.getItem()), but also some response headers.
You can use the Response constructor to create that, and return it from your getResponse() function.
The code could look something like:
const value = await localforage.getItem('video');
if (value) {
// See https://fetch.spec.whatwg.org/#bodyinit for what's accepted
// as a BodyInit.
return new Response(value, {
headers: {
// Replace this with the actual MIME type for the video.
'content-type': 'video/mp4',
// Include any other headers here if desired.
}
});
}

Related

Cloudflare worker scheduled response API KV

So previously I tried to store KV when CRON was processed and it works.
Now I tried to store KV based on API responses, and tried the following: https://gist.github.com/viggy28/522c4ed05e2bec051d3838ebaff27258 and Forward body from request to another url for Scheduled (CRON workers) but doesn't seems to work.
What I attempt to do is save response in KV when CRON triggers for access_token and use it in front-end code later on.
Attached is my current attempt:
addEventListener("scheduled", (event) => {
console.log("cron trigger processed..", event);
event.waitUntil(handleRequest());
});
async function handleRequest() {
const url = "<request_url>";
const body = { <credential> };
const init = {
body: JSON.stringify(body),
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8"
}
};
const response = await fetch(url, init);
const results = await gatherResponse(response);
//#ts-ignore
AUTH.put("attempt1", results);
//#ts-ignore
AUTH.put("attempt2", new Response(results, init));
return new Response(results, init);
}
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* #param {Response} response
*/
async function gatherResponse(response) {
const { headers } = response
const contentType = headers.get("content-type") || ""
if (contentType.includes("application/json")) {
return JSON.stringify(await response.json())
}
else if (contentType.includes("application/text")) {
return await response.text()
}
else if (contentType.includes("text/html")) {
return await response.text()
}
else {
return await response.text()
}
}
Both attempt doesn't seems to work (KV not saved):
//#ts-ignore
AUTH.put("attempt1", results);
//#ts-ignore
AUTH.put("attempt2", new Response(results, init));
Is there anything I'm missing?
The calls to NAMESPACE.put() return a Promise that should be awaited - I'd assume that since handleRequest() can return before those are completed (since you're missing the await), they're just being cancelled.
https://developers.cloudflare.com/workers/runtime-apis/kv/#writing-key-value-pairs

How to cancel axios request?

I have TextInput and I need to send request every time when the text is changing
I have this code:
// Main.js
import Api from 'network/ApiManager';
const api = new Api();
// TextInput onChangeText function
const getSearch = useCallback(
async (searchName, sectorTypeId, type, filterData) => {
const result = await api.controller.search(searchName, sectorTypeId, type, filterData);
console.log(result)
},
[],
);
And i have this network layer
// NetworkManager.js
async getData(url) {
try {
const {data: response} = await axios.get(url);
return response;
} catch (e) {
return response;
}
}
controller = {
profile: async (search, sector, f_type, filterData = {}) => {
const res = await this.getData('/url/path');
return this.transformToOptions(res);
},
};
When onChangeText is called, I send a lot of requests, but I want to cancel previous requests and get the latest only. I know that I need to use CancelToken but I don't know how to pass it on my network layer
Please help
You can create a cancelToken, whenever a request comes, you can save the cancel token, when a new request comes, cancelToken won't be undefined, thus you can call cancelToken.cancel(). Try something like this:
let cancelToken
if (typeof cancelToken != typeof undefined) {
cancelToken.cancel("Operation canceled due to new request.")
}
//Save the cancel token for the current request
cancelToken = axios.CancelToken.source()
try {
const results = await axios.get(
`Your URL here`,
{ cancelToken: cancelToken.token } //Pass the cancel token
)

I keep getting "error TypeError: Cannot read properties of undefined (reading 'temp') at updateUI (app.js:66)"

I am making a simple web app using async javascript
I am using api from the open weather map, everything works well except the updating ui
and I keep getting this error TypeError: Cannot read properties of undefined (reading 'temp') at updateUI (app.js:66)"
i think the problem is passing the data to the project data object beacause when i turned it to an array everything worked
this is my server side code
note : i required express, cors and boyparser
let entry = [];
projectData["entry"] = entry;
//post request
app.post('/add', function(request, response) {
let data = request.body;
console.log(data);
let latestEntry = {
temp: data.temp,
date: data.date,
content: data.content
}
entry.push(latestEntry);
response.send(projectData);
});
this is my client side code that I wrote, the updating ui function is not working properly and i am not getting an outout of the temperature however the result shows in the console
//
//Post function
const postData = async (url = '', data = {}) => {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
try {
const newData = await response.json();
return newData;
} catch (error) {
console.log("error", error);
}
}
//update UI function
const updateUI = async () => {
const request = await fetch('/all');
try {
const allData = await request.json();
document.getElementById('temp').innerHTML = `Current temperature: ${allData[0].temp} degree celsius`;
document.getElementById('date').innerHTML = `Today's date: ${allData[0].date} `;
document.getElementById('content').innerHTML = `I feel: ${allData[0].content}`;
} catch (error) {
console.log("error", error);
}
}

React native AsyncStorage bad response

Have created React Native app and ned to use AsyncStorage to benefit from it's storage mechanism.
To save in AsyncStorage use code:
_storeData = async (param) => {
try {
let par = JSON.stringify(param);
//await AsyncStorage.setItem(this.key, par);
Utilities.setItem(this.key, par);
this._retrieveData();
} catch (error) {
console.log(JSON.stringify(error));
}
};
To retrieve data:
_retrieveData = async () => {
try {
const value = Utilities.getItem(this.key);
if (value !== null) {
alert('data is new: ' + JSON.stringify(value));
}
} catch (error) {
}
};
And, to setItem and getItem in Utilities partial:
const setItem = (key, value) => {
if (!key || !value) return;
AsyncStorage.setItem(key, value);
};
const getItem = (key) => {
if (!key) return;
var val = AsyncStorage.getItem(key);
return val;
};
Data is being saved, but response I'm getting does not look correctly, as it's a string of 'weird' characters:
{"_40":0,"_65":0,"_55":null,"_72":null}
Does anybody know why I'm getting such answer?
Note that AsyncStorage.getItem is also async - the weird characters represent the promise being returned by getItem.
Use var val = await AsyncStorage.getItem(key); and mark your getItem utility function as async. You'll need to await on any calls to Utilities.getItem and Utilities.setItem as well.

Can't display from async function result

I need to display in my html variable: {my_dates}. The problem that I can't get it work with fetch but can do with old ajax request.
not working code:
created: function(){
//this.getTableData()
url = 'http://dlang.ru/test'
async function fetchAsync () {
const response = await fetch(url);
return await response.json();
}
this.my_dates = fetchAsync();
}
Working code:
$.ajax({
url: "http://dlang.ru/test",
success: function (data) {
Vue.set(app, "my_dates", data);
app.show = true;
}
});
If you want to be able to assign result of fetchAsync() to this.my_dates then entire created hook method needs to be declared as async.
Then you also need await in front of fetchAsync call:
created: async function () {
const url = 'http://dlang.ru/test';
async function fetchAsync() {
const response = await fetch(url);
return await response.json();
}
this.my_dates = await fetchAsync();
}
Please try this:
created: function(){
//this.getTableData()
url = 'http://dlang.ru/test'
async function fetchAsync () {
const response = await fetch(url);
const data = await response.json();
Vue.set(app, "my_dates", data);
app.show = true;
}
fetchAsync();
}