Firebase Cloud Functions: Get user property values - javascript

I am trying to store some data from the 'app_remove' event in the database.
It works for the standard information like appInfo.appInstanceId.
But how do I get the userProperty values, since they are objects?
exports.appremoved = functions.analytics.event('app_remove').onLog(event => {
console.log(event.data);
console.log(event.data.user.Selected_Games);
const user = event.data.user;
if (user != null) {
if(user.userId != null){
admin.database().ref('/user_events/'+user.appInfo.appInstanceId + "/" + "deviceId").set(user.userId);
}
admin.database().ref('/user_events/'+user.appInfo.appInstanceId + "/" + "app_remove").set(event.data.logTime);
admin.database().ref('/user_events/'+user.appInfo.appInstanceId + "/" + "app_install").set(user.firstOpenTime);
}
});
This is the result of the console.log of event.data
AnalyticsEvent {
params: { firebase_conversion: 1, firebase_event_origin: 'auto' },
name: 'app_remove',
reportingDate: '20170719',
logTime: '2017-07-19T10:57:12.920Z',
user:
UserDimensions {
deviceInfo:
{ deviceCategory: 'mobile',
deviceModel: 'WAS-LX1A',
deviceTimeZoneOffsetSeconds: 7200,
platformVersion: '7.0',
userDefaultLanguage: 'it-it' },
geoInfo:
{ city: 'Milan',
continent: '039',
country: 'Italy',
region: 'Lombardy' },
appInfo:
{ appId: 'com.example.example',
appInstanceId: '000000',
appPlatform: 'ANDROID',
appStore: 'com.android.vending',
appVersion: '1.12' },
firstOpenTime: '2017-07-17T12:37:01.320Z',
userProperties:
{ Active_Notification: [Object],
Referrer: [Object],
Selected_Games: [Object],
Selected_Sources: [Object],
Selected_Topics: [Object],
first_open_time: [Object],
user_id: [Object] },
bundleInfo: ExportBundleInfo { bundleSequenceId: 10, serverTimestampOffset: 693 } } }

I found the solution.
I did a console.log of that object (event.data.user.Selected_Games)
UserPropertyValue { value: '4', setTime: '2017-06-27T01:22:25.375Z' }
So to get the value
event.data.user.userProperties.Selected_Games.value

Related

Javascript nested map function return string

I have a set of data. I map through my data, if data is "HOME_DELIVERY then it will go to another function which will check is the order is valid or not. if the order is valid then it will return hello string. So far everything works as expected but I want my map function return string hello. currently it's returning ['hello']
const getRoundName = (orderId) => {
if (orderId === "a4013438-926f-4fdc-8f6a-a7aa402b40ea") {
return "hello";
} else {
retrun
}
};
const orders = [
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ea",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
];
const roundName = orders.map((order) => {
return order.deliveryMethod === 'HOME_DELIVERY' ? getRoundName(order.id) : ''
});
console.log(roundName);
Array.map returns an array as response. If you need a string as response, you have to modify the logic as
const getRoundName = (orderId) => {
if (orderId === "a4013438-926f-4fdc-8f6a-a7aa402b40ea") {
return "hello";
} else {
return;
}
};
const orders = [
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ea",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
{
id: "a4013438-926f-4fdc-8f6a-a7aa402b40ef",
modifiedAt: "2022-02-28T09:26:18+00:00",
deliveryDate: "2022-02-28",
pickupLocation: null,
orderStatus: "MODIFIED",
deliverySlotId: "2022-02-28:66ee337c-e252-4297-9aed-cafcef396f19",
createdAt: "2022-02-26T06:38:46+00:00",
deliveryTime: "22-00",
storeId: "516079340",
orderNumber: 28354107,
paymentMethod: "ON_DELIVERY",
cartItems: [[Object], [Object], [Object]],
deliveryMethod: "HOME_DELIVERY",
additionalInfo: null,
},
];
const roundName = orders.flatMap((order) => {
return order.deliveryMethod === 'HOME_DELIVERY' ? getRoundName(order.id) : ''
});
console.log(roundName.join(''));
You can use filter before calling map
//if it has more than 1 items in the list, it will join them together like this `hellohellohello`
const orderIds = orders.filter((order) => order.deliveryMethod === 'HOME_DELIVERY').map(order => getRoundName(order.id)).join("")

