Cloud Function example on Google docs onCreate not triggering - google-cloud-firestore

I am currently extremely confused as to why the below code is not running properly. I am following the exact steps from: https://firebase.google.com/docs/functions/get-started and I just can't get the second cloud function makeUpperCase to trigger. Any help would be greatly appreciated!
exports.addMessage = functions.https.onRequest(async (req, res) => {
const original = req.query.text;
const writeResult = await admin.firestore().collection('messages').add({ original: original });
res.json({ result: `Message with ID: ${writeResult.id} added.` });
});
exports.makeUppercase = functions.firestore.document('/messages/{documentId}').onCreate((snap, context) => {
const original = snap.data().original;
functions.logger.log('Uppercasing', context.params.documentId, original);
const uppercase = original.toUpperCase();
return snap.ref.set({ uppercase }, { merge: true });
});

You have to deploy Cloud Functions code before it gets triggered. The triggers are only going to work against actual database data when running in Google Cloud. Simply writing the code locally isn't going to work, and the local emulators will not work either. In order to get actual changes from actual document data in Firestore, the code must be deployed.

Related

Firebase Functions logs working, but Flutter returns null

I'm trying to display Firestore data in a Flutter app. To do that, I created a Firebase function like the following:
exports.getHouses = functions.https.onCall((data, context) => {
let pathBeginning = "users/";
console.log(data.userID);
let path = pathBeginning.concat(data.userID, "/houses");
let houses = [];
admin.firestore().collection(path).get().then(snapshot => {
console.log("COLECTION WHERE DOCUMENTS ARE RETREIVED:");
console.log(path);
snapshot.forEach(doc => {
let newHouse = {
"id": doc.id,
"address": doc.data().address
}
houses = houses.concat(newHouse);
});
console.log("THE FOLLOWING LOG SHOULD RETURN THE FULL LIST OF HOUSES:")
console.log(houses);
return houses;
}).catch(reason => {
response.send(reason);
});
});
I think this part works properly, because logs in Firebase look exactly as expected:
Firebase logs
The problem happens when I try to print this data in my Flutter app. To do so, I use the following code:
Future<void> listHouses() async {
var parameters = {
"userID": "1"
};
HttpsCallable getHouses = FirebaseFunctions.instance.httpsCallable("getHouses");
await getHouses.call(parameters).then((HttpsCallableResult response) {
print(response.data);
});
}
When called the funtion, it always returns null, even when Firebase log displays everything properly.
I would appreciate if anyone can help me solving this issue. Thank you in advance.
You're missing a return in front of your get() call. Without that, the Cloud Functions container doesn't know about the asynchronous get() operation and thus will/may terminate the function before loading the data completes.
To fix this, add return:
return admin.firestore().collection(path).get().then(snapshot => {
...
This is an extremely common problem within Cloud Functions and when dealing with asynchronous APIs in general, so I recommend taking a moment to read the Firebase documentation on terminating functions and watching the video series linked in there.

how to fix UNAUTHENTICATED error while trying to create an asset report using PLAID? Plaid createAssetReport using cloud function

I'm trying to create an asset report from Plaid, I'm using Cloud Functions for these calls, all the other cloud functions work (link, transactions, balance) but assetReportCreate fails and return UNAUTHENTICATED

The Plaid logs do not show the call...so I guess something is wrong in my Cloud Function, but the Google Console Logs show status 200.
has anybody experienced the same issue and know how to fix it?
PS: just double checked today to make sure I'm authenticated and I am...
//create ASSET report
exports.createAssetReport = functions.https.onCall(async (data, context) => {
const accessToken = data.accessToken;
const daysRequested = data.daysRequested;
// const options = {
// client_report_id: '123',
// webhook: "https://www.example.com", //to let you know when report is ready, get link from cloud console
// };
const configuration = new Configuration({
basePath: PlaidEnvironments[functions.config().app.env],
baseOptions: {
headers: {
"PLAID-CLIENT-ID": functions.config().plaid.client_id,
"PLAID-SECRET": functions.config().plaid.secret,
},
},
});
const plaidClient = new PlaidApi(configuration);
//call the createLinkToken METHOD of the plaidClient instance!
return plaidClient
.assetReportCreate({
access_tokens: [accessToken],
days_requested: daysRequested,
//options,
})
.then((response) => {
const assetReportId = response.data.asset_report_id;
const assetReportToken = response.data.asset_report_token;
return assetReportToken; //token is needed to retrieve the report via //pdf/get
})
.catch((err) => {
console.log(err);
throw new functions.https.HttpsError(
"internal",
" Unable to create asset report: " + err
);
});
});
I found that for whatever reason the function wasn't open for all users to invoke, adding a principal with role: "cloud functions invoker" fixed the issue, shame on you google cloud, I spent two full days on this!! jk, thanks for your services but fix these small details and you could become the #1 cloud provider

Mongoose save method seems to not be working

I am trying to create a REST API. I am pretty new to the back end and am just practicing on my own for the time being. For my code, I know it's bad practice to store the plain text password but again, this is completely for practice and will never go live. I will also add encryption at a later point for practice.
My issue is I am not sure why my API does not work. I see where it fails, it fails in the catch block when I try to save a user but I do not get any error to tell me what is wrong exactly, besides the once I force. I have another part on this website that follows almost the exact same logic and it works perfectly but for this one it does not. I have no idea how to solve my issue but after googling I still cannot figure it out. It looks perfectly fine too me, but as mentioned I am pretty new to the backend.
This is my controller function:
const signup = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(new HttpError('Invalid inputs passed, please check your data', 422));
}
const { name, email, password, places } = req.body;
let existingUser;
try {
existingUser = await User.findOne({email: email}) // finds one document matching our criteria we set
} catch(err) {
const error = new HttpError('Signing up failed, please try again later', 500);
return next(error);
}
if (existingUser) {
const error = new HttpError('User exists already, please login instead', 422);
return next(error);
}
const createdUser = new User({
name,
email,
image: 'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260',
password,
places
});
try {
await createdUser.save();
} catch(err) {
const error = new HttpError(
'Signing up failed', 500
);
return next(error);
}
res.status(201).json({user: createdUser.toObject({ getters:true })});
};
I use Postman to send the request to my API endpoint with all of the correct information. Based on what I recieve back it is failing in the try catch block of await createdUser.save()
For anyone who finds this from google this was my solution:
First I suggest you add this into your save method to try and diagnose the problem
await createdUser.save(function(err){
if(err){
console.log(err);
return;
}
});
This help me greatly as it gave me more information on how to solve it.It turns out my problem was because I misspelled a field in my Schema. So extremely simple solution!

