Call a Function - C++ SDK Preview
On this page
The examples on this page demonstrate calling an Atlas Function
named concatenate
that takes two arguments, concatenates them, and
returns the result:
// concatenate: concatenate two strings exports = function(a, b) { return a + b; };
Call a Function By Name
Important
Make sure to sanitize client data to protect against code injection when using Functions.
To execute a function from the C++ SDK, use the
call_function()
member function on the user
object. Pass in the name of the
function as a string for the first parameter. This function takes two arguments,
which we provide as a BsonArray
of arguments:
Changed in version 0.2.0: Returns std::future instead of std::promise
// Connect to an App Services App and authenticate a user auto app = realm::App(APP_ID); auto user = app.login(realm::App::credentials::anonymous()).get(); auto sync_config = user.flexible_sync_configuration(); // If a function takes arguments, pass them as BSON auto arg1 = realm::bson::Bson("john.smith"); auto arg2 = realm::bson::Bson("@companyemail.com"); // Call an App Services function as the logged-in user auto result = user.call_function("concatenate", { arg1, arg2 }).get(); // Verify that the result has a value CHECK(result); auto bsonResult = result.value(); // Translate the BSON result back to a string auto resultString = std::string(bsonResult); // Prints "Calling the concatenate function returned john.smith@companyemail.com." std::cout << "Calling the concatenate function returned " << resultString << ".\n";
The callback can provide an optional BSON result, or an optional error. In the example above, we check that the result has a value, and then cast it back to a string.