New filters on the Home Feed, take a look!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

3
Help with async/await & promises within a firebase api request function
Post Body

Hi all,

I am new to Firebase and absolutely loving the querying side of it and the ease of use but I am now having to branch out into cloud functions and my node, promises & async knowledge isn't quite where it needs to be for this.

I am sending an SMS to Twilio and a webhook then pings my Firebase API endpoint, I have a telephone number in the POST body which I then use to do the following;

  • Select the user by mobile number then....
  • Select a location record based on the user.currentLocation then.....
  • Select medics attached to that location then.....
  • Raise an alert based on the info above then.....
  • Send an SMS response back to the user using the Twilio library

This all works ok but I am 100% sure that my code stinks and could be refactored using either promises in a better way or async/await. Another obvious issue is I am using docs.forEach when I am only selecting one record but I can work around that, it's the 80-90 lines of code to make a few selects and nesting that I know is the main issue.

I am not asking anyone to rewrite my code here but would really appreciate a nudge in the right direction so I can get on refactoring and ensure that my future code is built in the best way possible. I am bound to look back and use the current code for future functions.

Can anyone give me a bit of advice?

Many thanks.

----------

app.post('/alert/raise/sms', async (req, response) => {
    const client = Twilio('xxxxxx', 'xxxxxx');
    console.log(req.body);

    const dataToSend = {
        Id: uuidv4(),
        location: null,
        user: null,
        geo: {
            latitude: 0,
            longitude: 0,
        },
        medics: <any>[],
    };

    const mobile = parseInt(req.body.From.substr(3), 10);
    let user: any;
    const query = db.collection('users')
        .where('mobile', '==', mobile);

    query.get()
        .then((docs) => {
            docs.forEach(async (doc) => {
                user = doc.data();
            });
            dataToSend.user = user;
            dataToSend.owner = user.Id;
            dataToSend.owner_name = user.firstname   ' '   user.surname;

            const responseData = {
                body: req.body,
                dataToSend: dataToSend,
            };

            if (user) {
                let location:any = null;
                const locationQuery = db.collection('locations')
                    .where('Id', '==', user.currentLocation);

                locationQuery.get()
                    .then((locationsDocs) => {
                        locationsDocs.forEach(async (doc) => {
                            location = doc.data();
                        });
                        dataToSend.location = location;
                        dataToSend.geo.latitude = location.lat;
                        dataToSend.geo.longitude = location.lng;

                        responseData.dataToSend = dataToSend;

                        const medicsQuery = db.collection('locationMedics')
                            .where( "location.Id", "==", location.Id)
                            .where( "granted", "==", true);
                        medicsQuery.get()
                            .then((medicsDocs) => {
                                medicsDocs.forEach(async (medic: any) => {
                                    dataToSend.medics.push(medic.data().user)
                                });

                                db.collection('alerts').add(dataToSend)
                                    .then(() => {
                                        return client.messages.create({
                                            body: 'Your alert has been raised and you will receive a response very shortly ',
                                            to: req.body.From,
                                            from: ' 447400000000',
                                        })
                                            .then(async smsData => {
                                                response.json(responseData);
                                            })
                                            .catch(err => {
                                                response.json(err);
                                            });

                                    })
                                    .catch((err) => {
                                        response.json(err);
                                    });
                            })
                            .catch(err => {
                                return err;
                            });
                    })
                    .catch(err => {
                        return err;
                    });

            } else {
                response.json(responseData);
            }
        })
        .catch(err => {
            return err;
        });
});

Author
Account Strength
90%
Account Age
7 years
Verified Email
Yes
Verified Flair
No
Total Karma
691
Link Karma
293
Comment Karma
398
Profile updated: 4 days ago
Posts updated: 1 month ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
5 years ago