简体   繁体   中英

How to create Cloud Function REST API endpoints with the read data from FIrestore

I fairly new to Cloud Functions. I want to do following

  • Read string data from Firestore when new document created
  • Use the string to create REST endpoint such as www.helloworld.com/\ <ReadStringData>

Following is my code

exports.createEndPoint = functions.firestore .document("test/{DocID}")
.onCreate((snap, context) =\> {
console.log("createEndPoint function triggered");
const newValue = snap.data();
console.log(newValue);

    const newEndPoint= newValue.endpoint;
    console.log(newEndPoint);
    
    return new Promise((resolve, reject) => {
      console.log(`/${newEndPoint}`); 
      app.get(`/${newEndPoint}`, (req, res) => {
        console.log("app.get function triggered"); 
        (async () => {
          try {
            console.log("app.get try block triggered"); 
            console.log(response);
            resolve();
          } catch (error) {
            console.log("app.get catch block triggered"); 
            console.log(error);
            reject(error);
          }
        })();
      });
    });

});

exports.app = functions.https.onRequest(app);

However, the problem is www.helloworld.com/newEndPoint is never created. When I send the GET request, it times out.

This what the log shows.

Logs

I tried taking the app.get out of createEndPoint function. It didn't work because app.get never gets the newEndpoint.

let newEndPoint= "";

exports.createEndPoint = functions.firestore
.document("test/{DocID}")
.onCreate((snap, context) =\> {
console.log("createEndPoint function triggered");
const newValue = snap.data();
console.log(newValue);

    newEndPoint= newValue.endpoint;
    console.log(newEndPoint);

});

app.get(`/${newEndPoint}`, (req, res) =\> {
console.log("app.get function triggered");
try {
console.log("app.get try block triggered");
console.log(response);
return res.status(200).send();
} catch (error) {
console.log("app.get catch block triggered\`");
console.log(error);
return res.status(500).send(error);
}
})();
});

exports.app = functions.https.onRequest(app);

I guess my problem is how to bridge the two functions.

What you're trying to do isn't possible. You can't dynamically create an API endpoint using data that created in another trigger. Everything for the express app needs to be defined at the top level of your source code, including all the URL paths, so it can be passed fully to functions.https.onRequest . Other triggers cannot influence that endpoint at all - they each run fully independently of each other.

If you want to change the behavior of your endpoint using data from Firestore, you will have to query Firestore directly from the endpoint code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM