Error Message : InvalidKey: A key should contain at least a kind - node.js

I am getting following error while trying to update the entity in google cloud datastore:
InvalidKey: A key should contain at least a kind.
at keyToKeyProto (/Volumes/Drive B/dev/zapi/node_modules/#google-cloud/datastore/src/entity.js:696:11)
at Array.map (<anonymous>)
at DatastoreRequest.createReadStream (/Volumes/Drive B/dev/zapi/node_modules/#google-cloud/datastore/src/request.js:226:23)
at DatastoreRequest.get (/Volumes/Drive B/dev/zapi/node_modules/#google-cloud/datastore/src/request.js:461:8)
at /Volumes/Drive B/dev/zapi/node_modules/#google-cloud/common/build/src/util.js:681:32
at new Promise (<anonymous>)
at Datastore.wrapper [as get] (/Volumes/Drive B/dev/zapi/node_modules/#google-cloud/common/build/src/util.js:662:20)
at fetchEntity (/Volumes/Drive B/dev/zapi/node_modules/gstore-node/lib/model.js:204:36)
at Function.get (/Volumes/Drive B/dev/zapi/node_modules/gstore-node/lib/model.js:174:16)
at Promise (/Volumes/Drive B/dev/zapi/node_modules/gstore-node/lib/utils.js:39:35)
at new Promise (<anonymous>)
at Function.wrapper (/Volumes/Drive B/dev/zapi/node_modules/gstore-node/lib/utils.js:27:16)
at resolve (/Volumes/Drive B/dev/zapi/graphql/mutations/user/linkConsult.js:101:44)
I don't know why is this coming for.
Thanks in advance.

When you trying to access key and key is not available when no data available, it gives the error
"Error Message : InvalidKey: A key should contain at least a kind"
To avoid this error first make sure that [datastrore.KEY] is available.
Thanks

I want to add to this answer with a little more detail. Here are some other helpful points to investigate if you run into this error when using the datastore.save method. The entity needs the correct key property like the example below.
// remember to use the key method on the google data store instance
const entity = {
key: dataStore.key('Name of your Kind') // this is Kind property you see on the GCP dashboard,
data: {
example: 'this is an example',
...
}
};
// then save the entity
const dbResult = await dataStore.save(entity)

Related

Channel Factory not registered when trying to store a SharedString within root SharedDirectory

I tried to create and store a new SharedString DDS on my root SharedDirectory with following code:
protected async initializingFirstTime() {
const text = SharedString.create(this.runtime);
this.root.set("text", text.handle)
}
When I run the app, I get following error in JavaScript console:
app.ts:49 Error: Channel Factory https://graph.microsoft.com/types/mergeTree not registered
at new LocalChannelContext (localChannelContext.js:19)
at FluidDataStoreRuntime.createChannel (dataStoreRuntime.js:169)
at Function.create (sharedString.js:33)
at DiceRoller.<anonymous> (dataObject.ts:43)
at Generator.next (<anonymous>)
at dataObject.ts:4
at new Promise (<anonymous>)
at ./src/dataObject.ts.__awaiter (dataObject.ts:4)
at DiceRoller.initializingFirstTime (dataObject.ts:42)
at DiceRoller.initializeInternal (pureDataObject.js:87)
You need to ensure you are registering all DDS types with your Data Object Factory.
public static readonly factory = new DataObjectFactory(
SomeFluidObject.Name,
SomeFluidObject,
[
SharedString.getFactory(),
],
{},
);

Cannot read property 'find' of undefined Discord.js

I am trying to make a discord.js bot delete a censored message from one channel and log it in an admin channel, this is my code:
msg.channel.send(exampleEmbed1);
msg.guilds.find("721079782833520651").send("Test")
It says this error:
TypeError: Cannot read property 'find' of undefined
at Client.<anonymous> (/Users/DShirriff/rebelbot/rebel.js:35:16)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (/Users/DShirriff/rebelbot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/Users/DShirriff/rebelbot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32) etc.
Pls someone help :) im pretty new to discord.js and I can't find the answer in other people's questions
msg.guilds does not exist.
Did you mean msg.guild? If you want to get a channel from that guild you will need to use msg.guild.channels
Depending on what version you are using:
v11:
const channel = msg.guild.channels.get("channel_id");
v12:
const channel = msg.guild.channels.cache.get("channel_id");
Use that (v12)
let channelID = "channeid";
client.channels.cache.get(channelID).send("Your Text")
// replace channelid to your channel id
Easy, No?

DocuSign' requestJWTUserToken method errors out with 'Not Initialized"

I'm trying to implement the DocuSign JWT Auth following this code example: https://github.com/docusign/eg-01-node-jwt/blob/master/lib/dsJwtAuth.js
But I get this error when calling requestJWTUserToken():
Error: Not initialised
at Sign.update (crypto.js:99:16)
at Object.sign (/code/node_modules/jwa/index.js:159:23)
at Object.jwsSign [as sign] (/code/node_modules/jws/lib/sign-stream.js:32:24)
at Object.module.exports [as sign (/code/node_modules/jsonwebtoken/sign.js:190:16)
at generateAndSignJWTAssertion (/code/node_modules/docusign-esign/src/ApiClient.js:63:16)
at exports.requestJWTUserToken (/code/node_modules/docusign-esign/src/ApiClient.js:892:19)
at ConsentGateway.<anonymous> (/code/app/gateways/ConsentGateway.ts:73:53)
at Generator.next (<anonymous>)
at /code/app/gateways/ConsentGateway.ts:19:71
at new Promise (<anonymous>)
at __awaiter (/code/app/gateways/ConsentGateway.ts:15:12)
at ConsentGateway.getToken (/code/app/gateways/ConsentGateway.ts:64:16)
at ConsentGateway.<anonymous> (/code/app/gateways/ConsentGateway.ts:54:41)
at Generator.next (<anonymous>)
at /code/app/gateways/ConsentGateway.ts:19:71
at new Promise (<anonymous>)
at __awaiter (/code/app/gateways/ConsentGateway.ts:15:12)
at ConsentGateway.checkToken (/code/app/gateways/ConsentGateway.ts:46:16)
at ConsentGateway.<anonymous> (/code/app/gateways/ConsentGateway.ts:139:24)
at Generator.next (<anonymous>)
at /code/app/gateways/ConsentGateway.ts:19:71
at new Promise (<anonymous>)
at __awaiter (/code/app/gateways/ConsentGateway.ts:15:12)
at ConsentGateway.getTemplateList (/code/app/gateways/ConsentGateway.ts:132:16)
at ConsentService.<anonymous> (/code/app/services/ConsentService.ts:58:50)
at Generator.next (<anonymous>)
at /code/app/services/ConsentService.ts:19:71
at new Promise (<anonymous>)
the code calling the method looks like this:
private async getToken(reqId: string): Promise<any> {
try {
const pathToPrivateKey = fs.readFileSync(path.resolve('/code/app/gateways/', 'test.pem'));
this.dsApiClient.setOAuthBasePath(this.authServer);
const jwtToken = await this.dsApiClient.requestJWTUserToken(
this.integrationKey, // clientId
this.guidAccountId, // userId
'signature',
pathToPrivateKey,
10 * 60
);
const expiresAt = moment().add(jwtToken.body.expires_in, 's');
return { accessToken: jwtToken.body.access_token, tokenExpirationTimestamp: expiresAt };
} catch (e) {
this.logger.error(
'Consent Error', reqId, ['accessToken'], { status: e.response.body.errorCode, message: e.response.body.message }
);
}
}
I cannot find any documentation for the requestJWTUserToken method which makes this error hard to debug.
Is there anyone familiar with the JWT Auth flow in node that could help out with this?
Here are the things that you must ensure:
You have an Integration key (clientID) that is configured correctly.
You have an RSA Private key. that key was copied/pasted exactly as given to your configuration file. New lines must be preserved
Your URLs are matching the environment. Meaning you use account-d and demo.docusign.net for the sandbox env endpoints.
You need the userId which is a GUid for the user that would be impersonated. That user must consent to the application. You have to ensure you pass userId and not accountId and that it is for the same account that you would be using.
If you confirm all of this and still get an error - I would consider to use our code example to start. I don't see code in your question, but our code example should be a good way to start.

How to update DocumentReference?

I tried to update DocumentReference but could not do it.
update() method fails. How to use it? (How to pass argument?)
firebase-admin version is 6.3.0.
#google-cloud/firestore version is 0.19.0.
❯ firebase functions:shell
i functions: Preparing to emulate functions.
Warning: You're using Node.js v8.14.0 but Google Cloud Functions only supports v6.11.5.
✔ functions: sampleFunc
firebase > const admin = require('firebase-admin');
firebase > admin.initializeApp();
firebase > let ref = admin.firestore().collection("users").doc('edqupYQhzqV1ODjEpoJn');
firebase > let updates = { email: 'xxx#yyy.zzz' };
firebase > ref.update(updates).then(value => console.log(value) );
Error: Update() requires either a single JavaScript object or an alternating list of field/value pairs that can be followed by an optional precondition. Argument "dataOrField" is not a valid Document. Input is not a plain JavaScript object.
at WriteBatch.update (/Users/xxx/Desktop/sample-functions/functions/node_modules/#google-cloud/firestore/build/src/write-batch.js:359:23)
at DocumentReference.update (/Users/xxx/Desktop/sample-functions/functions/node_modules/#google-cloud/firestore/build/src/reference.js:387:14)
Update
Document has already been created, so get() works.
firebase > ref.get().then(snapshot => console.log(snapshot.data()));
Errors also occur in set() as well.
firebase > ref.set({email: 'aaa#bbb.ccc'}, {merge: true}).then(value => console.log(value));
Error: Argument "data" is not a valid Document. Input is not a plain JavaScript object.
at Validator.(anonymous function).values [as isDocument] (/Users/xxx/Desktop/sample-functions/functions/node_modules/#google-cloud/firestore/build/src/validate.js:99:27)
at WriteBatch.set (/Users/xxx/Desktop/sample-functions/functions/node_modules/#google-cloud/firestore/build/src/write-batch.js:232:25)
at DocumentReference.set (/Users/xxx/Desktop/sample-functions/functions/node_modules/#google-cloud/firestore/build/src/reference.js:349:27)
Following the example you posted, you are trying to update a document that does not exist. In this case you should create it first.
If you're not sure whether the document exists, pass the option to merge the new data with any existing document to avoid overwriting entire documents.
From Google's Documentation:
var cityRef = db.collection('cities').doc('BJ');
var setWithOptions = cityRef.set({
capital: true
}, {merge: true});
Reference: Firestore Add Data
I've never tried using the Admin SDK in the functions:shell like you do in your example. However I can easily reproduce your error. I guess that the functions:shell somehow tampers with your variable updates. When i log updates undefined is concatenated in output
firebase > console.log(updates)
{ email2: 'xxx#yyy.zzz' }
undefined
If you put your code in a JS file, initialize your app with a service account and run in with node it will most likely work just fine!
Read more about how to use Service Account
create an object first then assign your values to a field/property on that object like:
var myObj = {};
myObj["myfield"] = myvalue;
now pass as the 2nd argument of .set or .update.

roleDelete event having problems after leaving guild

This error has appeared after I added a .catch statement to Promises after sending messages to guilds.
Quick Explanation: My bot is trying to retrieve data from a guild it no longer belongs to.
Here's my code:
Filename: roleDelete.js
'use strict';
const Discord = require('discord.js');
const Error = require('debug')('Event:roleDelete:Error');
/**
* #param {object} client - The client instance
* #param {object} role - The deleted role object
*/
module.exports.run = (client, role) => {
let embed = new Discord.RichEmbed();
const guildID = role.guild.id;
const guildName = role.guild.name;
const guildIcon = role.guild.iconURL;
const modLog = client.guilds.get(guildID).channels.find('name', client.config.modLog);
const tempIcon = 'https://images-ext-2.discordapp.net/external/ouGhEoGzz1ZyBG9mMFrYClvdv9V0FZ0jGSEHa_kLLYk/https/discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png';
if (!modLog) return;
embed = new Discord.RichEmbed()
.setAuthor(guildName, guildIcon ? guildIcon : tempIcon)
.addField('Role Name', role.name, true)
.addField('Role Color', role.hexColor, true)
.addField('Role Hoisted', role.hoist, true)
.setFooter('Role Deleted At')
.setTimestamp()
.setColor(client.config.colors.red);
return modLog.send(embed).catch(err => Error(err));
};
Additional Info:
bufferutil: 3.0.3
chalk: 2.3.0
clear: 0.0.1
debug: 3.1.0
discord.js: 11.3.0
dotenv: 4.0.0
firebase-admin: 5.8.1
moment: 2.20.1
opusscript: 0.0.6
Expected Result:
Discord.JS ignores and no error is thrown.
Current Result:
2018-01-23T12:34:05.029Z Event:guildDelete Left Guild: 395928739201941506, removed into database.
2018-01-23T12:34:05.212Z Event:roleDelete:Error DiscordAPIError: Missing Access
at item.request.gen.end (/app/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:71:65)
at then (/app/node_modules/snekfetch/src/index.js:218:21)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
2018-01-23T12:34:05.255Z Event:guildMemberRemove:Error DiscordAPIError: Missing Access
at item.request.gen.end (/app/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:71:65)
at then (/app/node_modules/snekfetch/src/index.js:218:21)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7
Is there any way to ignore the fact that it has left and completely ignore it?
This sounds like an error with multiple events running asynchronously. If that is the case, a simple check if the client is still in the guild should fix the issue. An example of one of the few ways to do this can be found below.
const guild = bot.guilds.get(myguildid); // Should return null if the guild is not found
if (!guild) // The guild does not exist.
The property used can be found here in the documentation. Of course, there are other ways to do this, but this also sounds like a bug with the library and caching. If this causes any further bugs and the above does not fix the issue, try reporting the issue in more detail on the Discord (to find and identify the bug). From there, they'll direct you to report it to their GitHub if it does turn out to be a bug. Happy coding!

Resources