I am currently writing a multi tenancy app. The app stores data in Firestore/Algolia & I have a cloud function to query the index. This is so that a user can only access data of the tenant they belong to.
The search works fine, but the cloud function keeps on returning null, although the logs shows the search results.
I suspect that the object returned by the Algolia JS client cannot be converted to JSON, hence the httpcallable framework is returning null. Below is a snapshot of the code.
I have tried to stringfy the object using JSON.stringify but no luck. Any ideas?
exports.getCustomerSuggestions = functions.region('europe-central2').https.onCall(async (data, context) => {
if(!context.auth){
throw new functions.https.HttpsError(
'unauthenticated',
'Authentication required.'
);
}
const uid = context.auth.uid;
functions.logger.info("Processing request from user " uid " with data: " JSON.stringify(data));
const client = algoliasearch(algoliaAppId, algoliaApiKey);
const index = client.initIndex(angoliaIndex);
userData = await getUserData(uid);
userData = prepForFirestore(userData.data()); // strip object properties
const searchTerm = data.query;
const filters = 'serviceProviderId:' userData.tenantId;
var result;
index.search(searchTerm, {
filters: filters
}).then(({hits}) => {
result = hits;
functions.logger.info("Returning: " JSON.stringify(result)); //The log shows the search results
});
return {status: true, data: result}; // data is returned as null
});
CodePudding user response:
since index.search
is asynchronous your function returns
before the search finishes. You can try to await
the index.search
call so that it will wait till the call finishes and after that return
const result = await index.search(searchTerm, {
filters: filters
})
return {status: true, data: result.hits}