Blog

How to Fetch an Application’s User Objects

by on September 1, 2019

The user accounts of a Backendless application are managed by the User Service, part of our user management feature. However, the data for the accounts is stored in the Data Service storage. As a result, you can use the Data Service API to load the user objects for an application. Moreover, any search queries, paging, and sorting supported by the Data Service API apply directly to fetching the user accounts.

Consider an application with the following user accounts:

The sample below demonstrates the loading of all user objects in an app. It is simply a matter of modifying the search query parameters to enable sorting or additional data filtering (i.e. loading with an SQL query, aka the “where clause”).

    Backendless.Data.of(BackendlessUser.class).find(new AsyncCallback<List>() {
       @Override
       public void handleResponse(List users) {
           for (BackendlessUser user : users) {
               Log.i(TAG, "Email - " + user.getEmail());
               Log.i(TAG, "User ID - " + user.getUserId());
               Log.i(TAG, "Phone Number - " + user.getProperty("phoneNumber"));
               Log.i(TAG, "============================");
           }
       }
    
       @Override
       public void handleFault(BackendlessFault fault) {
           Log.e(TAG, fault.getMessage());
       }
    });

    Backendless.Data.of(BackendlessUser::class.java).find(
       object : AsyncCallback<List> {
           override fun handleResponse(users: List?) {
               users?.let {
                   for (user in it) {
                       Log.i(TAG, "Email - ${user.email}")
                       Log.i(TAG, "User ID - ${user.userId}")
                       Log.i(TAG, "Phone Number - ${user.getProperty("phoneNumber")}")
                       Log.i(TAG, "============================")
                   }
               }
           }
    
           override fun handleFault(fault: BackendlessFault?) {
               Log.e(TAG, fault?.message)
           }
       }
    )

    [[Backendless.shared.data of:[BackendlessUser class]] findWithResponseHandler:^(NSArray *users) {
        for (BackendlessUser *user in users) {
            NSLog(@"Email - %@", user.email);
            NSLog(@"User ID - %@", user.objectId);
            NSLog(@"Phone number - %@", [user getPropertyWithPropertyName:@"phoneNumber"]);
            NSLog(@"============================");
        }
    } errorHandler:^(Fault *fault) {
        NSLog(@"Error: %@", fault.message);
    }];

    Backendless.shared.data.of(BackendlessUser.self).find(responseHandler: { users in
        if let users = users as? [BackendlessUser] {
            for user in users {
                print("Email - \(user.email)")
                if let userId = user.objectId {
                    print("User ID - \(userId)")
                }
                if let phoneNumber = user.getProperty(propertyName: "phoneNumber") as? String {
                    print("Phone number - \(phoneNumber)")
                }
                print("============================")
            }
        }
    }, errorHandler: { fault in
        print("Error: \(fault.message ?? "")")
    })

    const Backendless = require('backendless')
    /*
     Or use `import Backendless from 'backendless'` for client side.
     If you don't use npm or yarn to install modules, you can add the following line
     <script src="//api.backendless.com/sdk/js/latest/backendless.min.js"></script>
     to your index.html file and use the global Backendless variable.
    */
    
    Backendless.initApp('YOUR_APP_ID', 'YOUR_JS_API_KEY')
    
    const PAGE_SIZE = 100 // max possible value
    
    const fetchAllObjects = async tableName => {
      let offset = 0
      let totalCount = 0
      let lastPageSize = 0
      const itemsCollection = []
    
      do {
        const pageQuery = Backendless.DataQueryBuilder.create()
    
        pageQuery.setPageSize(PAGE_SIZE)
        pageQuery.setOffset(offset)
    
        const items = await Backendless.Data.of(tableName).find(pageQuery)
    
        lastPageSize = items.length
    
        itemsCollection.push(...items)
    
        offset += PAGE_SIZE
        totalCount += lastPageSize
      } while (lastPageSize >= PAGE_SIZE)
    
      return itemsCollection
    }
    
    const onSuccess = users => {
      users.forEach(user => {
        console.log(`Email - ${ user.email }`)
        console.log(`User ID - ${ user.objectId }`)
        console.log(`Phone Number - ${ user.phoneNumber }`)
        console.log('============================')
      })
    }
    
    const onError = error => {
      console.error('Server reported an error: ', error.message)
      console.error('error code: ', error.code)
      console.error('http status: ', error.status)
    }
    
    Promise.resolve()
      .then(() => fetchAllObjects('Users'))
      .then(onSuccess)
      .catch(onError)
    

    Backendless.Data.of("Users").find().then((users) {
      for (Map user in users) {
        print("""
    Email - ${user['email']}
    User ID - ${user['objectId']}
    Phone Number - ${user['phoneNumber']}
    ============================""");
      }
    });

    The program output is:

    Email - foo@backendless.com
    User ID - DC7A6B12-7249-3E8E-FF66-0E8A26743A00
    Phone Number - 314-987-6543
    ============================
    Email - spidey@backendless.com
    User ID - D866FD8A-54BC-99CF-FF16-05265D15A100
    Phone Number - 512-123-4567
    ============================
    Email - goblin@backendless.com
    User ID - 52040411-97A5-5E34-FF00-83FCAD51E500
    Phone Number - 212-555-1212
    ============================

    Notice the code uses the find() method from the Data Service API. It is important to understand that the demonstrated approach and all its variations are applicable to the Users table in Backendless.

    Enjoy!

    Leave a Reply