Starting Apollo Server - javascript

Hey I'm startin to learn graphQL by doing the Frontend Masters' course Introduction to GraphQL (repo).
I would start by the context, but I look everywhere and nothing, also I tried to change it but it´s always the SAME output. If someone could help I'll be very, very grateful.
I'm trying to start the server with the next code:
import { ApolloServer } from 'apollo-server'
import { loadTypeSchema } from './utils/schema'
import { authenticate } from './utils/auth'
import { merge } from 'lodash'
import config from './config'
import { connect } from './db'
import product from './types/product/product.resolvers'
import coupon from './types/coupon/coupon.resolvers'
import user from './types/user/user.resolvers'
const types = ['product', 'coupon', 'user']
export const start = async () => {
const rootSchema = `
type Cat {
name: String
}
type _Query {
myCat: Cat
}
schema {
query: _Query
mutation: Mutation
}
`
const schemaTypes = await Promise.all(types.map(loadTypeSchema))
const server = new ApolloServer({
typeDefs: [rootSchema, ...schemaTypes],
resolvers: {
_Query: {
myCat(){
console.log('Hello there')
return {name:'Ivar'}
}
},
async context({ req }) {
const user = await authenticate(req)
return { user }
}
}
}
)
await connect(config.dbUrl)
const {url} = await server.listen({port: config.port})
console.log(`GQL server ready at ${url}`)
}
db file:
import mongoose from 'mongoose'
import options from './config'
export const connect = (url = options.dbUrl, opts = {}) =>
{ return mongoose .connect(url, {
useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
.then(() => console.log('Database Connected'))
.catch(err => console.log(err))
}
The curious thing is that in some moment it worked well, I've made changes, but not important ones.
The console output is this:
...
$ node dist/index.js
(node:17124) UnhandledPromiseRejectionWarning: Error: "context" defined in resolvers, but not in schema (Use `node --trace-warnings ...` to show where the warning was created)
(node:17124) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:17124) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[nodemon] clean exit - waiting for changes before restart
I'm sure that is a silly bug but it's freaking me out.

The context is part of the configuration object you pass to ApolloServer, not part of its .resolvers object.
const server = new ApolloServer({
typeDefs: [rootSchema, ...schemaTypes],
resolvers: {
_Query: {
myCat(){
console.log('Hello there')
return {name:'Ivar'}
}
},
},
async context({ req }) {
const user = await authenticate(req)
return { user }
},
})

Related

Axios Get request with Looker API

I am trying to create a lookerbot. I want my node app to reach looker but I keep getting this error:
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "AxiosError: Request failed with status code 401".] {
code: 'ERR_UNHANDLED_REJECTION'
}
Node.js v17.9.0
error Command failed with exit code 1.
This is my code:
const axios = require('axios');
const qs = require('qs');
const SLACK_KEY = 'xoxb-1234';
const LOOKER_URL = 'https://xyz.abc.looker.com:19999/api/3.0/';
const LOOKER_CLIENT_ID = 'mnbv';
const LOOKER_CLIENT_SECRET = 'lkjh'
axios.get(LOOKER_URL, {
params: {
'clientId': LOOKER_CLIENT_ID,
'clientSecret': LOOKER_CLIENT_SECRET
}
})
.then(function (res) {
console.log(res);
})
I am not sure what my error is and how to make my node app reach my looker instance.

Firebase: Cloud function changing data in firestore - Permission denied on resource project [X:YYYYYYYYYY:web:KKKKKKKKKKKK]

