Getting Gmail Inbox using node.js and google-api - javascript

My Code follows,(above code is same as given in the example of nodejs in google developer site.)
function listLabels(auth) {
var gmail = google.gmail({ auth: auth, version: 'v1' });
var emails = gmail.users.messages.list({
includeSpamTrash: false,
maxResults: 500,
q: "",
userId: 'me'
}, function (err, results) {
console.log(results.messages);
});
}
I'm getting array of objects containing IDs and threadIds
Now, if i input these IDs
into these
function getMessage(messageId,auth) {
var requestt = google.gmail({ auth: auth, version: 'v1' }).users.messages.get({
'userId': 'me',
'id': messageId
});
console.log(requestt)
requestt.execute(function(response){
console.log(response);
});
}
I am getting error,
TypeError: requestt.execute is not a function
at getMessage (/home/jay/Projects/gmailwebapi/index.js:122:11)
at /home/jay/Projects/gmailwebapi/index.js:113:7
at OAuth2Client._postRequest (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/lib/auth/oauth2client.js:381:3)
at postRequestCb (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/lib/auth/oauth2client.js:343:10)
at Request._callback (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/lib/transporters.js:103:7)
at Request.self.callback (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/node_modules/request/request.js:198:22)
at emitTwo (events.js:100:13)
at Request.emit (events.js:185:7)
at Request.<anonymous> (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/node_modules/request/request.js:1057:14)
at emitOne (events.js:95:20)

You could use the callback the same way you do when you list messages:
function getMessage(messageId, auth) {
var gmail = google.gmail({ auth: auth, version: 'v1' });
gmail.users.messages.get({
'userId': 'me',
'id': messageId
}, function (err, result) {
console.log(result);
});
}

Related

auth0 Management Api NextJs not able to update metadata

Really struggling to get my head around authO management clients so I can update users information. I've created a Next.js API route for the backend but I'm not sure how to actually amend the user's data. I've followed the docs and got to the point below.
API route
The ID params I manually entered to test and my response is an empty JSON object.
The docs don't make it clear what I'm suppose to do in the update user area in.
var ManagementClient = require("auth0").ManagementClient;
export default async (req, res) => {
var auth0 = new ManagementClient({
domain: process.env.AUTH0_BASE_URL,
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
scope: "read:users update:users",
});
var params = { id: "**************************" };
var metadata = {
foo: "bar",
};
auth0.users.updateAppMetadata(params, metadata, function (err, user) {
if (err) {
// Handle error.
}
// Updated user.
console.log(user);
res.status(200).json({ user });
});
};
Error:
API resolved without sending a response for /api/authapi, this may result in stalled requests.
SanitizedError [APIError]: getaddrinfo ENOTFOUND http
(node:internal/process/task_queues:81:21) {
statusCode: 'ENOTFOUND',
requestInfo: { method: 'post', url: '***********' },
originalError: Error: getaddrinfo ENOTFOUND http
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http',
response: undefined
}
}

How to fix '400 Bad request' in half of my request to Elastic search?

I'm using elastic search cloud with a single index that has a single document. I'm using #elastic/elasticsearch latest version. I'm calling elastic search from Firebase cloud functions.
Here is how my elastic client is initialized in cloud function
const { Client, errors } = require('#elastic/elasticsearch');
const elasticClient = new Client({
cloud: {
id: 'xxxxxxxx',
},
auth: {
username: 'xxxx',
password: 'xxxxxx'
},
maxRetries: 5,
requestTimeout: 60000,
});
Here is cloud function that queries the elastic search
exports.stickerSearch = functions.runWith(runtimeOpts).https.onRequest(async (req, res) => {
try {
const searchQuery = req.query.query;
const searchResult = await elasticClient.search(
{
index: "packs",
from: 0,
q: searchQuery,
size: 20,
sort: 'dataCreatedAt'
});
res.status(searchResult.statusCode).send(searchResult.body.hits);
}
catch (e) {
console.log("search error", e)
res.status(200).send({ "total": { "value": 0, "relation": "eq" }, "max_score": null, "hits": [] });
}
});
When I call this function via HTTP as GET requests with the same "query" param half of the function works as expected and return search results, another half just fails with the following error :
{ ResponseError: Response Error
at IncomingMessage.response.on (/srv/node_modules/#elastic/elasticsearch/lib/Transport.js:287:25)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickDomainCallback (internal/process/next_tick.js:219:9)
name: 'ResponseError',
meta:
{ body: '400 Bad Request',
statusCode: 400,
headers: { 'content-type': 'text/plain; charset=utf-8', connection: 'close' },
warnings: null,
meta: {
context: null,
request: [Object],
name: 'elasticsearch-js',
connection: [Object],
attempts: 0,
aborted: false
} } }
I have no idea why the same request fails sometimes.

JavaScript AWS Cognito Connection Problems "NetworkError"

I'm running into a strange problem with AWS Cognito. I'm able to create user accounts, however when I attempt to set the created user to a group it is
giving me a network timed out error.
Setup:
const AmazonCognitoIdentity = require('amazon-cognito-identity-js')
const AWS = require('aws-sdk')
const CognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({
region: 'us-east-1 ', // 100% sure this is the correct region
apiVersion: '2016-04-18'
})
const UserPoolId = config.cognito.userPoolId
const ClientId = config.cognito.clientId
const userPool = new AmazonCognitoIdentity.CognitoUserPool({ UserPoolId, ClientId })
Creating account:
userPool.signUp(email, password, [ emailAttribute ], null, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
CognitoIdentityServiceProvider.adminAddUserToGroup({
GroupName: 'TRIAL',
UserPoolId,
Username: email
}, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
res.redirect('/dashboard')
})
})
The account gets made correctly, however when attempting to add the new account to a group I get this error:
{ Error: connect ETIMEDOUT 104.239.207.44:443
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
message: 'connect ETIMEDOUT 104.239.207.44:443',
code: 'NetworkingError',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '104.239.207.44',
port: 443,
region: 'us-east-1 ',
hostname: 'cognito-idp.us-east-1',
retryable: true,
time: 2018-06-20T14:01:49.029Z }
I find this very strange as I just was able to create an account successfully.
Any ideas on why this is happening?
Thanks

