I started to learn cloud functions. What I wish to achieve is sending json to cloud function and get all documents with same phone numbers that I send in json.
Cloud function:
exports.getUsers = functions.https.onRequest(async (request, response) => {
const data = request.body.data;
if (data !== null && data.users !== null) {
const users = data.users;
const phonelist = users.map(user => user.phone.toString());
const userlist = []
const snapshot = await db.collection("users").get()
snapshot.docs.forEach((userDoc) => {
const phone = userDoc.get("phone")
if(phone === null) return;
const isContain = phonelist.reduce((acc, num) => acc || phone.includes(num), false)
if(isContain) {
userlist.push(userDoc.data())
}
})
response.status(200).json({result: userlist})
} else{
response.sendStatus(403)
}
});
Ma call in Android:
private fun addMessage(): Task<String>? {
// Create the arguments to the callable function.
val data = "{\n"
" \"data\": {\n"
" \"users\": [\n"
" {\n"
" \"phone\": 55512345\n"
" },\n"
" {\n"
" \"phone\": 972525276676\n"
" },\n"
" {\n"
" \"phone\": 55512347\n"
" }\n"
" ]\n"
" }\n"
"}"
functions.getHttpsCallable("getUsers")
.call(data)
.addOnFailureListener {
Log.d("DTAG", it.toString())
}
.addOnSuccessListener {
Log.d("DTAG","Ok: ${it.data.toString()}")
}
return null
}
I getting an error from cloud function: Cannot read properties of undefined (reading 'map')
CodePudding user response:
You shouldn't provide raw strings as JSON to the Firebase SDK. Instead, provide a Map<String, Object>
if you want it to automatically convert that to a JSON Object. There is an example in the documentation. Firebase handles the JSON input and output on both ends so all you have to do is deal with native language data structures that come from the JSON, which is far more convenient and less error prone than manually building JSON.