I have 2 trigger functions in an index.js file.
const functions = require("firebase-functions");
//const addTrxns = require("./trxnAdd.js");
const admin = require("firebase-admin");
const { user } = require("firebase-functions/lib/providers/auth");
const { event } = require("firebase-functions/lib/providers/analytics");
//exports.addTrxns.addTrxns;
admin.initializeApp();
const db = admin.firestore();
exports.userProfileChanged = functions.firestore.document('/agents/{userId}').onWrite( async (change, context) => {
const userId = context.params.userId;
console.log('A change has been made to user profile');
const getUserDeviceToken = await db.collection('device').doc(userId).get();
.
.
.
return Promise.all(console.log('End of function'));
});
/* ======================================================================== */
exports.onTrxnCreate = functions.document('/trxns/{trxnId}').onCreate((snap, context) => {
const userId = context.params.userId;
console.log('A new transaction has been added');
const getUserDeviceToken = await **db.collection('device').doc(userId).get();**
return Promise.all(console.log('End of function'));
});
I get this error, "Parsing error: Unexpected token db" in the second function. I think it has something to do with the "await" but I don't know enough about this to fix it. How can I fix this error?
Thanks.
I figured this out. I was missing "async" in the second function.
Related
const IgApiClient = require('instagram-private-api').IgApiClient;
const fs = require('fs');
const config = require('./config.json');
const ig = new IgApiClient();
ig.state.generateDevice(config.instagramUsername);
ig.state.proxyUrl = config.igProxy;
async function uploadImage(imageBuffer) {
const imageUrl = await ig.upload.photo(
{
file: imageBuffer
}
);
console.log(`URL: ${imageUrl}`);
}
(async () => {
await ig.simulate.preLoginFlow();
const loggedInUser = await ig.account.login(config.instagramUsername, config.instagramPassword);
process.nextTick(async () => await ig.simulate.postLoginFlow());
const imageBuffer = fs.readFileSync('output.png');
uploadImage(imageBuffer);
})();
Error:
C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126
return new errors_1.IgResponseError(response);
^
IgResponseError: POST /rupload_igphoto/1672943340753_0_8268117741 - 400 Bad Request;
at Request.handleResponseError (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126:16)
at Request.send (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:54:28)
at async UploadRepository.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\repositories\upload.repository.js:18:26)
at async uploadImage (C:\Users\PC\Desktop\spotted\bomba.js:10:20)
Node.js v19.2.0
Hello, I've been trying to create an app, which will automatically post generated images on instagram, but there's a problem, it doesn't work even if i do it as it is intended in documentation (probably). Does anyone have any ideas?
ideally id like to move the line out of the function entirely but the only way i know to do this is in the function itself. the 'poolConnection' seems to be of the type 'mysql.PoolConnection', so id assume the query function is something like 'mysql.PoolConnection.query', but i cant find any way to modify the 'query' without writing it like 'poolConnection.query', which ties it to that specific connection. it seems like there should be a easy way to do this.
const discord = require('discord.js');
const config = require('./config.json');
var mysql = require('mysql');
const util = require('util');
const client = new discord.Client();
connection.connect(function(err) {
if (err) throw err;
client.login(config.token);
});
client.on('message', message => test());
let pool = mysql.createPool(poolConfig);
const getPoolConnection = util.promisify(pool.getConnection).bind(pool);
const endPool = util.promisify(pool.end).bind(pool);
async function test()
{
try
{
let poolConnection = await getPoolConnection();
//can the follow line be made so its not specific to one connection in the pool?
poolConnection.query = util.promisify(poolConnection.query);
let sql = `INSERT INTO user(UserID) VALUES(${01});`;
let sql2 = `INSERT INTO user(UserID) VALUES(${02});`;
await poolConnection.beginTransaction();
let results = await poolConnection.query(sql);
let results2 = await poolConnection.query(sql2);
await poolConnection.commit();
await poolConnection.release();
await endPool();
console.log(results);
console.log(results2);
}
catch(error)
{
console.log(error);
}
}
Here is my firebase function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.newMatch = functions.https.onCall((data, context) => {
const user1 = data.user1;
const user1token = data.user1token;
const user2name = data.user2name;
const user2 = data.user2;
const gender = data.gender;
console.log("before query");
const user1doc = admin.firestore().collection('users').doc(user1);
user1doc.get().then(doc => {
console.log(doc.get("fcmToken"));
return null;
})
the user1doc.get() line is giving me the following error:
22:2 error Expected catch() or return promise/catch-or-return
How can I return a promise so I can log the fcmToken value? Or is there a way to do it without returning a promise?
Simply put a return in from of the line that get()s the data:
return user1doc.get().then(doc => {
console.log(doc.get("fcmToken"));
return null;
})
I highly recommend learning more about Promises and their role in Cloud Functions, for example by reading https://medium.com/google-developers/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93.
I would like to setup my prepared statements with the mssql module. I created a query file for all user related requests.
const db = require('../databaseManager.js');
module.exports = {
getUserByName: async username => db(async pool => await pool.request()
.input('username', dataTypes.VarChar, username)
.query(`SELECT
*
FROM
person
WHERE
username = #username;`))
};
This approach allows me to require this query file and access the database by executing the query that is needed
const userQueries = require('../database/queries/users.js');
const userQueryResult = await userQueries.getUserByName(username); // call this somewhere in an async function
My database manager handles the database connection and executes the query
const sql = require('mssql');
const config = require('../config/database.js');
const pool = new sql.ConnectionPool(config).connect();
module.exports = async request => {
try {
const result = await request(pool);
return {
result: result.recordSet,
err: null
};
} catch (err) {
return {
result: null,
err
}
}
};
When I run the code I get the following error
UnhandledPromiseRejectionWarning: TypeError: pool.request is not a
function
Does someone know what is wrong with the code?
I think this happens because the pool is not initialized yet... but I used async/await to handle this...
Here is how I made your code work (I did some drastic simplifications):
const sql = require("mssql");
const { TYPES } = require("mssql");
const CONN = "";
(async () => {
const pool = new sql.ConnectionPool(CONN);
const poolConnect = pool.connect();
const getUserByName = async username => {
await poolConnect;
try {
const result = await pool.request()
.input("username", TYPES.VarChar, username)
.query(`SELECT
*
FROM
person
WHERE
username = #username;`);
return {
result: result.recordset,
err: null
};
} catch (err) {
return {
result: null,
err
};
}
};
console.log(await getUserByName("Timur"));
})();
In short, first read this.
You probably smiled when saw that the PR was created just 2 months before your questions and still not reflected in here.
Basically, instead of:
const pool = new sql.ConnectionPool(config).connect();
you do this:
const pool = new sql.ConnectionPool(config);
const poolConnection = pool.connect();
//later, when you need the connection you make the Promise resolve
await poolConnection;
I am working on sending notification between two applications. I have tried to do this through node.js but now I am stuck at this error for 1 month but found no solution to it.please help me out in it. this is very important for me.I will be very thankful for any kind of help.
"use-strict"
const functions = require('firebase-functions');
const admin= require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification= functions.firestore.document('Users/{user_id}/Notifications/{notification_id}').onWrite((change, context) => {
const user_id= context.params.user_id;
const notification_id= context.params.notification_id;
return admin.firestore().collection("ServiceProviders").doc(user_id).collection("Notifications").doc("notification_id").get().then(querySnapshot => {
const from_user_id= querySnapshot.data().From;
const from_message= querySnapshot.data().message;
const from_data= admin.firestore.collection("Users").doc(from_user_id).get();
const to_data= admin.firestore.collection("Users").doc(user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const from_name=result[0].data().name;
const to_name=result[1].data().name;
const token_id= result[1].data().token_id;
const payload= {
notifications:{
title: "Notification from : " + from_name,
body: from_message,
icon:"default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(result => {
return console.log("Notification Sent");
});
});
});
here is the monstrous error`
Your firestore query isn't returning anything; probably because either the document/collection doesn't exist.
Right off the bat, it stands out that your "notification_id" is queried as string, rather than the const you set earlier. It's kind of a gamble, but changing line 10 to this may help:
return admin.firestore().collection("ServiceProviders").doc(user_id).collection("Notifications").doc(notification_id).get().then(querySnapshot => {