Getting Data from Firestore for web - javascript

I currently try to use firebase for web and get data from Firestore.
This is my code for bring the all my data from Firestore.
function FireStoreGetAllData() {
let db = firebase.firestore();
let dataMap = new Map();
db.collection("User").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
let dataset = new Map();
let docId = doc.id;
let docdata = doc.data();
let firstName = docdata.first;
let lastName = docdata.last;
let bornData = docdata.born;
dataset.set('first', firstName);
dataset.set('last', lastName);
dataset.set('born', bornData)
dataMap.set(docId, dataset);
});
});
console.log('dataSet',dataMap.entries());
return dataMap;}
Problem is the "dataMap" always return null every time.
I debug this issue and find out that "db.colloction" is execute the code after "return dataMap".
What am I missing?

db.collection is execute after return dataMap because of the asynchronous.
Make you FireStoreGetAllData as async function then you will get your dataMap.
async function FireStoreGetAllData() {
let db = firebase.firestore();
let dataMap = new Map();
const querySnapshot = await db.collection("User").get();
querySnapshot.forEach((doc) => {
let dataset = new Map();
let docId = doc.id;
let docdata = doc.data();
let firstName = docdata.first;
let lastName = docdata.last;
let bornData = docdata.born;
dataset.set('first', firstName);
dataset.set('last', lastName);
dataset.set('born', bornData)
dataMap.set(docId, dataset);
});
return dataMap;
}

Related

Save console.log output into a file

I have a JavaScript code that is printing a few statements that I would like to save in a file, which I will parse with a Python code.
I have saw multiple solutions, but I am having a hard time to modifying my code to save the console.log output.
Here is my JavaScript code:
import { JSBI } from "#uniswap/sdk";
import { ethers } from 'ethers';
import * as fs from 'fs';
// ERC20 json abi file
let ERC20Abi = fs.readFileSync('ERC20.json');
const ERC20 = JSON.parse(ERC20Abi);
// V3 pool abi json file
let pool = fs.readFileSync('V3PairAbi.json');
const IUniswapV3PoolABI = JSON.parse(pool);
// V3 factory abi json
let facto = fs.readFileSync('V3factory.json');
const IUniswapV3FactoryABI = JSON.parse(facto);
let NFT = fs.readFileSync('UniV3NFT.json');
const IUniswapV3NFTmanagerABI = JSON.parse(NFT);
const provider = new ethers.providers.JsonRpcProvider(ALCHEMY)
// V3 standard addresses (different for celo)
const factory = FACTORY;
const NFTmanager = NFTMANAGER;
async function getData(tokenID){
let FactoryContract = new ethers.Contract(factory, IUniswapV3FactoryABI, provider);
let NFTContract = new ethers.Contract(NFTmanager, IUniswapV3NFTmanagerABI, provider);
let position = await NFTContract.positions(tokenID);
let token0contract = new ethers.Contract(position.token0, ERC20, provider);
let token1contract = new ethers.Contract(position.token1, ERC20, provider);
let token0Decimal = await token0contract.decimals();
let token1Decimal = await token1contract.decimals();
let token0sym = await token0contract.symbol();
let token1sym = await token1contract.symbol();
let V3pool = await FactoryContract.getPool(position.token0, position.token1, position.fee);
let poolContract = new ethers.Contract(V3pool, IUniswapV3PoolABI, provider);
let slot0 = await poolContract.slot0();
let pairName = token0sym +"/"+ token1sym;
let dict = {"SqrtX96" : slot0.sqrtPriceX96.toString(), "Pair": pairName, "T0d": token0Decimal, "T1d": token1Decimal, "tickLow": position.tickLower, "tickHigh": position.tickUpper, "liquidity": position.liquidity.toString()}
return dict
}
const Q96 = JSBI.exponentiate(JSBI.BigInt(2), JSBI.BigInt(96));
const MIN_TICK = -887272;
const MAX_TICK = 887272;
function getTickAtSqrtRatio(sqrtPriceX96){
let tick = Math.floor(Math.log((sqrtPriceX96/Q96)**2)/Math.log(1.0001));
return tick;
}
async function getTokenAmounts(liquidity,sqrtPriceX96,tickLow,tickHigh,token0Decimal,token1Decimal){
let sqrtRatioA = Math.sqrt(1.0001**tickLow).toFixed(18);
let sqrtRatioB = Math.sqrt(1.0001**tickHigh).toFixed(18);
let currentTick = getTickAtSqrtRatio(sqrtPriceX96);
let sqrtPrice = sqrtPriceX96 / Q96;
let amount0wei = 0;
let amount1wei = 0;
if(currentTick <= tickLow){
amount0wei = Math.floor(liquidity*((sqrtRatioB-sqrtRatioA)/(sqrtRatioA*sqrtRatioB)));
}
if(currentTick > tickHigh){
amount1wei = Math.floor(liquidity*(sqrtRatioB-sqrtRatioA));
}
if(currentTick >= tickLow && currentTick < tickHigh){
amount0wei = Math.floor(liquidity*((sqrtRatioB-sqrtPrice)/(sqrtPrice*sqrtRatioB)));
amount1wei = Math.floor(liquidity*(sqrtPrice-sqrtRatioA));
}
let amount0Human = (amount0wei/(10**token0Decimal)).toFixed(token0Decimal);
let amount1Human = (amount1wei/(10**token1Decimal)).toFixed(token1Decimal);
console.log("Amount Token0 wei: "+amount0wei);
console.log("Amount Token1 wei: "+amount1wei);
console.log("Amount Token0 : "+amount0Human);
console.log("Amount Token1 : "+amount1Human);
return [amount0wei, amount1wei]
}
async function start(positionID){
let data = await getData(positionID);
let tokens = await getTokenAmounts(data.liquidity, data.SqrtX96, data.tickLow, data.tickHigh, data.T0d, data.T1d);
}
start(POOLID)
// Also it can be used without the position data if you pull the data it will work for any range
getTokenAmounts(12558033400096537032, 20259533801624375790673555415)

