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.
Related
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));
});
});
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
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 }
},
})
I'm using Jest to write a test and mock a function that calls an HTTP request.
import { mocked } from "ts-jest/utils";
import * as pull from "../src/pull";
import fs = require("fs");
// read the reponse data from a file.
const response = JSON.parse(
fs.readFileSync("./__fixtures__/pr.json", "utf8")
);
// have jest mock the function and set it's response.
jest.mock("../src/pull");
const mockedCoeus = mocked(pull.getPullRequest, true);
mockedCoeus.mockImplementation(async () => {
return response as any;
});
// write the test.
describe("#get details for a PR", () => {
it("should load user data", async () => {
const data = await pull.getPullRequest(165, "data-ios");
expect(data).toBeDefined();
expect(data.updated_at).toEqual("2020-04-10T16:46:30Z");
});
});
The test passes, however, I get the following error when running npm jest
TypeError: mockedCoeus.mockImplementation is not a function
I've looked at other reported errors having to do with the placement of jest.mock however, it does not seem to be the case here. Why is this error thrown but the tests pass? How can I fix it?
I receive an error when attempting to web-scrape images off amazon. The goal is to download the book cover.
(node:26904) UnhandledPromiseRejectionWarning: Error: undefined is not a valid uri or options object.
at request (C:\Users\Isaac\Desktop\webscrape_with_cheerio\node_modules\request\index.js:44:11)
at PromisseHandle._RejectOrResolve (C:\Users\Isaac\Desktop\webscrape_with_cheerio\node_modules\node-image-downloader\src\image-downloader.js:86:5)
at new Promise (<anonymous>)
at ImageDownloader (C:\Users\Isaac\Desktop\webscrape_with_cheerio\node_modules\node-image-downloader\src\image-downloader.js:98:26)
at Request._callback (C:\Users\Isaac\Desktop\webscrape_with_cheerio\index.js:22:13)
at Request.self.callback (C:\Users\Isaac\Desktop\webscrape_with_cheerio\node_modules\request\request.js:185:22)
at Request.emit (events.js:210:5)
at Request.<anonymous> (C:\Users\Isaac\Desktop\webscrape_with_cheerio\node_modules\request\request.js:1154:10)
at Request.emit (events.js:210:5)
at IncomingMessage.<anonymous> (C:\Users\Isaac\Desktop\webscrape_with_cheerio\node_modules\request\request.js:1076:12)
(node:26904) 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(). (rejection id: 2)
(node:26904) [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.
Here is my code thus far. I believe my error stems from the line;
var imagesrc = $(".a-row center-align litb-on-click img").attr('src')
I need to access the Class over where the book url is, though i might be wrong.
const express = require('express');
const cheerio = require('cheerio');
const download = require('node-image-downloader');
const request = require('request');
const app = express();
app.get('/', (req, res) => {
var url = "https://www.amazon.com/Black-Swan-Improbable-Robustness-Fragility/dp/081297381X"
// makeing a request
request(url,(error, response,html) => {
if (!error){
//console.log(html);
var $ = cheerio.load(html)
var imagesrc = $(".a-row center-align litb-on-click img").attr('src')
//download the image
download({
imgs: [
{
uri:imagesrc
}
],
dest:'./downloads'
})
.then((info) => {
console.log("Download Complete")
process.exit(1)
})
}
})
})
app.listen(5000)
Here, a-row center-align litb-on-click are classes
To select a class we need to use class-selector . (dot)
please try to update your imagesrc variable as below
var imagesrc = $(".a-row.center-align.litb-on-click img").attr('src');
Spaces are not compulsory.