Firebase - Cloud Functions: enumerate [Object Object] - node.js

I would like to enumerate the members object from the below structure.
I do not have prior experience in node.js, I have tried the following code and it doesn't seem to work.
exports.sendVaultUnlockedPush = functions.database.ref('/Vaults/{id}/action').onUpdate(event => {
let status = event.data.val();
if (status == 'lock') {
var db = admin.database();
var vaultRef = db.ref("/Vaults/" + event.params.id);
vaultRef.once('value').then(function(snapshot) {
var hasMembers = snapshot.child('members');
if (hasMembers) {
var memberRef = db.ref("Vaults/" + event.params.id + "/members");
memberRef.once('value').then(function(memberSnapshot) {
memberSnapshot.forEach(function(element) {
console(element.key + " - " + element.val());
}, this);
});
}
});
}
})
It throws the following error:
Error: Firebase.DataSnapshot.forEach failed: Was called with 2 arguments. Expects no more than 1.
at Error (native)
at z (/user_code/node_modules/firebase-admin/lib/database/database.js:42:1666)
at T.forEach (/user_code/node_modules/firebase-admin/lib/database/database.js:114:179)
at /user_code/index.js:34:36
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
I would just like it to return the value of 'members' node. And I have no clue to do the same.
Any help is much appreciated in getting this sorted. Thanks!

