@@ -28,37 +28,44 @@ npm install cacheables
2828
2929``` ts
3030// Import Cacheables
31- import { Cacheables } from ' cacheables'
31+ import { Cacheables } from " cacheables"
32+
33+ const apiUrl = " https://goweather.herokuapp.com/weather/Karlsruhe"
3234
3335// Create a new cache instance
3436const cache = new Cacheables ({
3537 logTiming: true ,
38+ log: true
3639})
3740
38- // Use the method `cacheable` to set and get from the cache
39- const cachedApiQuery = (locale : string ) =>
40- cache .cacheable (
41- () => apiQuery (locale ),
42- Cacheables .key (' key' , locale ),
43- 60e3 ,
44- )
41+ const wait = (ms : number ) => new Promise ((resolve ) => setTimeout (resolve , ms ))
4542
46- await cachedApiQuery ( ' de ' )
47- // Cache miss: initial call.
48- // In this example, the response of apiQuery('de') will be
49- // cached for 60 seconds with the key 'key:de'.
43+ // Use the method `cacheable` to both set and get from the cache
44+ const fetchCached = ( url : string , key : string , timeout ? : number ) => {
45+ return cache . cacheable (() => fetch ( url ), key , timeout )
46+ }
5047
51- // key:de: 120.922ms
48+ const getWeatherData = async () => {
49+ // Fetch weather and cache for 5 seconds.
50+ const freshWeatherData = await fetchCached (apiUrl , " weather" , 5e3 )
51+ console .log (freshWeatherData )
5252
53- await cachedApiQuery ( ' de ' )
54- // Cache hit: resource with key "key:de" is in cache.
53+ // wait 2 seconds
54+ await wait ( 2e3 )
5555
56- // key:de: 0.029ms
56+ // Fetch cached weather, set the timeout to 1 second.
57+ const cachedWeatherData = await fetchCached (apiUrl , " weather" , 1e3 )
58+ console .log (cachedWeatherData )
5759
58- await cachedApiQuery (' en' )
59- // Cache miss: resource with key "key:en" is not in cache.
60+ // wait 5 seconds
61+ await wait (3e3 )
62+
63+ // Fetch again, this time the cache is not present anymore.
64+ const againFreshWeatherData = await fetchCached (apiUrl , " weather" )
65+ console .log (againFreshWeatherData )
66+ }
6067
61- // key:en: 156.538ms
68+ getWeatherData ()
6269```
6370
6471` cacheable ` serves both as the getter and setter. This method will return a cached resource if available or use the provided argument ` resource ` to fill the cache and return a value.
0 commit comments