I am trying to add data to my firestore collection via firebase cloud functions. However, when executing the function the following error appears.
My cloud function code is:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
const Firestore = require("#google-cloud/firestore");
const PROJECTID = "[...]";
const firestore = new Firestore({
projectId: PROJECTID,
timestampsInSnapshots: true,
});
exports.createNewChat = functions.region("europe-west1")
.https.onRequest((request, response) => {
console.log("!!!!!!");
console.log("THe BodY: " + request);
console.log("THe BodY: " + request.rawBody);
console.log("THe BodY: " + request.body);
try {
const groupName = request.body.groupName;
const members: string[] = request.body.members;
firestore.collection("chats").add({
groupName: groupName,
members: members,
lastMessage: new Date(),
messages: [],
}).then((doc: any) => {
const chatId = doc.id;
members.forEach((member) => {
firestore.collection("myChats/" + member).add({
chatKey: chatId,
});
});
return response.status(200).send(doc);
});
} catch (e) {
functions.logger.log("catch clause " + e);
response.status(500).send(e);
}
});
My postman request looks like this:
Header: Content-Type -> application/json
Body (raw, json):
{
"groupName": "someGroupName",
"members": [
"123321aklslasl"
]
}
The exception which is thrown is:
! Google API requested!
URL: "https://oauth2.googleapis.com/token"
Be careful, this may be a production service.
(node:23224) UnhandledPromiseRejectionWarning: Error: 7 PERMISSION_DENIED: Permission denied on resource project [...].
at Object.callErrorFromStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\call.js:31:26)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client.js:179:52)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client-interceptors.js:336:141)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client-interceptors.js:299:181)
at E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\call-stream.js:145:78
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Caused by: Error
at WriteBatch.commit (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\write-batch.js:414:23)
at DocumentReference.create (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\reference.js:291:14)
at CollectionReference.add (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\reference.js:1967:28)
at E:\Workspaces\cloudFunctions\functions\lib\index.js:39:39
at C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:560:16
at runFunction (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:533:15)
at runHTTPS (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:559:11)
at handler (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:479:23)
at Layer.handle [as handle_request] (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\express\lib\router\route.js:137:13)
(node:23224) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). T
o terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:23224) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
In a Cloud Function for Firebase you should use the Admin SDK for Node.js and not the standard JS SDK.
In addition, you need to use Promise.all() to execute in parallel the calls to the asynchronous add() method in the forEach() loop.
So the following set of adaptations should solve your problem:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
exports.createNewChat = functions.region("europe-west1")
.https.onRequest((request, response) => {
const groupName = request.body.groupName;
const members: string[] = request.body.members;
const db = admin.firestore();
db.collection("chats").add({
groupName: groupName,
members: members,
lastMessage: new Date(),
messages: [],
}).then((doc: any) => {
const chatId = doc.id;
const promises = [];
members.forEach((member) => {
promises.push(db.collection("myChats/" + member).add({
chatKey: chatId,
}));
});
return Promise.all(promises);
})
.then(() => {
response.status(200).send(JSON.stringify(doc));
})
.catch(e => {
functions.logger.log("catch clause " + e);
response.status(500).send(JSON.stringify(e));
});
});

Trying to susbcribe to PairCreated events from UniswapV2 Factory in Nodejs