Push a returned object into an array of objects

I'm trying to save the output of function setData (an object) to an array (state=[]), but can't figure out how. Here's the code:
const sbmt = document.getElementById("myForm");
const elName = document.getElementById("iname");
const elGender = document.getElementById("igender");
const elAge = document.getElementById("iage");
const elForm = document.getElementById("myForm");
const setData = (event) => {
event.preventDefault();
let nodeList = document.forms[0].elements;
let flatNodeList = [...nodeList].map(x => x.value).filter(x => x !== "Submit");
let objData = {
userName: flatNodeList[0],
userGender: flatNodeList[1],
userAge: flatNodeList[2]
};
console.log(objData);
return objData;
};
let state =[];
const resetForm = () => elForm.reset();
sbmt.addEventListener("submit", setData);
sbmt.addEventListener("submit", resetForm);
You basically just need to push the data into your state array. Returning the object will have no affect.
let state =[];
const setData = (event) => {
event.preventDefault();
let nodeList = document.forms[0].elements;
let flatNodeList = [...nodeList].map(x => x.value).filter(x => x !== "Submit");
let objData = {
userName: flatNodeList[0],
userGender: flatNodeList[1],
userAge: flatNodeList[2]
};
console.log(objData);
state.push(objData);
};

embedMsg is returning undefined

