I've written into an array from input data on Dialogflow using Firestore, like this.
But I don’t know how to fetch data from Firestore to display in Dialogflow, and there's my programming below it.
Here is what I want to achieve. When I input number in Dialogflow, I would like to get an array of number from the Firestore instance.
const db = admin.firestore();
db.settings({timestampsInSnapshots: true});
.
.
.
const sessionId = request.body.session.split("/").reverse()[0]; // or agent.session
function read(agent){
const number = agent.parameters.number; // when I input the number in Fialogflow
const docRef = db.collection('orders').doc(sessionId);
return docRef.get()
.then(doc => {
if (!doc.exists) {
agent.add('No data found in the database!');
console.log(doc);
} else {
agent.add(doc.data().orders);
}
return Promise.resolve('Read complete');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
agent.add('Please add a entry to the database first by saying, "Write <your phrase> to the database"');
});
}
function writeOrderToDb (newOrder) {
const docRef = db.collection('orders').doc(sessionId);
return db.runTransaction(t => {
return t.get(docRef)
.then(doc => {
t.update(docRef, {
orders: admin.firestore.FieldValue.arrayUnion(newOrder)
}, {merge: true});
/*if (!doc.data()) {
t.set(docRef, { orders: [newOrder] });
}
else {
t.update(docRef, {
orders: admin.firestore.FieldValue.arrayUnion(newOrder)
});
}*/
});
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
});
}
function confirmOrder(agent) {
const order = agent.context.get('order'),
amount = order.parameters.amount,
size = order.parameters.size,
type = order.parameters.type;
agent.add(`Confirming ${amount} ${type} in ${size}`);
// important to return, otherwise console.logs will not appear and non-deterministic behavior will ocurr
return writeOrderToDb({
"type": type,
"size": size,
"amount": amount
});
}