Calling a JSON key that has a non-letter character

I am trying to return the value of #microsoft.graph.downloadUrl from the json object below:
[
{
'#microsoft.graph.downloadUrl': 'https://public.bl.files.1drv.com/XXXX',
createdDateTime: '2021-07-10T06:14:31.03Z',
cTag: 'QQQQ',
eTag: 'SSSS',
id: 'FFFF',
lastModifiedDateTime: '2021-07-12T09:27:21.69Z',
name: 'FILE_NAME',
size: 98580,
webUrl: 'https://1drv.ms/b/SSSS',
reactions: { commentCount: 0 },
createdBy: { application: [Object], user: [Object] },
lastModifiedBy: { user: [Object] },
parentReference: {
driveId: 'XXX',
driveType: 'personal',
id: 'YYYY!YYY',
name: 'Documents',
path: '/drive/root:/Documents'
},
file: { mimeType: 'application/pdf', hashes: [Object] },
fileSystemInfo: {
createdDateTime: '2021-07-10T06:14:31.03Z',
lastModifiedDateTime: '2021-07-12T09:27:21.69Z'
}
}
]
I wish to use something like this that i had done to extract the name as I need to be able to get the #microsoft.graph.downloadUrl from each json object (known as f below) in 'files'.
var fileName = (JSON.stringify(files[f].name));
I tried both:
var fileURL = (JSON.stringify(files[f]."#microsoft.graph.downloadUrl"));
var fileURL = (JSON.stringify(files[f].#microsoft.graph.downloadUrl));
but neither work -- any help would be much appreciated!
You should just use files[f]["#microsoft.graph.downloadUrl"].

How to use map function on a json response in javascript?

I am using zomato API to find a random restaurant within an area. This is the API call.
app.post('/locations/:query', async (req, res) =>
{
try{
const query = req.params.query;
const data = await zomato.cities({ q: query,count: 1 })
const cityId= await (data[0].id);
const result = [];
const nrOfRequests = 60;
let currCount = 0;
const nrOfEntries = 20;
for(let i=0; i < nrOfRequests ; i++) {
const response = await zomato.search({ entity_id: cityId, entity_type: 'city', start:currCount, count:nrOfEntries, sort:'rating', order:'desc' });
result.push(...response.restaurants);
currCount += nrOfEntries;
}
const no = Math.floor(Math.random() * 60);
const restaur = result[no].restaurants.map(r => {
return {
name: r.name,
url: r.url,
location: r.location,
price: r.price_range,
thumbnail: r.thumb,
rating: r.user_rating.aggregate_rating,
}
})
res.send({restaur});
} catch (err) {
console.error(err)
res.status(500).send('error')
}
});
What this API is doing is
1)Finds cityId of query.(query is a city name)
2)Using for loop finds upto 60 restaurants in that city according to rating and pushes it in results[].(zomato api has restriction to display only 20 restaurants per call)
3)Chooses a random number between 0 to 60 and outputs that particular restaurant from result.
4)Then what I want to do is find features like name price etc and return to display that in the frontend.
Using this code I get the following error
TypeError: Cannot read property 'map' of undefined
The result[no] response looks like this.
{
R: {
has_menu_status: { delivery: -1, takeaway: -1 },
res_id: 302578,
is_grocery_store: false
},
apikey: '*************',
id: '302578',
name: 'Barbeque Nation',
url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1',
location: {
address: 'M/A 04, DLF Avenue, District Centre, Saket, New Delhi',
locality: 'DLF Avenue, Saket',
city: 'New Delhi',
city_id: 1,
latitude: '28.5273432339',
longitude: '77.2173847631',
zipcode: '',
country_id: 1,
locality_verbose: 'DLF Avenue, Saket, New Delhi'
},
switch_to_order_menu: 0,
cuisines: 'North Indian, BBQ, Beverages',
timings: '12noon – 3:30pm, 6pm – 11pm (Mon-Sun)',
average_cost_for_two: 1600,
price_range: 3,
currency: 'Rs.',
highlights: [
'Lunch',
'Serves Alcohol',
'Mall Parking',
'Cash',
'Credit Card',
'Debit Card',
'Dinner',
'Takeaway Available',
'Fullbar',
'Indoor Seating',
'Air Conditioned',
'Reopened',
'Buffet'
],
offers: [],
opentable_support: 0,
is_zomato_book_res: 0,
mezzo_provider: 'OTHER',
is_book_form_web_view: 0,
book_form_web_view_url: '',
book_again_url: '',
thumb: 'https://b.zmtcdn.com/data/pictures/chains/2/1212/b6429ddad24625e65344caabb921bd57.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A',
user_rating: {
aggregate_rating: '4.7',
rating_text: 'Excellent',
rating_color: '3F7E00',
rating_obj: { title: [Object], bg_color: [Object] },
votes: 2248
},
all_reviews_count: 1159,
photos_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop',
photo_count: 1991,
menu_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop',
featured_image: 'https://b.zmtcdn.com/data/pictures/chains/2/1212/b6429ddad24625e65344caabb921bd57.jpg',
medio_provider: 1,
has_online_delivery: 1,
is_delivering_now: 0,
store_type: '',
include_bogo_offers: true,
deeplink: 'zomato://restaurant/302578',
is_table_reservation_supported: 1,
has_table_booking: 0,
events_url: 'https://www.zomato.com/ncr/barbeque-nation-saket-new-delhi/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1',
phone_numbers: '080 61756005',
all_reviews: { reviews: [ [Object], [Object], [Object], [Object], [Object] ] },
establishment: [ 'Casual Dining' ],
establishment_types: []
}
The results[no] that you're showing indeed has no property called restaurants. You have an array called results, and you're selecting a single element from that array. When you have a single element, there's nothing to "map".
Instead, just return the fields you want from that element:
const no = Math.floor(Math.random() * 60);
const restaur = {
name: result[no].name,
url: result[no].url,
location: result[no].location,
price: result[no].price_range,
thumbnail: result[no].thumb,
rating: result[no].user_rating.aggregate_rating,
};
res.send(restaur);