I tried to make and embed and add reactions to it.
but the embeds find is returning undefined when console.log
I am trying to make reaction role the following code is to create one.
I can successfully create embed but I can't add desired reactions because it is not able to find embed
const Discord = require('discord.js')
module.exports.run = async (client,message,args,con)=>{
message.channel.send("How many reaction role you want to create");
answer = await message.channel.awaitMessages(answer => answer.author.id != client.user.id,{max: 1});
const n = (answer.map(answers => answers.content).join())
if(isNaN(n)) return message.channel.send("Enter a Number")
message.channel.send("Enter the title");
answer = await message.channel.awaitMessages(answer => answer.author.id != client.user.id,{max: 1});
const embtitle = (answer.map(answers => answers.content).join())
var a = []
var b = []
for(var i =0; i<n;i++){
message.channel.send("Enter the emoji")
answer = await message.channel.awaitMessages(answer => answer.author.id != client.user.id,{max: 1});
a[i] = (answer.map(answers => answers.content).join())
message.channel.send("Enter the role name")
answer = await message.channel.awaitMessages(answer => answer.author.id != client.user.id,{max: 1});
b[i] = (answer.map(answers => answers.content).join())
}
function embstr(){
var finalString = '';
for(var i =0;i<n;i++){
finalString += a[i]+ ' '+b[i] +'\n';
}
return finalString;
}
const embed = new Discord.MessageEmbed()
.setTitle(embtitle)
.setColor("BLUE")
.setDescription(embstr());
message.channel.send(embed);
const embedMsg = message.embeds.find(msg => msg.title === 'some');
console.log(embedMsg)
for(var i = 0;i<n;i++){
var emoid = a[i].slice(1,-1)
emoid = emoid.split(':')
emoid = emoid[2];
console.log(emoid);
const embedMsg = message.embeds.find(msg => msg.title === embtitle);
console.log(embedMsg)
if(embedMsg){
message.react(emoid)
}
}
}
module.exports.config = {
command: 'create'
}
Instead of constantly trying to find the message you sent like this :
const embedMsg = message.embeds.find(msg => msg.title === 'some');
You could simply assign the message you sent to a variable, like this :
const embedMsg = await message.channel.send(embed); // I used await since I saw your function is asynchronous
Then react to the message this way :
await embedMsg.react('emote Name/ID/Whatever');
Hope this will help :)

Firestore get subcollection is slow

I have collections and their sub-collections. I loop over them and collect data. It works fine but it is too slow. Can anyone suggest to improve performance issue?
static async getSubCategories(category_id) {
const db = Firebase.firestore(),
subCategories = [];
activeRef = await db.collection("sub_categories").where("category_id", "==", category_id).orderBy("id").get();
for (let doc of activeRef.docs) {
const subCategory = doc.data();
if (_.isObject(subCategory)) {
const subRef = await doc.ref.collection('sub_sub_categories').orderBy("id").get(),
subSubCategories = [];
for (let subDoc of subRef.docs) {
const subSubCategory = subDoc.data();
if (_.isObject(subCategory)) {
subSubCategories.push(subSubCategory);
// If SubCategory has image, download storage uri
if (subSubCategory.image_storage_uri) {
const imageRef = Firebase.storage().refFromURL(subSubCategory.image_storage_uri),
imageUri = await imageRef.getDownloadURL();
subSubCategory.image_uri = imageUri;
}
}
}
if (subSubCategories.length > 0)
subCategory.sub_sub_categories = subSubCategories;
subCategories.push(subCategory);
}
}
return subCategories;
}

How to get value of node in firebase database in Cloud Function

exports.respublished =
functions.database.ref('/Posts/{postid}').onWrite(event => {
const snapshot = event.data;
const postid = event.params.examid;
const uid = snapshot.child('uid').val();
const ispublic = snapshot.child('Public').val();
firebase.database.ref('Users/' + uid).once(event => {
const snapshot = event.data;
const name = snapshot.child('name').val();
});
});
The event is triggered by another node and i want to retrive data from another node of firebase database. I have tried the above code but it produces an error saying TypeError: firebase.database.ref(...).once is not a function.
yes i got the answer we can use this code
exports.respublished = functions.database.ref('/Posts/{postid}').onWrite(event => {
const snapshot = event.data;
const postid = event.params.examid;
const uid = snapshot.child('uid').val();
const ispublic = snapshot.child('Public').val();
return admin.database().ref('Users/' + uid).once(event => {
const snapshot = event.data;
const name = snapshot.child('name').val();
});
});

Categories