Gmail-API Threads.list is not returning messages in the response - javascript

I'm trying to use the Gmail-API to get all the threads from a user and to have all of the messages in that thread by using threads.list. In the gmail documentation, it states that the following is the response from hitting this endpoint:
{
"threads": [
users.threads Resource
],
"nextPageToken": string,
"resultSizeEstimate": unsigned integer
}
I have a simple function to hit this endpoint
const {google} = require('googleapis');
/**
* Lists the threads in the user's account.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
export function listThreads(auth,fn) {
const gmail = google.gmail({version: 'v1', auth});
gmail.users.threads.list({
userId: 'me',
q: 'to:abc#abc.com '
}, (err, res) => {
if (err) throw 'The API returned an error: ' + err;
// fn is a callback used to return data to the handler since
// the res object is in the callback of thread.list
fn(res)
});
}
The following is what I get as a response (I replaced the actual email with abc and replaced my token for privacy):
{
"gmail": {
"config": {
"url": "https://www.googleapis.com/gmail/v1/users/me/threads?q=to%3Aabc%40abc.com",
"method": "GET",
"headers": {
"Accept-Encoding": "gzip",
"User-Agent": "google-api-nodejs-client/0.7.2 (gzip)",
"Authorization": "Bearer 123456",
"Accept": "application/json"
},
"params": {
"q": "to:abc#abc.com"
},
"responseType": "json"
},
"data": {
"threads": [
{
"id": "173bf0efdd1f1dc4",
"snippet": "Hello abc, Attached are the screenshots of my website for the requirements. Please send me an email with all of the information I'm asking for in the forms. For the colors, here is the site to",
"historyId": "4759550"
}
],
"resultSizeEstimate": 1
},
"headers": {
"alt-svc": "h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"",
"cache-control": "private",
"connection": "close",
"content-encoding": "gzip",
"content-type": "application/json; charset=UTF-8",
"date": "Thu, 20 Aug 2020 01:13:07 GMT",
"server": "ESF",
"transfer-encoding": "chunked",
"vary": "Origin, X-Origin, Referer",
"x-content-type-options": "nosniff",
"x-frame-options": "SAMEORIGIN",
"x-xss-protection": "0"
},
"status": 200,
"statusText": "OK"
}
}
As you can see, the messages property of res.data.threads is completely missing. I would appreciate any guidance.
Thank You

In this case, in order to retrieve all messages from each thread, it is required to use the method of "Users.threads: get". When your script is modified, it becomes as follows.
Modified script:
const gmail = google.gmail({version: 'v1', auth});
gmail.users.threads.list(
{
userId: "me",
q: "to:abc#abc.com ",
},
(err, res) => {
if (err) throw "The API returned an error: " + err;
Promise.all(
res.data.threads.map(({ id }) => {
return new Promise((resolve, reject) => {
gmail.users.threads.get({ userId: "me", id }, (err, res) => {
if (err) rejects(err);
resolve(res.data);
});
});
})
).then((res) => {
fn(res);
});
}
);
Note:
In this modified script, it supposes that you have already been able to retrieve the email using Gmail API.
References:
-Users.threads: list
-Users.threads: get

Related

How to POST a request using data from console.log in the URL

I am receiving a response code which I receive as follows:
function(res) {
console.log("Response from the authorize call:")
console.log(res)
The console.log(res) returns the following:
approved: true
​
authorization_token: "sometoken"
​
finalize_required: false
​
show_form: true
I want to use the authorization_token to send a POST request I have tried the following:
function(res) {
console.log("Response from the authorize call:")
console.log(res)
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Basic mypw-usn");
var raw = JSON.stringify({
"intent": "buy",
"purchase_country": "GB",
"purchase_currency": "GBP",
"locale": "en-GB",
"order_amount": 10,
"order_tax_amount": 0,
"order_lines": [{
"type": "physical",
"reference": "19-402",
"name": "Battery Power Pack",
"quantity": 1,
"unit_price": 10,
"tax_rate": 0,
"total_amount": 10,
"total_tax_amount": 0
}],
"merchant_urls": {
"confirmation": "http://localhost:8888/jcart/mypage1.php",
"authorization": "http://localhost:8888/jcart/mypag1e.php"
}
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://api.example//payments/v1/authorizations/res.authorization_token/order", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
The error I get is TypeError: NetworkError when attempting to fetch resource.
I think I am not showing the res.authorization_token correctly in the fetch url, however I do not know how to do this correctly.
Any help welcome

Lambda Times Out Writing to DynamoDB

I have a simple function that puts an item into the database. I have enabled a role that has a policy attached to allow puts for this table.
Here is the code below. I have even tired hard coding all the information still it times out. I have also tried increasing the timeout to 30 seconds and the Memory to 512 MB but it still just times out. any help would be greatly appreciated.
const AWS = require(`aws-sdk`);
AWS.config.update({region: `eu-east-2`});
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.handler = function(event, context, callback){
var TableName ="MyFirstExamAnswers";
var Item = {};
Item["Student"] = event.params.Student;
Item[event.params.Question] = event.params.Answer;
console.log("theItem: "+ JSON.stringify( Item));
dynamo.put({TableName,Item}, function (err, data) {
if (err) {
console.log(`error`, err);
callback(err, null);
} else {
var response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Methods': `GET,POST,OPTIONS`,
'Access-Control-Allow-Origin': `*`,
'Access-Control-Allow-Credentials': `true`
},
body: JSON.stringify(data),
isBase64Encoded: false
};
console.log(`success: returned ${data.Item}`);
callback(null, response);
}
});
};
With the following policy attached to the role that the Lambda is running under
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowDBAccess2Lambda001",
"Effect": "Allow",
"Action": [
"dynamodb:PutItem"
],
"Resource": "arn:aws:dynamodb:us-east-2:MyAccountNumber:table/MyFirstExamAnswers"
}
]
}

Expressjs Post-request is not getting recognized | 404-Error

I want to implement paypal to my website, but I am stuck with this. Always when I try to do a post request (also tried with postman), I dont get an answer which is just the normal 404 error-page. The console is showing no error, so I guess the post request is not getting recognized.
What could be the problem and how can I fix it?
server.js
//payment
app.post("/pay", (req, res) => {
// payment data
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/success",
"cancel_url": "http://localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "product1",
"sku": "001",
"price": "350.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "350.00"
},
"description": "test"
}]
};
// create payment
paypal.payment.create(create_payment_json, (error, payment) => {
if(error) {
console.log("payment not successful");
console.log(error)
} else {
console.log("payment successful");
console.log(payment);
}
})
})
products.ejs
<form action="/pay" method="post">
<input type="submit" value="add to cart" onclick="window.location.href='/pay'"/>
</form>
Couple of things you need to make sure
Make sure you are sending the post request to the correct port, just incase your express server isn't hosting the actual site as well. If it is then don't worry about the port
You can use js to send the request to prevent the page from refreshing.
const form = document.querySelector('form')
form.addEventListener('submit', async function(e) {
e.preventDefault()
const port = 3000 //make sure this is the port your express erver is listening on
const formData = new FormData(e.target)
const itemId = formData.get('itemId')// You can store the items id in the name attribute of an input
const response = await fetch(`http://localhost:${port}/pay`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({itemId})
})
})
const data = await response.json()
console.log(data) // The response you would get from the server

Slack interactive message getting invalid_payload for response_url sent back

I've been doing some work with the Slack API and with their
interactive messages
I post a message with the interactive message attachment here:
export const postMessage = (msg, channel) => {
request({
method: 'POST',
uri: 'https://slack.com/api/chat.postMessage',
headers: {
'content-type': 'application/json;charset=UTF-8',
Authorization: `Bearer ${process.env.SLACKTOKEN}`,
},
body: JSON.stringify({
token: process.env.SLACKTOKEN,
attachments: [
{
"text": "",
"fallback": "If you could read this message, you'd be choosing something fun to do right now.",
"color": "#3AA3E3",
"attachment_type": "default",
"callback_id": "command_selection",
"actions": [
{
"name": "command_list",
"text": "Choose a command",
"type": "select",
"options": [
{
"text": "Register Team",
"value": "registerTeam"
},
{
"text": "Edit Team",
"value": "editTeam"
},
{
"text": "Get By Url",
"value": "getByUrl"
},
{
"text": "Report Issue",
"value": "reportIssue"
},
{
"text": "Find Team",
"value": "findTeam"
},
{
"text": "List Teams",
"value": "listTeams"
}
]
}
]
}
],
text: msg,
channel,
as_user: true,
})
}, (err, res, body) => {
if (err) {
console.log('error posting msg: ', err);
} else {
console.log('post message to channel: ', body);
}
})
}
Slack then sends a POST request to this URL with a response_url parameter in their payload. This is where I'm getting the payload from in my code:
api.post('/interactivity', (req, res) => {
const { body } = req;
const { payload } = body;
const parsedPayload = JSON.parse(payload)
res.send(parsedPayload.response_url)
var message = {
"text": payload.user.name+" clicked: "+payload.actions[0].name,
"replace_original": false,
}
util.sendMessageToSlackResponseURL(parsedPayload.response_url, message)
})
export const sendMessageToSlackResponseURL = (responseURL, JSONmessage) => {
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'content-type': 'application/json'
},
json: JSONmessage
}
request(postOptions, (error, res, body) => {
if (error){
console.log(error)
} else {
console.log('post message to channel: ', body);
}
})
}
For some reason though, the response_url is giving an invalid_payload error when I click on the link and I can't figure out if its the payload I'm sending in the original message I posted or something's up with the POST request that Slack sent
The issue is with utility method on line json: JSONmessage which should be body: JSONmessage
Updated code,
export const sendMessageToSlackResponseURL = (responseURL, JSONmessage) => {
var postOptions = {
uri: responseURL,
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSONmessage
}
request(postOptions, (error, res, body) => {
if (error){
console.log(error)
} else {
console.log('post message to channel: ', body);
}
})
}
Hope this works!

FCM data messages doesn't load in firefox

I am working on cloud messaging using Web FCM. When I send a notification with title and body, both firefox and chrome shows notification and works fine. But when I trying to send FCM Data Message, firefox doesn't receive and log Messages.
I am using a HTTPS secure url and also this template.
This is my javascript function:
function sendMSG()
{
var _ID = $("#user_id").val();
var ServerKey = "SERVER_KEY";
var msg = {
"to": _ID,
"data": {
"Nick": "Mario",
"body": "great match!",
"Room": "PortugalVSDenmark"
}
}
;
$.ajax({
type: 'POST',
url: "https://fcm.googleapis.com/fcm/send",
headers: {
Authorization: 'key=' + ServerKey
},
contentType: "application/json",
data: JSON.stringify(msg),
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
console.log(xhr.error);
}
});
}
And my service worker:
importScripts('/script/firebase.js');
importScripts('/script/firebase-app.js');
importScripts('/script/firebase-messaging.js');
firebase.initializeApp({ 'messagingSenderId': 'MY_ID' });
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
console.log('FIREBASE call', payload);
if (payload.data.status == 'calling') {
channel.postMessage(payload.data)
return self.registration.showNotification('Nuevo pedido', { body: "Llamada para transporte de un pedido" })
}
})
chrome responses message in console like this:
But there is no any response from firefox.
Can anyone help me to solve this issue?
finally i found where is the problem:
the contentType must be placed in the headers brackets like this:
headers: {
'Content-Type': 'application/json',
Authorization: 'key=' + ServerKey
},
now, all functions works fine in firefox

Categories

Resources