MongoDb find query giving weird response

I am trying to search data in mongodb with nodejs. This is my query
collection.find({ age: { '$gt': 20 } });
its working fine in robomongo but giving me this response in my application
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'versioncontrol.Branch/contacts',
cmd:
{ find: 'versioncontrol.Branch/contacts',
limit: 0,
skip: 0,
query: { age: [Object] },
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: [Object] } }
Now i don't know how to get my data out of it.
The cursor returned from the find method is a Readable stream. You have do read items from it to get the actual result. Look at this
Example:
var cursor = collection.find({ age: { '$gt': 20 } });
cursor.each(function (err, doc) {
if (err) {
console.log(err);
} else {
console.log('Fetched:', doc);
}
});
Done it using
var cursor = collection.find({ age: { '$gt': 20 } }).toArray();
cursor.then(function (docs) {
console.log( docs );
});

Node Js Steam Trade Offers Bot Items

This bot accept all trades but it need to accept only trade offers which contains [type: 'Consumer Grade SMG',] item in itemsToReceive. I was trying to do something like: If itemsToReceive contains Consumer Grade SMG then accpet offer else cancel offer but i failed. Im newby and i dont have any idea how to do that.
Sorry for my bad english.
My output console:
New offer #644673626 from [U:1:205839253]
[ { appid: 730,
contextid: { low: 2, high: 0, unsigned: true },
assetid: '3142560367',
classid: '310777708',
instanceid: '302028390',
amount: 1,
missing: true,
id: '3142560367',
icon_url: '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHL
bXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpopuP1FBRw7ODYYzxb08-3moS0m_7zO6-fxzNQ65J03L2Vo
9-sigzj_kU6Mmr6LIKVdwNvZVHTqVTqxri8jZS4tYOJlyVoTeLjug',
icon_url_large: '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4o
FJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpopuP1FBRw7ODYYzxb08-3moS0m_7zO6_ummpD78A
_27HA9tvw3gDg_UBlMWH0IYDDIwU3aVzQ_1Tvxefs1pPou8uawXBnsz5iuyjoOPjz8g',
icon_drag_url: '',
name: 'P90 | Sand Spray',
market_hash_name: 'P90 | Sand Spray (Minimal Wear)',
market_name: 'P90 | Sand Spray (Minimal Wear)',
name_color: 'D2D2D2',
background_color: '',
type: 'Consumer Grade SMG',
tradable: true,
marketable: true,
commodity: false,
market_tradable_restriction: 7,
fraudwarnings: '',
descriptions:
{ '0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object] },
owner_descriptions: '',
actions: { '0': [Object] },
market_actions: { '0': [Object] },
tags:
{ '0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object] } } ]
Offer accepted
Offer #644673626 changed: Active -Accepted
Received: P90 | Sand Spray
And bot code:
/**
* STOREHOUSE - node-steam
*
* Uses node-steam-user for notifications and accepts all incoming trade offers
*/
var SteamUser = require('steam-user');
var TradeOfferManager = require('../lib/index.js'); // use require('steam-tradeoffer-manager') in production
var fs = require('fs');
var client = new SteamUser();
var manager = new TradeOfferManager({
"steam": client, // Polling every 30 seconds is fine since we get notifications from Steam
"domain": "example.com", // Our domain is example.com
"language": "en" // We want English item descriptions
});
// Steam logon options
var logOnOptions = {
"accountName": "xxxxx",
"password": "xxxxx"
};
if(fs.existsSync('polldata.json')) {
manager.pollData = JSON.parse(fs.readFileSync('polldata.json'));
}
client.logOn(logOnOptions);
client.on('loggedOn', function() {
console.log("Logged into Steam");
});
client.on('webSession', function(sessionID, cookies) {
manager.setCookies(cookies, function(err) {
if(err) {
console.log(err);
process.exit(1); // Fatal error since we couldn't get our API key
return;
}
console.log("Got API key: " + manager.apiKey);
});
});
manager.on('newOffer', function(offer) {
console.log("New offer #" + offer.id + " from " + offer.partner.getSteam3RenderedID());
console.log(offer.itemsToReceive);
offer.accept(function(err) {
if(err) {
console.log("Unable to accept offer: " + err.message);
} else {
console.log("Offer accepted");
}
});
});
manager.on('receivedOfferChanged', function(offer, oldState) {
console.log("Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));
if(offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
offer.getReceivedItems(function(err, items) {
if(err) {
console.log("Couldn't get received items: " + err);
} else {
var names = items.map(function(item) {
return item.name;
});
console.log("Received: " + names.join(', '));
}
});
}
});
manager.on('pollData', function(pollData) {
fs.writeFile('polldata.json', JSON.stringify(pollData));
});
Have try.
manager.on('newOffer', function(offer) {
console.log("New offer #" + offer.id + " from " + offer.partner.getSteam3RenderedID());
console.log(offer.itemsToReceive);
for(var i = 0; i > offer.itemsToReceive.length)
{
if(offer.itemsToReceive[i]['type'] != "Consumer Grade SMG")
{
return;
if(i == offer.itemsToReceive.length)
{
offer.accept(function(err){
if(err){
console.log("Unable to accept offer: " + err.message);
}
else{
console.log("Offer accepted");
}
});
}
}
}
});

Categories

Resources