According to the docs forEach takes only one parameter:
This should work:
var values;
memberSnapshot.forEach(function(element) {
console(element.key);
values = element.val();
for (var val in values) {
if (values.hasOwnProperty(val)) {
console(val, values[val]);
}
}
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Related

TypeError: Cannot read property 'facts' of undefined

I am trying to make a word randomizer, and it gives me this error:
message.channel.send(item.facts);
^
TypeError: Cannot read property 'facts' of undefined
and I don't know how to fix it.
Here is my code:
const Discord = require('discord.js');
module.exports = {
name: 'game',
execute(message, args) {
const gameChanger = require('../text.txt')
const item = gameChanger[Math.floor(Math.random() * gameChanger.length)];
setInterval(() => {
const item = gameChanger[Math.floor(Math.random() * gameChanger.length)];
message.channel.send(item.facts);
}, 5 * 1000);
}
}
Someone please help me
The error indicates that the variable item is undefined. This is probably because you are going out of bounds of the gameChanger array, which is causing undefined to be assigned to item.

Discord.JS ReferenceError: stopTyping is not Defined

I'm trying to get our announce command to work but it keeps throwing the following error:
#Nimbi, An error occurred while running the command: ReferenceError: stopTyping is not defined
You shouldn't ever receive an error like this.
Please contact Nimbi#4961.
Here is my announce.js code:
const stripIndents = require('common-tags').stripIndents;
const { Command } = require('discord.js-commando');
require('dotenv').config();
ANNOUNCE_CHANNEL_NAME = process.env.ANNOUNCEMENT_CHANNEL;
NEWS_CHANNEL_NAME = process.env.NEWS_CHANNEL;
MODLOG_CHANNEL_NAME = process.env.MODLOG_CHANNEL;
module.exports = class NewsCommand extends Command {
constructor (client) {
super(client, {
name: 'announce',
memberName: 'announce',
group: 'mod',
aliases: ['news', 'ann', 'a'],
description: 'Make an announcement in the news channel',
format: 'Announcement',
examples: ['announce John Appleseed reads the news'],
guildOnly: true,
throttling: {
usages: 2,
duration: 3
},
args: [
{
key: 'body',
prompt: 'What do you want me to announce?',
type: 'string'
}
],
userPermissions: ['MANAGE_MESSAGES'],
clientPermissions: ['MANAGE_MESSAGES']
});
}
run (msg, {body}) {
try {
startTyping(msg);
let announce = body,
newsChannel = null;
const announceEmbed = new MessageEmbed(),
modlogChannel = msg.guild.settings.get('modLogChannel',
msg.guild.channels.find(c => c.name === MODLOG_CHANNEL) ? msg.guild.channels.find(c => c.name === MODLOG_CHANNEL).id : null);
if (msg.guild.settings.get('announcechannel')) {
newsChannel = msg.guild.channels.find(c => c.id === msg.guild.settings.get('announcechannel'));
} else {
msg.guild.channels.find(c => c.name === 'announcements')
? newsChannel = msg.guild.channels.find(c => c.name === ANNOUNCEMENT_CHANNEL)
: newsChannel = msg.guild.channels.find(c => c.name === NEWS_CHANNEL);
}
if (!newsChannel) throw new Error('nochannel');
if (!newsChannel.permissionsFor(msg.guild.me).has(['SEND_MESSAGES', 'VIEW_CHANNEL'])) throw new Error('noperms');
newsChannel.startTyping(1);
announce.slice(0, 4) !== 'http' ? announce = `${body.slice(0, 1).toUpperCase()}${body.slice(1)}` : null;
msg.attachments.first() && msg.attachments.first().url ? announce += `\n${msg.attachments.first().url}` : null;
announceEmbed
.setColor('#AAEFE6')
.setAuthor(msg.author.tag, msg.author.displayAvatarURL())
.setDescription(stripIndents`**Action:** Made an announcement`)
.setTimestamp();
newsChannel.msg.say(announce);
newsChannel.stopTyping(true);
if (msg.guild.settings.get('mod-logs', true)) {
if (!msg.guild.settings.get('hasSentModLogMessage', false)) {
msg.reply(oneLine`📃 I can keep a log of moderator actions if you create a channel named **${MODLOG_CHANNEL_NAME}**
(or some other name configured by the ${msg.guild.commandPrefix}setmodlogs command) and give me access to it.
This message will only show up this one time and never again after this so if you desire to set up mod logs make sure to do so now.`);
msg.guild.settings.set('hasSentModLogMessage', true);
}
modlogChannel && msg.guild.settings.get('mod-logs', false) ? msg.guild.channels.get(modlogChannel).msg.say('', {embed: announceEmbed}) : null;
}
stopTyping(msg);
return msg.embed(announceEmbed);
} catch (err) {
stopTyping(msg);
if ((/(?:nochannel)/i).test(err.toString())) {
return msg.reply(`there is no channel for me to make the announcement in. Create channel named either ${ANNOUNCE_CHANNEL_NAME} or ${NEWS_CHANNEL_NAME}`);
} else if ((/(?:noperms)/i).test(err.toString())) {
return msg.reply(`I do not have permission to send messages to the ${ANNOUNCE_CHANNEL_NAME} or ${NEWS_CHANNEL_NAME} channel. Better go fix that!`);
}
return msg.reply(oneLine`An error occurred but I notified ${this.client.owners[0].username}
Want to know more about the error? Join the support server by getting an invite by using the \`${msg.guild.commandPrefix}invite\` command `);
}
}
};
My discord.js version is: ^12.5.1
My discord.js-commando version is: ^0.11.1
My node.js version is: ^12.0.0
I've already tried defining it with:
const {startTyping, stopTypeing } = require('discord.js');
and
const {startTyping, stopTypeing } = require('util');
however, both simply threw the startTyping is not a function error.
Any help would be much appreciated.
Note: this is in discord.js#13 and onwards
startTyping
// like 101arrowz said, startTyping (or now sendTyping) is a method of the TextChannel, which you can get by msg.channel
message.channel.sendTyping()
Discord.js and commando (which is by the same people) works great, but if you have any problems I suggest you read the docs or ask at their discord server (they do actually help)

Uncaught TypeError: Object.values is not a function

Okay so, I npm run build my application, drag the build files into tizon studio.
Run the application...
I get the error:
2.bd938b3f.chunk.js:79798 Uncaught TypeError: Object.values is not a function
The same behavior is shown on any Samsung and Tizon model I've tested this on.
I've tried switching out Object.values with Object.map,
which returns "the same" error.
2.bd938b3f.chunk.js:79798 Uncaught TypeError: Object.map is not a function
I have not been able to find an answer to fix this.
Any help with finding an answer would be massively appreciated.
Thank you all in advance!
if (!le) {
(function () {
for (var e = window.document.getElementsByTagName("script"), t = 0, n = Object.values(e); t < n.length; t++) {
var r = n[t];
if (r.src && r.src.includes(te))
return r
}
return null
})() || function (e) {
var t = document.createElement("script");
t.src = te + "?l=" + e,
t.async = !0,
document.head.appendChild(t)
}
(ue),
function (e) {
var t = [];
Array.isArray(window[e]) ? t = window[e] : window[e] = t
}
(ue);
var r = ne(se, ue, ce),
i = r.wrappedGtag,
a = r.gtagCore;
ie = i,
re = a,
le = !0
}
Samsung's TizenOS's javascript isn't as up-to-date as it could be, and according to this looks to not be actively supported.
You can use react-app-polyfill to provide any missing functionalities.
We use the following in our root index.jsx as the "kitchen sink" of polyfills
import 'react-app-polyfill/ie9';
import 'react-app-polyfill/stable';
It seems Object.values() is not supported in your developing environment. Try adding this polyfill on top of your script file: https://github.com/tc39/proposal-object-values-entries/blob/master/polyfill.js
You can define your own values function if the node version is too low.
if (!Object.values) {
Object.values = function values(O) {
return Object.keys(O).map(k=>O[k]);
};
}

How to unpack an google.protobuf.Any type in gRPC nodejs client?

My protobuf file is like this:
syntax = "proto3"; import "google/protobuf/any.proto";
service RoomService {
getTestAny (Hotelid) returns (google.protobuf.Any); }
message Hotelid {
string hotelid = 1;
}
message HtlInDate {
Hotelid hotelid = 1;
string date = 2;
}
My java-gRPC-server code is like that:
#Override
public void getTestAny(Roomservice.Hotelid request, StreamObserver<Any> responseObserver) {
Roomservice.Hotelid hotelid = Roomservice.Hotelid.newBuilder()
.setHotelid("This is Hotelid")
.build();
Roomservice.HtlInDate htlDate = Roomservice.HtlInDate.newBuilder()
.setHotelid(hotelid)
.setDate("This is Data")
.build();
responseObserver.onNext(Any.pack(htlDate));
responseObserver.onCompleted();
}
And I make a request from a nodejs-gRPC-client, which code is like that:
function () {
var client = new services.RoomServiceClient('localhost:6565',
grpc.credentials.createInsecure());
var request = new messages.Hotelid();
var hotelid = "ignore";
request.setHotelid(hotelid);
var call = client.getTestAny(request, function (err, response) {
var obj = response.toObject();
console.log(obj);
});
}
The response in nodejs-gRPC-client is a type of Any. And it contains a data array:
array:["type.googleapis.com/HtlInDate", Uint8Array[10,17,10...]]
I try to use response.toObject() to get HtlInDate instance but I just get like this:
obj:{
typeUrl:"type.googleapis.com/HtlInDate",
value:"ChEKD1RoaXMgaXMgSG90ZWxpZBIMVGhpcyBpcyBEYXRh"
}
So how can I unpack the Any type response and get the HtlInDate instance exactly? Thanks a lot if you have any idea about this!
Currently, the google.protobuf.Any type is not supported in Node.js, either in Protobuf.js, which gRPC uses by default, or by google-protobuf, which is the official first party protobuf implementation.
From documentation:
https://developers.google.com/protocol-buffers/docs/reference/javascript-generated#message
// Storing an arbitrary message type in Any.
const status = new proto.foo.ErrorStatus();
const any = new Any();
const binarySerialized = ...;
any.pack(binarySerialized, 'foo.Bar');
console.log(any.getTypeName()); // foo.Bar
// Reading an arbitrary message from Any.
const bar = any.unpack(proto.foo.Bar.deserializeBinary, 'foo.Bar');
Please take a note that for browser support you need to use webpack(probably with babel loader) or browserify
As found in google-protobuf tests Any is bundled with pack and unpack functions.
Your code could be unpacked like this:
function () {
var client = new services.RoomServiceClient('localhost:6565',
grpc.credentials.createInsecure());
var request = new messages.Hotelid();
var hotelid = "ignore";
request.setHotelid(hotelid);
var call = client.getTestAny(request, function (err, response) {
var obj = response.toObject();
console.log('Any content', obj);
var date = response.unpack(messages.HtlInDate.deserializeBinary, response.getTypeName());
console.log('HtlInDate', date.toObject());
});
}
This will deserialize the bytes received in the Any object.
You could also build some Any using pack function for wrapping TypeUrl and Value:
var someAny = new Any();
someAny.pack(date.serializeBinary(), 'HtlInDate')

TypeError: tagGroupString.split is not a function + node.js +cucumber

I am getting below error when trying to execute the tests. I am using grunt-protractor-cucumber 0.6.0, protractor 3.2.2 - node 4.4, npm 3.8.8, typings 0.6.8,
I am using Windows OS
[launcher] Error: TypeError: tagGroupString.split is not a function
at Array.map (native)
at Array.filter (native)
[launcher] Process exited with error code 100
Above function is in cucumber-js/lib/cucumber/tag_group_parser.js
function TagGroupParser(tagGroupString) {
var self = {
parse: function parse() {
var splitTags = tagGroupString.split(TagGroupParser.TAG_SEPARATOR);
var trimmedTags = splitTags.map(function (tag) { return tag.trim(); });
return trimmedTags;
}
};
return self;
}
TagGroupParser.getTagGroupsFromStrings = function getTagGroupsFromStrings(tagGroupStrings) {
var Cucumber = require('../cucumber');
var tagGroups = tagGroupStrings.map(function (tagOptionValue) {
var tagGroupParser = Cucumber.TagGroupParser(tagOptionValue);
var tagGroup = tagGroupParser.parse();
return tagGroup;
});
return tagGroups;
};
TagGroupParser.TAG_SEPARATOR = ',';
module.exports = TagGroupParser;
Looks like it's a bug with npm 3.8.8 on Windows , it works fine on Mac. After down graded to 2.15, it worked fine.

Resources