I have previously used this code to get events from PancakeSwapV2 factory on the Binance Smart Chain. I'd like now to use this code to get events from UniswapV2 factory on the Ethereum blockchain but I get the following error :
(node:3544) UnhandledPromiseRejectionWarning: Error: resolver or addr is not configured for ENS name (argument="name", value="0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ", code=INVALID_ARGUMENT, version=contracts/5.4.0)
at Logger.makeError (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\logger\lib\index.js:187:21)
at Logger.throwError (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\logger\lib\index.js:196:20)
at Logger.throwArgumentError (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\logger\lib\index.js:199:21)
at C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\contracts\lib\index.js:101:32
at step (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\contracts\lib\index.js:48:23)
at Object.next (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\contracts\lib\index.js:29:53)
at fulfilled (C:\Users\aaaa\WebstormProjects\web3test\node_modules\#ethersproject\contracts\lib\index.js:20:58)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3544) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To
terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3544) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Process finished with exit code 0
Here's the source code I'm trying to reuse :
const Web3 = require('web3');
const ethers = require('ethers');
const INFURA_BASE_URL = 'https://mainnet.infura.io/v3/';
const INFURA_API_KEY = 'REPLACE';
web3 = new Web3(new Web3.providers.HttpProvider(INFURA_BASE_URL + INFURA_API_KEY));
const privateKey = "REPLACE";
const account = web3.eth.accounts.privateKeyToAccount(privateKey)
console.log(account.address)
const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/REPLACE');
const wallet = new ethers.Wallet(privateKey);
const account2 = wallet.connect(provider);
const addresses = {
WETH: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
factory: '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ',
router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ',
recipient: account.address
};
//console.log(provider)
const factory = new ethers.Contract(
addresses.factory,
[
'event PairCreated(address indexed token0, address indexed token1, address pair, uint)',
'function getPair(address tokenA, address tokenB) external view returns (address pair)'
],
account2
);
factory.on('PairCreated', async (token0, token1, pairAddress) => { }
Would you know what I'm doing wrong ? Thank you.
It seems that I'm approaching the solution with this piece of code :
const Web3 = require("web3");
let web3 = new Web3(
new Web3.providers.WebsocketProvider("wss://mainnet.infura.io/ws/v3/cc44823998a0412294a47680xxxxxxxx")
);
let abi = JSON.parse('[{"inputs":[{"internalType":"address","name":"_feeToSetter","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token0","type":"address"},{"indexed":true,"internalType":"address","name":"token1","type":"address"},{"indexed":false,"internalType":"address","name":"pair","type":"address"},{"indexed":false,"internalType":"uint256","name":"","type":"uint256"}],"name":"PairCreated","type":"event"},{"constant":true,"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"allPairs","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"allPairsLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"}],"name":"createPair","outputs":[{"internalType":"address","name":"pair","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"feeTo","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"feeToSetter","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"getPair","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_feeTo","type":"address"}],"name":"setFeeTo","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_feeToSetter","type":"address"}],"name":"setFeeToSetter","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]')
const instance = new web3.eth.Contract(abi, '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f');
//web3.eth.getBlockNumber().then(console.log)
instance.getPastEvents(
"allEvents",
{fromBlock: "12908000", toBlock: "12908094"},
(errors, events) => {
if (!errors) {
//console.log('it is ok')
//console.log(events)
}
}
).then(r => {
console.log(r)
});

SSH2 issues wiht Node.js

I got this code that it seems to be working but it does not.
let REMOTE_SSH_HOST = '190.444.01.75:55554'
let REMOTE_SSH_USERNAME = 'olec'
let REMOTE_SSH_PASSWORD = 'm3uW4jkbaEwVChklFszpbm4'
const Client = require('ssh2-sftp-client');
const sshConfig = {
host: process.env.REMOTE_SSH_HOST,
//port: 22,
username: process.env.REMOTE_SSH_USERNAME,
password: process.env.REMOTE_SSH_PASSWORD,
readyTimeout: 99999,
};
let sftp = new Client();
async function Read(directory) {
console.log('Read(' + directory + ')');
const result = await sftp.list(directory);
for(const sub of result) {
if (sub['type'] === 'd') {
await Read(directory + '/ ' + sub['name']);
}
}
}
async function main(directory) {
try{
const myList = await sftp.list(directory);
}catch(err){console.log(err)}//NEVER forget to catch
finally {
console.log('Closing session...');
await sftp.end();
console.log('Session closed.');
}
}
console.log('Application started');
main('/home/user/path').then(r => {
console.log('Application ended.');
});
I get the error message of:
(Use node --trace-warnings ... to show where the warning was created)
(node:16240) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 5)
(node:16240) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.
I think you might need something like
const sftp = new Client();
await sftp.connect({
host: hostAddress,
username: '...',
privateKey: ...,
});
The issue is you are using environment variables where you have set consts. (also you are setting consts as lets... don't ever use a let where something will never change.
const Client = require('ssh2-sftp-client');
const REMOTE_SSH_HOST = '190.444.01.75'
const REMOTE_SSH_PORT = '55554';
const REMOTE_SSH_USERNAME = 'olec'
const REMOTE_SSH_PASSWORD = 'm3uW4jkbaEwVChklFszpbm4'
const sshConfig = {
host: REMOTE_SSH_HOST,
port: REMOTE_SSH_PORT,
username: REMOTE_SSH_USERNAME,
password: REMOTE_SSH_PASSWORD,
readyTimeout: 99999,
};
Thnx gonna try this and get back to you!
There are a series of errors on your script that are causing the issue. The main one is that you are not handling errors in your async code. You should add a catch chain function to your main call because, even though you are using a try/catch clause inside your main function, it doesn't consider the code that runs inside the finally block.
On the other hand, your code seems to be failing because you are running sftp.list before running sftp.connect.
There are a couple of minor errors that could potentially cause problems in your script:
The address 190.444.01.75 is not a valid IPv4 address.
You should provide default values when reading env variables where they make sense.
You are not really using the Read function yet, but I would suggest you name functions in lower case.
You are declaring the variable of the for-of loop inside the Read function with const. It would be best to use let instead since the engine will update it on each iteration.
Here is a modified example of your script that works:
const Client = require('ssh2-sftp-client')
/**
* Global variables
*/
const SSH_CONFIG = {
host : process.env.REMOTE_SSH_HOST || '190.44.1.75:55554',
port : process.env.REMOTE_SSH_PORT || 22,
username : process.env.REMOTE_SSH_USERNAME || 'olec',
password : process.env.REMOTE_SSH_PASSWORD,
readyTimeout: 99999,
}
const ROOT = process.env.ROOT || '/home/user/path'
/**
* Constructors
*/
const sftp = new Client()
/**
* Main
*/
console.log("Application Started!")
main(ROOT)
.then ((response) => console.log(response))
.catch((err) => console.error(err))
/**
* Functions
*/
async function main(directory) {
let myList
try {
await sftp.connect(SSH_CONFIG)
return await sftp.list(directory)
} catch(err) {
console.error(err)
} finally {
console.log('Closing session...')
await sftp.end()
console.log('Session closed.')
}
}
And here is how you would call it:
env REMOTE_SSH_HOST=10.0.0.10 \
env REMOTE_SSH_USERNAME=conatel \
env REMOTE_SSH_PASSWORD=C0n4t3lC0n4t3l \
env REMOTE_SSH_PORT=22 \
env ROOT=/home/conatel \
node ssh.js

Discord.js embed image not working. (Could not interpret "{'url': 'https://cdn.nekos.life/boobs/boobs105.gif'}" as string.)

My command.js
based on some other bots like HarutoHiroki Bot thst open source on Github and the Nekos.life documentation
const Discord = require('discord.js');
const client = require('nekos.life');
const neko = new client();
module.exports.run = async (bot, message, args) => {
if (message.channel.nsfw === true) {
link = await neko.nsfw.boobs()
console.log(link)
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link)
.setFooter(`Bot by`);
message.channel.send(embed);
}
else {
message.channel.send("This isn't NSFW channel!")
}
};
module.exports.config = {
name: "boobs",
description: "",
usage: "*boobs",
accessableby: "Members",
aliases: []
}
Error:
> node .
(node:25052) ExperimentalWarning: Conditional exports is an experimental feature. This feature could change at any time
Logged in and connected as Bot#1234
{ url: 'https://cdn.nekos.life/boobs/boobs105.gif' }
(node:25052) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.image.url: Could not interpret "{'url': 'https://cdn.nekos.life/boobs/boobs105.gif'}" as string.
at RequestHandler.execute (C:\Users\User\Documents\GitHub\Bot\node_modules\discord.js\src\rest\RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:25052) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)(node:25052) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
My Question
how to fix this? (I tried the hole day but didn't got it working need help soon as possible)
I fixed it:
const Discord = require('discord.js');
const client = require('nekos.life');
const neko = new client();
module.exports.run = async (bot, message, args) => {
if (message.channel.nsfw === true) {
link = await neko.nsfw.boobs()
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link.url)
.setFooter(`Bot by`);
message.channel.send(embed);
}
else {
message.channel.send("This isn't NSFW channel!")
}
};
module.exports.config = {
name: "boobs",
description: "",
usage: "*boobs",
accessableby: "Members",
aliases: []
}
It looks like neko.nsfw.boobs() returns an object, not a string. Try this instead:
const { url } = await neko.nsfw.boobs(); // get only the URL, not the whole object
const embed = new Discord.MessageEmbed()
.setAuthor(`Some neko boobs`)
.setColor('#00FFF3')
.setImage(link.url)
.setFooter(`Bot by`);
message.channel.send(embed);
Here's a code snippet example:
const link = {
url: 'https://cdn.nekos.life/boobs/boobs105.gif'
};
console.log(link); // this will not give the link. it will give the whole object
/* using object destructuring, you can use brackets to capture one
property of an array. in this case, the url.
Object Destructuring - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
*/
const {
url
} = link;
console.log(url); // this will give *only* the link
console.log(link.url); // another method to give only the link

Categories

Resources