I'm new to cloud functions and firestore and I got an exercise in which I have to update a field in a firestore-document called "Stuttgart" in a "alarms" collection. Whenever the alarm field gets changed, the cloud function should trigger, make a call to the API and receive the current alarm status. Then the function should update the alarm field in a Firestore with the received boolean from the API call.
I tried some code below but I'm not getting any further with it so any help is appreciated
firestore looks like this: alarms (collection) -> stuttgart (document) -> alarm: false (field)
The API call gives a JSON object: {"alarm":false,"infos":[]}
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as rp from 'request-promise';
admin.initializeApp()
const db = admin.firestore();
export const onAlarmsUpdate = functions.firestore.document('alarms/{alarmId}')
.onUpdate((change, context) => {
const options = {
url: 'https://api.bitfactory.io/fineparticlesalarm/',
method: 'GET',
auth: {
'user': 'bitfactory',
'pass': '...'
},
json: true
}
return rp(options).then(data => {
console.log(data.alarm)
db.collection('alarms').doc('stuttgart').set({
alarm: data.alarm
})
.catch(error => {
console.log('Error writing document: ' + error);
return false;
});
});
});