I´m having a problem to return a promise inside my onCall function, while trying to retrieve sub-collections with getCollections()
I have a document with sub-collections. And each sub-collection has a document. I´m trying to retrieve all this structure structure
I have the code below with 2 structures, but they are failing to return the data. I´m not understanding the structure to\when return the value
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp()
exports.rs = functions.https.onCall( async (data, context) => {
let cols = []
return await new Promise( async (res, rej) => {
let required_ref = admin.firestore().collection('required_services')
.doc(data.user_id)
return await required_ref.get()
.then(async () => {
let collections = await required_ref.getCollections()
console.log('collections', collections)
collections.forEach(async collection => {
let docs = await collection.get()
console.log('docs for collection', collection.id)
docs.forEach(doc => {
console.log('doc', doc)
let doc_ = {
id: doc.id,
data: doc.data()
}
cols.push(doc_)
})
})
console.log('inside async', cols)
res(cols)
})
})
})
exports.requiresServices = functions.https.onCall( async (data, context) => {
// const docs = () => {
let required_ref = admin.firestore().collection('required_services')
.doc(data.user_id)
let cols = []
return await required_ref.get()
.then(async () => {
let collections = await required_ref.getCollections()
console.log('collections', collections)
collections.forEach(async collection => {
let docs = await collection.get()
console.log('docs for collection', collection.id)
docs.forEach(doc => {
console.log('doc', doc)
let doc_ = {
id: doc.id,
data: doc.data()
}
cols.push(doc_)
})
})
console.log('inside async', cols)
return cols
})
})
exports.getRequiredServices = functions.https.onCall( (data, context) => {
let required_ref = admin.firestore().collection('required_services')
.doc(data.user_id)
let cols = []
let first = () => {
console.log('inside first')
let promise = new Promise( (res, rej) =>{
required_ref.get().then( () => {
return required_ref.getCollections().then(collections => {
res(collections)
})
})
} )
return promise
}
let second = collections => {
console.log('inside second')
new Promise( (res, rej) => {
collections.forEach(collection => {
console.log('collection', collection)
collection.get().then(docs => {
return docs.forEach(doc => {
console.log('each doc inside each collection first ', doc.id, '=>', doc.data())
let doc_ = {
id: doc.id,
data: doc.data()
}
cols.push(doc_)
})
})
console.log('return inside two, cols', cols)
})
res(cols)
})
}
return first().then(second => second)//.then(third)
})
The error in the console is showing
Error: internal
at new HttpsErrorImpl (index.cjs.js?001a:58)
at _errorForResponse (index.cjs.js?001a:153)
at Service.eval