Marklogic node js client api not connecting to database - node.js

I am trying to load some documents in my "Documents" database, but am getting this error on running node load.js(filename):
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:201:27) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}
load.js
// Load documents into the database.
const marklogic = require('marklogic');
const my = require('./my-connection.js');
const db = marklogic.createDatabaseClient(my.connInfo);
// Document descriptors to pass to write().
const documents = [
{ uri: '/gs/aardvark.json',
content: {
name: 'aardvark',
kind: 'mammal',
desc: 'The aardvark is a medium-sized burrowing, nocturnal mammal.'
}
},
{ uri: '/gs/bluebird.json',
content: {
name: 'bluebird',
kind: 'bird',
desc: 'The bluebird is a medium-sized, mostly insectivorous bird.'
}
},
{ uri: '/gs/cobra.json',
content: {
name: 'cobra',
kind: 'mammal',
desc: 'The cobra is a venomous, hooded snake of the family Elapidae.'
}
},
];
// Load the example documents into the database
db.documents.write(documents).result(
function(response) {
console.log('Loaded the following documents:');
response.documents.forEach( function(document) {
console.log(' ' + document.uri);
});
},
function(error) {
console.log(JSON.stringify(error, null, 2));
}
);
my-connection.js
module.exports = {
connInfo: {
host: 'localhost',
port: 8000,
user: 'user',
password: 'password'
}
};

Related

Can a push notification be send from the server without a client call?

I have a javascript file on my NodeJS server that runs at 00:00:00 and updates some fields in the database, if that happens I want to send out a push notification to some users. I've set this up in my Javascript file:
https://dev.to/devsmranjan/web-push-notification-with-web-push-angular-node-js-36de
const subscription = {
endpoint: '',
expirationTime: null,
keys: {
auth: '',
p256dh: '',
},
};
const payload = {
notification: {
title: 'Title',
body: 'This is my body',
icon: 'assets/icons/icon-384x384.png',
actions: [
{action: 'bar', title: 'Focus last'},
{action: 'baz', title: 'Navigate last'},
],
data: {
onActionClick: {
default: {operation: 'openWindow'},
bar: {
operation: 'focusLastFocusedOrOpen',
url: '/signin',
},
baz: {
operation: 'navigateLastFocusedOrOpen',
url: '/signin',
},
},
},
},
};
const options = {
vapidDetails: {
subject: 'mailto:example_email#example.com',
publicKey: process.env.REACT_APP_PUBLIC_VAPID_KEY,
privateKey: process.env.REACT_APP_PRIVATE_VAPID_KEY,
},
TTL: 60,
};
webpush.sendNotification(subscription, JSON.stringify(payload), options)
.then((_) => {
console.log(subscription);
console.log('SENT!!!');
console.log(_);
})
.catch((_) => {
console.log(subscription);
console.log(_);
});
But when I run the file I get the message:
{ endpoint: '', expirationTime: null, keys: { auth: '', p256dh: '' } } Error: You must pass in a subscription with at least an endpoint.
Which makes sense since the server has no idea about service workers etc. Any suggestions on how to proceed?

Why am I getting this error when I run my Discord Bot? - code: 50035

