Skip to content

Commit

Permalink
Refactor adapter example for cache to map old one
Browse files Browse the repository at this point in the history
  • Loading branch information
Baltazore committed Oct 16, 2023
1 parent 1da2ce5 commit 2ed06b6
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions snippets/adapters/cache-lifetime/new.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,40 @@ import DataStore from '@ember-data/store';
export default class Store extends DataStore {
constructor(args) {
super(args);
this.lifetimes = new LifetimesService(this, {
apiCacheSoftExpires: 30_000,
apiCacheHardExpires: 60_000
});
// This is default configuration that would be set automatically be Ember Data
// this.lifetimes = new LifetimesService(this, {
// apiCacheSoftExpires: 30_000,
// apiCacheHardExpires: 60_000
// });
this.lifetimes = {
isHardExpired(identifier) {
const cached = this.store.cache.peekRequest(identifier);
const twentyMinutesInMs = 20 * 60 * 1000;

function isStale(headers, expirationTime) {
const date = headers.get('date');

if (!date) {
return true;
}

const time = new Date(date).getTime();
const now = Date.now();
const deadline = time + expirationTime;

const result = now > deadline;

return result;
}

return !cached || !cached.response || isStale(cached.response.headers, twentyMinutesInMs);
},

isSoftExpired(identifier) {
const { downlink, effectiveType } = navigator.connection;

return downlink > 0 && effectiveType === '4g';
}
}
}
}

0 comments on commit 2ed06b6

Please sign in to comment.