SSL Error in nodejs request package

I'm trying to call freecodecamp api #url https://forum.freecodecamp.org/c/getting-a-developer-job.json?
I am doing some analysis on the data, but when I call this service using 'request' npm package I am getting ssl error as follows:
error { Error: write EPROTO 140735782093632:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1500:SSL alert number 40
140735782093632:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:659:
at _errnoException (util.js:1022:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:867:14) code: 'EPROTO', errno: 'EPROTO', syscall: 'write' }
Can somebody let me know what the issue is? A wget call pulls the data when provided with --ca-certificate option, also the webservice is giving data to postman without any certificate.
Here is my code:
import request from 'request';
import fs from 'fs';
const BASE_URL = 'forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1';
request.get(BASE_URL, {
port: 443,
agentOptions: {
ciphers: 'ALL',
ca: fs.readFileSync('./mycertfile.pem'),
secureProtocol: 'TLSv1_2_method'
},
strictSSL: false
})
.on('response', (response) => {
console.log('Response is ', response);
}).on('error', (err) => {
console.log('error', err);
});
I see no problems there except URI http:// is absent, in my environment i have node v10.5.0, and the slightly modified version of your script works well:
const request = require('request')
const BASE_URL = 'https://forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1'
request.get(BASE_URL, { json: true }, (err, res, body) => {
if (err) throw('error', err);
console.log('JSON object is => ', body);
})
outputs to console:
JSON object is => { users:
[ { id: 117390,
username: 'anthony2025',
....

No results from promise in Express Routing

I'm using NodeJS, Express and GoogleApis en Google-oauth-jwt to authenticate.
I'm having problems with getting data from my second promise function (getData).
I can succesfully retrieve a token, when I use res.json(myToken) in the getToken().then(function(myToken). However I'm having problems using this token in the getData(token) function.
When I'm finally able to retrieve data from the googleapis via the getData function,I'd like to save this data into a MongoDB, to reduce calls to the Google Analytics API.
These are the errors I get:
2018-01-11T09:46:55.063Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 token: XXXXXXXXXXXXXXX
2018-01-11T09:46:55.148Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 { Error:
Login Required at RequestError.Error (native) at new RequestError
(/var/task/node_modules/google-auth-library/lib/transporters.js:34:42)
at Request._callback
(/var/task/node_modules/google-auth-library/lib/transporters.js:96:27)
at Request.self.callback
(/var/task/node_modules/request/request.js:186:22) at emitTwo
(events.js:106:13) at Request.emit (events.js:191:7) at
Request.
(/var/task/node_modules/request/request.js:1163:10) at emitOne
(events.js:96:13) at Request.emit (events.js:188:7) at
IncomingMessage.
(/var/task/node_modules/request/request.js:1085:12) code: 401, errors:
[ { domain: 'global', reason: 'required', message: 'Login Required',
locationType: 'header', location: 'Authorization' } ] }
2018-01-11T09:46:55.153Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 (node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Login Required
This is my code:
var express = require('express');
var router = express.Router();
var googleAuth = require('google-oauth-jwt');
var google = require('googleapis');
var app = express();
/* get GA data*/
router.get('/kpis', function(req, res, next) {
// get token with googleapis library
function getToken() {
return new Promise(function(resolve,reject) {
googleAuth.authenticate({
email: 'serviceAcountemail#email.com',
key: "getting key",
scopes: ['https://www.googleapis.com/auth/analytics.readonly']
}, function (err, token) {
if (err){
reject(err)
} else
resolve(token)
});
});
}
function getData(token){
return new Promise(function(resolve,reject){
var analytics = google.analytics('v3');
var VIEW_ID = 'ga:profileid';
analytics.data.ga.get({
'auth': token,
'ids': VIEW_ID,
'metrics': 'ga:uniquePageviews',
'dimensions': 'ga:pagePath',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'sort': '-ga:uniquePageviews',
'max-results': 10,
}, function (err, response) {
if (err) {
console.log(err)
reject(err)
} else
console.log('Response:',response)
resolve(response)
});
});
}
getToken().then(function(myToken) {
// get the token, make a call to google analytics api with token included in auth
console.log('token:', myToken);
getData(myToken).then(function(results){
// show results on screen in json
res.json(gaResults);
});
});
});
/* end of get GA data*/
module.exports = router;
My question:

Categories

Resources