I made Firestore Could Function Where I have Database Like this
'posts/{postId}/comments/{commentId}'
and Function I made To Increase Field In PostId when New Comment Added
the Funtion has Deploy But it`s Never Execute when adding New Comment
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.comment= functions.firestore
.document('posts/{postId}/comments/{commentId}')
.onWrite((change, context) => {
const commentId = event.params.commentId;
const postId = event.params.postId;
const docRef = admin.firestore().collection('posts').doc(postId);
return docRef.update({numberOfComments:200});
});
I Added Many Comment Even Executions is 0
change this:
const commentId = event.params.commentId;
const postId = event.params.postId;
into this:
const commentId = context.params.commentId;
const postId = context.params.postId;
more info here:
https://firebase.google.com/docs/functions/beta-v1-diff
Before Firebase SDK (<= v0.9.1) version event.params.id was worked. but Now (v1.0.0) android provide documentation to use context.params.id.
Use context insted of event, your problem will be solve.
const commentId = event.params.commentId;
const postId = event.params.postId;
Thanks.
Related
I want to automate my staking on The Sandbox. For that I need in the first step to interact with the mSand-Matic Pool Contract. It is this one: https://polygonscan.com/address/0x4ab071c42c28c4858c4bac171f06b13586b20f30#code
I have written a little program in a GitHub repository to show what I have done: https://github.com/ChristianErdtmann/mSandMaticStakingAutomation
Or here is the code example from the contract-interact.js
Web3 = require('web3')
const fs = require('fs');
const web3 = new Web3("https://polygon-rpc.com")
const contractAddress = "0x4AB071C42C28c4858C4BAc171F06b13586b20F30"
const contractJson = fs.readFileSync('./abi.json')
const abi = JSON.parse(contractJson)
const mSandMaticContract = new web3.eth.Contract(abi, contractAddress)
mSandMaticContract.balanceOf('0x7e5475290Df8E66234A541483453B5503551C780')
The ABI I have taken from the contract link on the top. But it seems there is a problem.
I tried for testing to read something from the contract. For that I used the function balanceOf(address), how you can see in the code.
But I always get this error:
TypeError: mSandMaticContract.balanceOf is not a function
I found the solution
web3 needs .methots to get acces to the balanceOf() function
if we want only to read so we need to add .call()
we need to add await before the function is called this needs to be in a asynchonus function
So the final working code is:
Web3 = require('web3')
const fs = require('fs');
const web3 = new Web3("https://polygon-rpc.com")
const contractAddress = "0x4AB071C42C28c4858C4BAc171F06b13586b20F30"
const contractJson = fs.readFileSync('./abi.json')
const abi = JSON.parse(contractJson)
const mSandMaticContract = new web3.eth.Contract(abi, contractAddress)
asyncCall()
async function asyncCall() {
console.log(await mSandMaticContract.methods.balanceOf('0x7e5475290Df8E66234A541483453B5503551C780').call())
}
If you dont want only to read you need addtional to sign the transaction with:
The solution is, to sign the transaction before sending we can doing this with any method by this code:
encoded = mSandMaticContract.methods.getReward().encodeABI()
var block = await web3.eth.getBlock("latest");
var gasLimit = Math.round(block.gasLimit / block.transactions.length);
var tx = {
gas: gasLimit,
to: publicKey,
data: encoded
}
web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
web3.eth.sendSignedTransaction(signed.rawTransaction).on('receipt', console.log)
})
Hey im trying to figuring out if i have a firebase function and inside 4 get methods like this
export default functions
.runWith(runtimeOpts)
.firestore.document("ParentComment/{commentID}")
.onCreate(async (snap, context) => {
try {
const db = admin.firestore();
const { videoID, author, text,videoowner } = snap.data() || {};
const ref = db.doc(`videos/${videoID}`);
const videouid = await db.doc(`videos/${videoID}`).get();
const userSnap = await db.doc(`meinprofilsettings/${author}`).get();
const { commentID } = context.params;
const recoveringuser1 = await db.doc(`Recovering/${videoowner}`).get();
const recoveringuser2 = await db.doc(`Recovering/${author}`).get();
…
do i have to pay for each get method?
or does it count as 1 read?
The pricing elements for Firestore in play here are:
Document Reads: as the name implies, you will be charged for each document that your code causes to be read from the database on the server. Since you are reading 4 individual documents, there are 4 charged document reads
Network Bandwidth: you may also be charged for the bandwidth that is consumed for transferring the data. If the Cloud Function and Firestore are in the same region, this charge is waved.
For more on this, I recommend reading the Firestore pricing page in the documentation.
In my cloud functions, I'm trying to delete an image based on its url, but I think that I don't use correctly the API as I'm getting errors :
const admin = require('firebase-admin');
exports.deleteImageWhenOfferDeleted = functions.firestore
.document('offers/{offerId}')
.onDelete(async(snap, context) => {
console.log('----------------start function--------------------')
const deletedOffer = snap.data();
var imageUrlToDelete = deletedOffer.imageUrl;
await admin.storage.getPathStorageFromUrl(imageUrlToDelete).delete();
function getPathStorageFromUrl(url){
const baseUrl = "https://firebasestorage.googleapis.com/v0/b/muslim-coloc.appspot.com/o/";
let imagePath = url.replace(baseUrl,"");
const indexOfEndPath = imagePath.indexOf("?");
imagePath = imagePath.substring(0,indexOfEndPath);
imagePath = imagePath.replace("%2F","/");
return imagePath;
}
I think you're missing brackets after storage word.
You need to get an instance of storage object.
admin.storage.getReferenceFromUrl(...)
should be
admin.storage().getReferenceFromUrl(...)
BTW: Consider using TypeScript, because it catches errors like that during compilation.
I'm trying to add new fields to a new document after calculation, that I have to do when a new doc is created. But, the field isn't added.
I have deploy this code without any errors but when a new doc is added in this path, nothing happens..
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
exports.test = functions.firestore.document('a/{a.id}/b/{b.id}/c/d')
.onCreate(async(snapshot, context) => {
const data = snapshot.data();
const userRef = db.doc(`a/${a.id}/b/${b.id}/c/d`);
var result = 1+2; //just for lighter code example
return userRef.update({
result: result
});
})
Your wildcards are invalid. You can't have a dot in the wildcard name. I'm kind of surprised that the Firebase CLI allowed you to deploy this function. Also, you're not using the wildcards correctly, even if those wildcards were valid.
There is an easier way to get a reference to the document that was just created. You can use snapshot.ref.
exports.test = functions.firestore.document('a/{a}/b/{b}/c/d')
.onCreate(async(snapshot, context) => {
var result = 1+2; //just for lighter code example
return snapshot.ref.update({
result: result
});
})
If you do want to use the wildcard values, you should use context.params instead, as described in the documentation.
how to store a uploaded image to two different path/places in firebase Storage? I tried this but it isn't working
const { currentUser } = firebase.auth();
const ref = firebase.storage().ref().child(`images/${currentUser.uid}`);
const ref = firebase.storage().ref().child('photos')
const snapshot = await ref.put(blob);
blob.close();
Okay so first, you can't re-declare variables like that (const ref = ...; then const ref = ....; right below it). Second, you need to perform put on each ref. So should look something like this:
const { currentUser } = firebase.auth();
const ref1 = firebase.storage().ref().child(`images/${currentUser.uid}`);
const ref2 = firebase.storage().ref().child('photos')
const snapshot1 = await ref1.put(blob);
const snapshot2 = await ref2.put(blob);
blob.close();
Or if you want to have a little more optimized code:
const { currentUser } = firebase.auth();
const ref = firebase.storage().ref();
const imagesUpload = await ref.child(`images/${currentUser.uid}`).put(blob);
const photosUpload = await ref.child('photos').put(blob);
blob.close();
If you want to be more advanced with this and have only a single upload task, read more here: https://cloud.google.com/storage/docs/json_api/v1/how-tos/batch