1

I am using firebase function to write the data into the database. The function I am using is triggered by HTTP call (only POST). I was able to save the data to the database, however, couldn't return the data in proper format. I am getting, the following error

TypeError: snapshot.val is not a function

export const saveOrder = functions.https.onRequest(((request, response) => {

    if (request.method == "POST") {

        const data = JSON.stringify(request.body);
        let jsonData = data.replace(/\r?\n\t?/g, '');

        let object = {order: JSON.parse(jsonData), status: "pending"};

        return admin.database()
            .ref("orders")
            .push(object)
            .then(function (snapshot) {
                return response.send(200, snapshot.val());
            });
    } else {
        response.contentType("application/json");
        response.status(400).send('{"message":"Invalid method"}');
        return;
    }
}));

1 Answer 1

2

The .push() method doesn't return a Snapshot data, it returns a Reference.

You can get the key of the new reference:

    .then((reference) => { return response.send(200, reference.key) });

To return the data in a proper format, you can return the object that you are passing to Firebase:

return admin.database() ref("orders").push(object)
        .then(function(reference) {
            return response.send(200, {
                  key: reference.key,
                  data: object,
            });
        });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.