How to trigger Google Composer Airflow dag using appscript?

I want to trigger a Google Composer airflow dag using Appscript. Is there any way to do it via rest API or another way.
If it is possible please suggest the solution.
Airflow has an endpoint that allows to trigger a DAG through its REST API, however it’s not possible to access it directly, since within the Cloud Composer architecture, the Airflow web server is located under an App Engine flexible environment. By default, the Airflow web server is integrated with Identity-Aware Proxy (IAP) and authentication is required.
Based on that, I found an example in the Cloud Composer documentation, that guides you to trigger a DAG using Cloud Functions, although the code is in JavaScript I don’t think it’s possible to execute it by Google App Script.
On the other hand, a workaround is to follow the Triggering DAGs guide changing some settings as follows.
In the creation of the function instead of setting the trigger type as Cloud Storage set it as HTTP, and check the “Allow unauthenticated invocations” for test purpose. An URL will be displayed, the goal is that every time that URL is accessed the DAG is executed.
Modify the first part of the index.js file, since no data would be passed as parameters and also the makeIapPostRequest function to return the response of the API call.
exports.triggerDag = async (req, res) => { // Modification
// Fill in your Composer environment information here.
// The project that holds your function
const PROJECT_ID = 'your-project-id';
// Navigate to your webserver's login page and get this from the URL
const CLIENT_ID = 'your-iap-client-id';
// This should be part of your webserver's URL:
// {tenant-project-id}.appspot.com
const WEBSERVER_ID = 'your-tenant-project-id';
// The name of the DAG you wish to trigger
const DAG_NAME = 'composer_sample_trigger_response_dag';
// Other constants
const WEBSERVER_URL = `https://${WEBSERVER_ID}.appspot.com/api/experimental/dags/${DAG_NAME}/dag_runs`;
const USER_AGENT = 'gcf-event-trigger';
const BODY = {conf: ‘’}; // Modification
// Make the request
try {
const iap = await authorizeIap(CLIENT_ID, PROJECT_ID, USER_AGENT);
const apiReponse = await makeIapPostRequest(WEBSERVER_URL, BODY, iap.idToken, USER_AGENT); // Modification
res.status(200).send('DAG_running!'); // Modification
} catch (err) {
console.error('Error authorizing IAP:', err.message);
throw new Error(err);
}
};
const makeIapPostRequest = async (url, body, idToken, userAgent) => {
const res = await fetch(url, {
method: 'POST',
headers: {
'User-Agent': userAgent,
Authorization: `Bearer ${idToken}`,
},
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.text();
console.error('Error making IAP post request:', err.message);
throw new Error(err);
}
return {
apiRes: res.ok, // Modification
};
};
At this point, anything else has to be changed, so in your Script file execute the next instructions in order to trigger the DAG.
function myFunction() {
var response = UrlFetchApp.fetch("Cloud-function-URL");
Logger.log(response.getAllHeaders());
}
Finally, verify in the Airflow web interface if the DAG was triggered.

How to query firestore with the Dialogflow inline editor to get information

I am using the inline editor within Dialogflow with the aim of making queries to the database I have created within Firestore.
In short, the user requests a list of courses, I'd like the chatbot to then grab that information form the db and display that back to the user.
Below I have tried to create a function that will do this, I want to take the user input, say "Art Courses" and have my db return those results.
So far, I have created a function that is triggered when the intent is matched, like so;
function getCourses(agent){
let courseRequest = agent.parameters.courseRequest;
if (getCourses){
console.log('Here is the list you requested for ${getCourses}' + parameters.courseRequest);
return admin.firestore().collection('Course_Information').doc.where('CoureTypes').get();
}
}
Are there any notable things I need to add to my function to perform what I wish to achieve?
Thank you.
UPDATE
This code deploys fine, but when I communicate with my bot and trigger the CourseEnquiry intent, cloud Functions shows this error:
admin.collection is not a function
Whilst this seems self explanatory I can't make sure of what it means, I thought declaring const admin = require('firebase-admin');enables me to use admin.collection
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function getDate(agent){
var today = new Date();
}
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function test(agent){
agent.add("The test is successful");
}
function getCourses(agent){
// Get the database collection and document
const getCourseDoc = admin.collection('Course_Information').doc('Course_Types');
return getCourseDoc.get()
.then(doc => {
if (!doc.exists) {
agent.add('No data found in the database!');
} else {
agent.add(doc.data().entry);
}
return Promise.resolve('Here is the information you wanted');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
});
}
function getSubmissionDateSep(agent){
agent.add('Your next submission date is for coursework 1 is');
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Test_Test', test);
intentMap.set('CourseEnquiry', getCourses);
intentMap.set('Submission_Dates - sept', getSubmissionDateSep);
agent.handleRequest(intentMap);
});
UPDATE #2
Hey guys, still not got anywhere with this, I have tried adding:
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
According to this document but I get this error when deploying:
The deployment of your Cloud Function failed:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: Error: Firebase config variables are not available. Please use the latest version of the Firebase CLI to deploy this function.
You don't show how you're responding to the user with your results, but you'll want to make sure you handle that as part of the then() clause in a Promise. Since the get() in the firestore collection returns a Promise, and you are returning it from your function, you need to make sure that the calling function treats it as a Promise, has a then() clause, and sends back the result as part of something inside this clause.