Blog

How to Check If an Object Exists in Server-Side Cache

by on September 1, 2019

Previously, we wrote about how to store and retrieve objects to and from server-side in-memory cache. Quite often when working with your cache, it is necessary to check if an object already exists in cache. Backendless provides an API for that function. The code below checks if an object exists in cache, and if not, it places it in there and then runs the existence check again.

    checkInCacheSync();
    addToCacheSync();
    checkInCacheSync();
    
    private static void checkInCacheAsync()
    {
       Backendless.Cache.contains( "myobject", new AsyncCallback<Boolean>()
       {
           @Override
           public void handleResponse( Boolean containsKey )
           {
               Log.i( TAG, "Cache contains key 'myobject' - " + containsKey );
           }
           @Override
           public void handleFault( BackendlessFault backendlessFault )
           {
               Log.e( TAG, "Server reported an error " + backendlessFault.getMessage() );
           }
       } );
    }
    private static void addToCacheAsync()
    {
       Person p = new Person();
       p.name = "James Bond";
       p.age = 42;
       Backendless.Cache.put( "myobject", p, new AsyncCallback<Object>()
       {
           @Override
           public void handleResponse( Object o )
           {
               Log.i( TAG, "Object has been placed into cache" );
           }
           @Override
           public void handleFault( BackendlessFault backendlessFault )
           {
               Log.e( TAG, "Server reported an error " + backendlessFault.getMessage() );
           }
       } );
    }
    

    checkInCacheSync()
    addToCacheSync()
    checkInCacheSync()
    
    private fun checkInCacheAsync() {
       Backendless.Cache.contains("myobject", object : AsyncCallback<Boolean> {
           override fun handleResponse(containsKey: Boolean?) {
               Log.i(TAG, "Cache contains key 'myobject' - " + containsKey!!)
           }
    
           override fun handleFault(backendlessFault: BackendlessFault) {
               Log.e(TAG, "Server reported an error " + backendlessFault.message)
           }
       })
    }
    
    private fun addToCacheAsync() {
       val p = Person()
       p.name = "James Bond"
       p.age = 42
       Backendless.Cache.put("myobject", p, object : AsyncCallback<Any> {
           override fun handleResponse(o: Any) {
               Log.i(TAG, "Object has been placed into cache")
           }
    
           override fun handleFault(backendlessFault: BackendlessFault) {
               Log.e(TAG, "Server reported an error " + backendlessFault.message)
           }
       })
    }
    

    - (void)checkInCache {
        [Backendless.shared.cache containsWithKey:@"myobject" responseHandler:^(BOOL containsKey) {
            NSLog(@"Cache contains key 'myobject' - %@", containsKey ? @"true" : @"false");
        } errorHandler:^(Fault *fault) {
            NSLog(@"Error: %@", fault.message);
        }];
    }
    
    - (void)addToCache {
        Person *person = [Person new];
        person.name = @"James Bond";
        person.age = @42;
        [Backendless.shared.cache putWithKey:@"myobject" object:person responseHandler:^{
            NSLog(@"Object has been placed into cache");
        } errorHandler:^(Fault *fault) {
            NSLog(@"Error: %@", fault.message);
        }];
    }

    func checkInCache() {
        Backendless.shared.cache.contains(key: "myobject", responseHandler: { containsKey in
            print("Cache contains key 'myobject' - \(containsKey)")
        }, errorHandler: { fault in
            print("Error: \(fault.message ?? "")")
        })
    }
        
    func addToCache() {
        let person = Person()
        person.name = "James Bond"
        person.age = 42
        Backendless.shared.cache.put(key: "myobject", object: person, responseHandler: {
            print("Object has been placed into cache")
        }, errorHandler: { fault in
            print("Error: \(fault.message ?? "")")
        })
    }

    Promise.resolve()
      .then(checkInCache)
      .then(addToCache)
      .then(checkInCache)
    
    function checkInCache() {
      return Backendless.Cache.contains('myobject')
        .then(containsKey => console.log(`Cache contains key 'myobject' - ${ containsKey }`))
        .catch(error => console.error(`Server reported an error - ${ error.message }`))
    }
    
    function addToCache() {
      const person = new Person()
      person.name = 'James Bond'
      person.age = 42
    
      return Backendless.Cache.put('myobject', person)
        .then(object => {
          console.log('Object has been placed into cache')
        })
        .catch(error => {
          console.error(`Server reported an error - ${ error.message }`)
        })
    }
    

    await checkInCache();
    await addToCache();
    await checkInCache();
    
     void checkInCache() async {
       await Backendless.cache.contains( "myobject" ).then((containsKey) {
         print("Cache contains key 'myobject' - $containsKey" );
       });
     }
    
     void addToCache() async {
       Person p = Person()
         ..name = "James Bond"
         ..age = 42;
       await Backendless.cache.put( "myobject", p ).then((response) {
         print("Object has been placed into cache");
       });
     }
    

    The first time you run the code it produces the following output:

    Cache contains key 'myobject' - false
    Object has been placed into cache
    Cache contains key 'myobject' - true

    Leave a Reply