When I run my Discord bot, which is made through the Discord.js and Node.js framework, I receive the following error.
node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293
throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50035]: Invalid Form Body
options[0].type[NUMBER_TYPE_COERCE]: Value "string" is not int.
options[1].type[NUMBER_TYPE_COERCE]: Value "string" is not int.
at SequentialHandler.runRequest (D:\Programming\GitHub\void-bot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (D:\Programming\GitHub\void-bot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
at async REST.request (D:\Programming\GitHub\void-bot\node_modules\#discordjs\rest\dist\lib\REST.cjs:52:22)
at async GuildApplicationCommandManager.create (D:\Programming\GitHub\void-bot\node_modules\discord.js\src\managers\ApplicationCommandManager.js:144:18) {
rawError: {
code: 50035,
errors: {
options: {
'0': { type: { _errors: [Array] } },
'1': { type: { _errors: [Array] } }
}
},
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/applications/1016623217399570512/guilds/915541815225118740/commands',
requestBody: {
files: undefined,
json: {
name: 'poll',
name_localizations: undefined,
description: 'Sets up a poll.',
description_localizations: undefined,
type: undefined,
options: [
{
type: 'string',
name: 'title',
name_localizations: undefined,
name_localized: undefined,
description: 'The title of the poll.',
description_localizations: undefined,
description_localized: undefined,
required: true,
autocomplete: undefined,
choices: undefined,
options: undefined,
channel_types: undefined,
min_value: undefined,
max_value: undefined,
min_length: undefined,
max_length: undefined
},
{
type: 'string',
name: 'content',
name_localizations: undefined,
name_localized: undefined,
description: 'The content of the poll.',
description_localizations: undefined,
description_localized: undefined,
required: true,
autocomplete: undefined,
choices: undefined,
options: undefined,
channel_types: undefined,
min_value: undefined,
max_value: undefined,
min_length: undefined,
max_length: undefined
}
],
default_member_permissions: undefined,
dm_permission: undefined
}
}
}
I am unsure why I am receiving this for the code below:
require("dotenv").config();
const { GatewayIntentBits } = require("discord.js");
const Discord = require("discord.js");
const PREFIX = "!";
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildBans,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildWebhooks,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildScheduledEvents
]
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
const guildID = "915541815225118740";
const guild = client.guilds.cache.get(guildID);
let commands;
if (guild) {
commands = guild.commands;
} else {
commands = client.application?.commands;
}
commands?.create({
name: "poll",
description: "Sets up a poll.",
options: [
{
name: "title",
description: "The title of the poll.",
required: true,
type: "string"
},
{
name: "content",
description: "The content of the poll.",
required: true,
type: "string"
}
]
});
});
client.on("interactionCreate", async (interaction) => {
if (!interaction.isCommand()) {
return;
}
const { commandName, options } = interaction;
if (commandName === "poll") {
const embed = new Discord.EmbedBuilder()
.setColor(0x0099FF)
.setTitle(options.get("title"))
.addFields(
{
value: options.get("content"),
inline: false
},
{
value: ":thumbsup: - Yes",
inline: true
},
{
value: ":thumbsdown: - No",
inline: true
}
)
}
interaction.reply(embed);
});
client.login(process.env.TOKEN);
I hope someone can help me out with this. It would be greatly appreciated as I have been stuck on this issue for a couple of days now.
Thanks,
nozzy
You've specified the option type using a string literal. It should be a value of the ApplicationCommandOptionType enum. So instead you should be using:
{
name: "...",
description: "...",
required: ...
type: ApplicationCommandOptionType.STRING
}

Trying to disable a button but an error popped up

I am making a help command, but I want to disable it when the embed title is the same as the button label. Except this error pops out:
C:\Users\admin\OneDrive\Documents\VSCode\JS\Discord
Bots\Testing3.JS\node_modules\discord.js\src\rest\RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Invalid Form Body components[0]: The specified
component type is invalid in this context components[1]: The specified
component type is invalid in this context
at RequestHandler.execute (C:\Users\admin\OneDrive\Documents\VSCode\JS\Discord
Bots\Testing3.JS\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\admin\OneDrive\Documents\VSCode\JS\Discord
Bots\Testing3.JS\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async MessageManager.edit (C:\Users\admin\OneDrive\Documents\VSCode\JS\Discord
Bots\Testing3.JS\node_modules\discord.js\src\managers\MessageManager.js:132:15)
{ method: 'patch', path:
'/channels/956427421073158194/messages/965228940685897748', code:
50035, httpStatus: 400, requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: [
{
title: 'Economy',
type: 'rich',
description: null,
url: null,
timestamp: null,
color: null,
fields: [ [Object], [Object], [Object], [Object] ],
thumbnail: null,
image: null,
author: null,
footer: null
}
],
components: [
{
custom_id: 'econ',
disabled: true,
emoji: { animated: false, name: '💵', id: null },
label: 'Economy',
style: 1,
type: 2,
url: null
},
{
custom_id: 'info',
disabled: false,
emoji: { animated: false, name: '📃', id: null },
label: 'Info',
style: 2,
type: 2,
url: null
}
],
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: 0,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: [] } }
Code:
if (cmd === "help") {
const econ = new Discord.MessageButton()
.setCustomId('econ')
.setEmoji('💵')
.setLabel('Economy')
.setStyle('PRIMARY')
const info = new Discord.MessageButton()
.setCustomId('info')
.setEmoji('📃')
.setLabel('Info')
.setStyle('SECONDARY')
const row = new Discord.MessageActionRow().addComponents([econ, info]);
let helpMsg = await message.channel.send({
embeds: [
{
title: "Economy",
fields: [
{
name: `\`${cPrefix}bal | balance [user]\``,
value: 'Displays your balance or a user\'s balance.'
},
{
name: `\`${cPrefix}dep | deposit <amount>\``,
value: 'Deposits a specified amount of cash to your bank.'
},
{
name: `\`${cPrefix}with | withdraw <amount>\``,
value: 'Withdraws a specified amount of cash to your wallet.'
},
{
name: `\`${cPrefix}addcoins <user> <amount>\``,
value: 'Adds a specified amount of cash to a user. (Administrator)'
}
]
}
],
components: [row]
});
const collector = helpMsg.createMessageComponentCollector({
componentType: 'BUTTON',
time: 60000
});
collector.on('collect', async (b) => {
if (b.user.id === message.author.id) {
if (b.customId === 'econ') {
helpMsg.edit({
embeds: [
{
title: "Economy",
fields: [
{
name: `\`${cPrefix}bal | balance [user]\``,
value: 'Displays your balance or a user\'s balance.'
},
{
name: `\`${cPrefix}dep | deposit <amount>\``,
value: 'Deposits a specified amount of cash to your bank.'
},
{
name: `\`${cPrefix}with | withdraw <amount>\``,
value: 'Withdraws a specified amount of cash to your wallet.'
},
{
name: `\`${cPrefix}addcoins <user> <amount>\``,
value: 'Adds a specified amount of cash to a user. (Administrator)'
}
]
},
],
components: [row.components[0].setDisabled(true), row.components[1].setDisabled(false)]
});
}
if (b.customId === 'info') {
helpMsg.edit({
embeds: [
{
title: "Info",
fields: [
{
name: `${cPrefix}info <user|server> <user: user>`,
value: 'Displays an info of the server or a user'
},
{
name: `${cPrefix}ping`,
value: 'Displays the current client ping and the database connection'
},
{
name: `${cPrefix}help`,
value: 'Umm... You used this command'
},
]
}
],
components: [row.components[0].setDisabled(false), row.components[1].setDisabled(true)]
})
}
} else {
b.reply({ content: 'These buttons are not for you.', ephemeral: true })
}
});
collector.on('end', async () => {
helpMsg.edit({ components: [row.components[0].setDisabled(true), row.components[1].setDisabled(true)] })
});
}
Is there anything wrong in this code?
You can create a new MessageActionRow and set everything to disabled. This code is from my bot's help command (discord.js v13.6.0):
let btnraw = new Discord.MessageActionRow().addComponents(
[
new Discord.MessageButton().setCustomId("home").setStyle("SUCCESS").setLabel("Home"),
new Discord.MessageButton().setCustomId("general").setStyle("PRIMARY").setLabel("General"),
new Discord.MessageButton().setCustomId("info").setStyle("PRIMARY").setLabel("Information"),
new Discord.MessageButton().setCustomId("mod").setStyle("PRIMARY").setLabel("Moderation"),
new Discord.MessageButton().setCustomId("fun").setStyle("PRIMARY").setLabel("Fun"),
]
);
let dbtnraw = new Discord.MessageActionRow().addComponents(
[
new Discord.MessageButton().setCustomId("d_home").setStyle("SUCCESS").setLabel("Home").setDisabled(true),
new Discord.MessageButton().setCustomId("d_general").setStyle("PRIMARY").setLabel("General").setDisabled(true),
new Discord.MessageButton().setCustomId("d_info").setStyle("PRIMARY").setLabel("Information").setDisabled(true),
new Discord.MessageButton().setCustomId("d_mod").setStyle("PRIMARY").setLabel("Moderation").setDisabled(true),
new Discord.MessageButton().setCustomId("d_fun").setStyle("PRIMARY").setLabel("Fun").setDisabled(true),
]
);
Then you can edit the message to replace the original row like this:
helpMsg.edit({components: [d_btnraw]});

Apollo GraphQL Server - Access query params from cache plugin

I have an Apollo GraphQL server using the apollo-server-plugin-response-cache plugin and I need to determine whether or not I'm going to write to the cache based on incoming parameters. I have the plugin set up and I'm using the shouldWriteToCache hook. I can print out the GraphQLRequestContext object that gets passed into the hook, and I can see the full request source, but request.variables is empty. Other than parsing the query itself, how can I access the actual params for the resolver in this hook? (In the example below, I need the value of param2.)
Apollo Server:
new ApolloServer({
introspection: true,
playground: true,
subscriptions: false,
typeDefs,
resolvers,
cacheControl: {
defaultMaxAge: 60
},
plugins: [
apolloServerPluginResponseCache({
cache, // This is a "apollo-server-cache-redis" instance
shouldWriteToCache: (requestContext) => {
// I get a lot of info here, including the source query, but not the
// parsed out query variables
console.log(requestContext.request);
// What I want to do here is:
return !context.request.variables.param2
// but `variables` is empty, and I can't see that value parsed anywhere else
}
})
]
})
Here is my resolver:
export async function exapi(variables, context) {
// in here I use context.param1 and context.param2
// ...
}
I have also tried:
export async function exapi(variables, { param1, param2 }) {
// ...
}
Here is what I get logged out from the code above:
{
query: '{\n' +
' exapi(param1: "value1", param2: true) {\n' +
' records\n' +
' }\n' +
'}\n',
operationName: null,
variables: {}, // <-- this is empty?! How can I get param2's value??
extensions: undefined,
http: Request {
size: 0,
timeout: 0,
follow: 20,
compress: true,
counter: 0,
agent: undefined,
[Symbol(Body internals)]: { body: null, disturbed: false, error: null },
[Symbol(Request internals)]: {
method: 'POST',
redirect: 'follow',
headers: [Headers],
parsedURL: [Url],
signal: null
}
}
}
If you didn't provide variables for GraphQL query, you could get the arguments from the GraphQL query string via ArgumentNode of AST
If you provide variables for GraphQL query, you will get them from requestContext.request.variables.
E.g.
server.js:
import apolloServerPluginResponseCache from 'apollo-server-plugin-response-cache';
import { ApolloServer, gql } from 'apollo-server';
import { RedisCache } from 'apollo-server-cache-redis';
const typeDefs = gql`
type Query {
exapi(param1: String, param2: Boolean): String
}
`;
const resolvers = {
Query: {
exapi: (_, { param1, param2 }) => 'teresa teng',
},
};
const cache = new RedisCache({ host: 'localhost', port: 6379 });
const server = new ApolloServer({
introspection: true,
playground: true,
subscriptions: false,
typeDefs,
resolvers,
cacheControl: {
defaultMaxAge: 60,
},
plugins: [
apolloServerPluginResponseCache({
cache,
shouldWriteToCache: (requestContext) => {
console.log(requestContext.document.definitions[0].selectionSet.selections[0].arguments);
return true;
},
}),
],
});
server.listen().then(({ url }) => console.log(`🚀 Server ready at ${url}`));
GraphQL query:
query{
exapi(param1: "value1", param2: true)
}
Server logs print param1 and param2 arguments:
🚀 Server ready at http://localhost:4000/
[]
[ { kind: 'Argument',
name: { kind: 'Name', value: 'param1', loc: [Object] },
value:
{ kind: 'StringValue',
value: 'value1',
block: false,
loc: [Object] },
loc: { start: 15, end: 31 } },
{ kind: 'Argument',
name: { kind: 'Name', value: 'param2', loc: [Object] },
value: { kind: 'BooleanValue', value: true, loc: [Object] },
loc: { start: 33, end: 45 } } ]

Email-Templates/Nodemailer emails not containing template

I'm trying to send an ejs template with email-templates but I'm not having much joy.
The email sends fine, however it doesn't contain any template data.
const email = new Email ({
template: 'activateAccount',
message: {
from: "noreply#domain.com",
subject: "Activate your account!",
to: data.email
},
locals: {
name: data.name,
url: data.url
},
send: true,
transport: {
host: "domain.com",
port: 2525,
auth: {
user: "abc",
pass: "123"
}
},
views: {
options: {
extension: 'ejs'
}
}
});
return await email.send();
Does anyone know why the templates aren't being populated?
Use the locals when .sending the email,
const email = new Email({
message: {
from: "noreply#domain.com",
subject: "Activate your account!",
to: data.email
},
send: true,
transport: {
host: "domain.com",
port: 2525,
auth: {
user: "abc",
pass: "123"
}
},
views: {
options: {
extension: 'ejs'
}
}
});
await email.send({
template: 'activateAccount',
locals: {
name: data.name,
url: data.url
}
});
Basically, you can use all the options is .send function itself.

Resources