Both the static and dynamic cache get deleted from the browser when you want to visit another link. So if you go offline and try to make a request you then get an error page instead of a cached response. If you then click the back button in browser and then the forward button the cache comes back and it works. I might have something wrong with verifying the cache on activation?
This is my service worker:
const staticCacheName = "CacheV1";
const dynamicCacheName = "DynamicCacheV1";
const dynamicCacheLimit = 18;
const assets = [
'/',
'/css/main_styles.css',
'/js/ui.js',
'/js/jquery-3.6.0.slim.min.js',
'/icons/search.svg',
'/icons/favicon.svg',
'/img/bg.png',
'/img/og.png',
'/img/generated.svg',
'/icons/at.svg',
'/icons/heartFull.svg',
'/icons/comment.svg',
'/icons/share.svg',
'/icons/report.svg',
'/manifest.json',
'/fonts/titillium-web-300.woff2',
/* ... */
];
// This just deletes access dynamic cache
const limitCacheSize = (name, size) => {
caches.open(name).then(cache => {
cache.keys().then(keys => {
if(keys.length > size) {
cache.delete(keys[0]).then(limitCacheSize(name, size));
}
});
});
}
// Install service worker
self.addEventListener('install', evt => {
evt.waitUntil(
caches.open(staticCacheName).then(cache => {
cache.addAll(assets);
})
);
});
// Activate event
self.addEventListener('activate', evt => {
evt.waitUntil(
caches.keys().then(keys => {
return Promise.all( keys
.filter(key => key !== staticCacheName && key !== dynamicCacheName)
.map(key => caches.delete(key))
)
})
)
});
// Fetch event
self.addEventListener('fetch', evt => {
evt.respondWith(
caches.match(evt.request).then(cacheRes => {
return cacheRes || fetch(evt.request).then(fetchRes => {
return caches.open(dynamicCacheName).then(cache => {
if (evt.request.headers.has('range')) {
return cacheRes;
} else {
cache.put(evt.request.url, fetchRes.clone());
limitCacheSize(dynamicCacheName, dynamicCacheLimit);
return fetchRes;
}
});
});
}).catch(() => {
if (!/./.test(evt.request.url)) {
return caches.match('/img/fallback.html');
} else if(/.jpeg|.jpg|.png|.webp/.test(evt.request.url)) {
return caches.match('/img/fallbackImage.png');
} else if(/.gif/.test(evt.request.url)) {
return caches.match('/img/fallbackImage.png');
} else if(/.mp3|.ogg|.aac|.wav/.test(evt.request.url)) {
return caches.match('/img/beepBoop.mp3');
}
})
)
});
Related
There is a track stored in mongo, it needs to be selected in the ReactNative application (so it doesn’t matter, although the link in the browser), in general, this does not cause problems, but as soon as I try to rewind to an unloaded section, stops the audio. With headers, with bytes, everything seems to be ok.
async playTrack(id: string, res: Response, req: RequestWithTokenData) {
const track = await this.findOneById(id);
if (!track) {
throw new CustomHttpException(ErrorTranslateKey.trackNotFound, HttpStatus.NOT_FOUND);
}
let fondedFile: { length: number, chunkSize: number } | undefined;
const { db } = this.connection;
const bucket = new mongo.GridFSBucket(db, {
bucketName: 'tracks',
});
await bucket.find({ _id: new ObjectId(track.trackId) }).forEach((file) => {
fondedFile = file;
});
if (!fondedFile) {
throw new CustomHttpException(ErrorTranslateKey.trackNotFound, HttpStatus.NOT_FOUND);
}
// #ts-ignore
const { range: rangeHeader } = req.headers;
const range = rangeHeader ? rangeHeader.replace(/bytes=/, '').split('-') : [];
range[0] = range[0] ? parseInt(range[0], 10) : 0;
range[1] = range[1] ? parseInt(range[1], 10) : fondedFile.length;
const { start, end } = { start: range[0], end: range[1] };
const downloadStream = bucket.openDownloadStream(track.trackId);
res.set('content-length', String(end - start));
res.set('content-range', `bytes ${start}-${end - 1}/${fondedFile.length}`);
res.set('content-type', 'audio/mp3');
res.set('accept-ranges', 'bytes');
downloadStream.on('data', (chunk) => {
res.write(chunk);
});
downloadStream.on('error', () => {
res.sendStatus(404);
});
downloadStream.on('end', () => {
res.end();
});
}
I'm using axios to make HTTP request
This is my function to delete a user in my database, I'm using json-server which is installed as a dependency
const deleteThisPerson = (id) => {
// console.log(`${name} is being deleted`);
contactServices
.remove(id)
.then(() => {
const currentContacts = persons.filter(person => person.id !== id)
setPersons(currentContacts)
})
.catch(error => console.log(error))
}
and my http delete request is this
const remove = (id) => {
if (window.confirm(`Delete user?`)) {
const request = axios.delete(`${baseUrl}/${id}`)
return request.then(response => response.data)
} else {
return false
}
}
I have a window.confirm() that pops up when a user tries to delete a resource from the database, it works if I click on Ok but crashes if I click on Cancel, I get the following error message **Uncaught TypeError: _services_persons__WEBPACK_IMPORTED_MODULE_2__.default.remove(...).then is not a function**
How can I correct this?
In the else branch, you are returning false which does not have a then property (false.then is undefined). You can use Promise.reject to return a rejected promise instead.
const remove = (id) => {
if (window.confirm('Delete user?')) {
// ...
} else {
return Promise.reject(new Error('Request cancelled'))
}
}
You can also omit the else clause since you're returning from the if branch.
const remove = (id) => {
if (window.confirm('Delete user?')) {
// ...
}
return Promise.reject(new Error('Request cancelled'))
}
setInterval(() => {
// lets update the config
grid.updateConfig({
server: {
url: document.location.href + 'api.json/',
then: data => data.map(obj => {
return [obj.name, obj.value]
}),
handle: (res) => {
// no matching records found
if (res.status === 404) return { data: [] }
if (res.ok) return res.json()
throw Error('oh no :(')
}
}
}).forceRender()
}, 2000)
This snippet make the work, but loading message and flicking/redraw all table are ruining UX.
I am trying to upload an image to Firebase Storage, however, ref.putfile() leads to the error in the tittle
I didn't find any appropriate resource related to this error
This is where I get image from user:
openPicker = () => {
// More info on all the options is below in the API Reference... just some common use cases shown here
const options = {
title: 'Fotoğraf Seç',
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
const source = { uri: response.uri}
this.setState({
imageMessageSrc: source
});
this.uploadImage();
}
});
}
Then I try to uploadImage to firebase
uploadImage = () => {
console.log("Here");
const filename = this.randIDGenerator// Generate unique name
firebase
.storage()
.ref(`${firebase.auth().currentUser.uid}/sentPictures/${filename}`)
.putFile(this.state.imageMessageSrc)
.then(() => {
console.log("Here1");
})
.catch((error) => {
console.log(error);
})
When I delete putFile, error is gone, but obviously nothing happens to database.
Problem is related to the difference between filePath and fileUri. So, the solution is as below:
openPicker = () => {
const options = {
title: 'Fotoğraf Seç',
storageOptions: {
skipBackup: true,
path: 'images',
allowsEditing: true,
},
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ',response.customButton);
}
else {
var path = '';
if (Platform.OS == 'ios')
path = response.uri.toString();
else {
path = response.path.toString();
}
const image= {
image: response.uri.toString(),
path: path
};
this.uploadImage(image);
}
});
}
uploadImage = (image) => {
firebase.storage().ref(uploadUrl).putFile(image.path);
}
I realized that Firebase Storage putFile function doesn't work with image uri, instead it should be supplied with filePath. I used uri of this image to directly show image on the screen even before upload.
I'm trying to authenticate my user when the page is loading. So I have the following code :
actions: {
nuxtServerInit ({dispatch, commit, app}, context) {
return new Promise((resolve, reject) => {
const cookies = cparse.parse(context.req.headers.cookie || '')
if (cookies.hasOwnProperty('x-access-token')) {
app.$axios.setToken(cookies['x-access-token'], 'Bearer')
api.auth.me2()
.then(result => {
commit('setUser', result.data.user)
resolve(true)
})
.catch(error => {
commit('resetUser')
resetAuthToken()
resolve(false)
})
} else {
resetAuthToken()
resolve(false)
}
})
}
However I have the following error :
Cannot read $axios property of undefined. What is wrong with my code ?
App should come from context e.g. from second argument.
So your code should be
context.app.$axios.setToken(cookies['x-access-token'], 'Bearer')
Another way. You could pass app in the second argument such that
nuxtServerInit ({dispatch, commit}, {app}) {
The complete code:
actions: {
nuxtServerInit ({dispatch, commit}, {app}) {
return new Promise((resolve, reject) => {
const cookies = cparse.parse(context.req.headers.cookie || '')
if (cookies.hasOwnProperty('x-access-token')) {
app.$axios.setToken(cookies['x-access-token'], 'Bearer')
api.auth.me2()
.then(result => {
commit('setUser', result.data.user)
resolve(true)
})
.catch(error => {
commit('resetUser')
resetAuthToken()
resolve(false)
})
} else {
resetAuthToken()
resolve(false)
}
})
}
}