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.


    Synchronous API:

    checkInCacheSync();
    addToCachetSync();
    checkInCacheSync();
    private static void checkInCacheSync()
    {
        boolean containsKey = Backendless.Cache.contains( "myobject" );
        System.out.println( "Cache contains key 'myobject' - " + containsKey );
    }
    private static void addToCachetSync()
    {
        Person p = new Person();
        p.name = "James Bond";
        p.age = 42;
        Backendless.Cache.put( "myobject", p );
    }

    Asynchronous API:

    private static void checkInCacheAsync()
    {
        Backendless.Cache.contains( "myobject", new AsyncCallback<Boolean>()
        {
            @Override
            public void handleResponse( Boolean containsKey )
            {
                System.out.println( "Cache contains key 'myobject' - " + containsKey );
            }
            @Override
            public void handleFault( BackendlessFault backendlessFault )
            {
                System.out.println( "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 )
            {
                System.out.println( "Object has been placed into cache" );
            }
            @Override
            public void handleFault( BackendlessFault backendlessFault )
            {
                System.out.println( "Server reported an error " + backendlessFault.getMessage() );
            }
        } );
    }

    
    

    - (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 }`)
        })
    }
    

    
    

    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