I want to fetch whole reply thread using the particular messageId something like this 2a2b0f84-261c-ecd5-33bf-919548b76000#hotmail.com.
I have tried this:
const getInbox = () => {
return new Promise((resolve, reject) => {
imaps.connect(config).then(function (connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = ['ALL'];
var fetchOptions = {
bodies: ['HEADER', 'TEXT', ''],
};
return connection.search(searchCriteria, fetchOptions).then(async function (messages) {
let promises = messages.map(item=>{
return new Promise((resolve,reject)=>{
var all = _.find(item.parts, { "which": "" })
var id = item.attributes.uid;
var idHeader = "Imap-Id: " + id + "\r\n";
simpleParser(idHeader + all.body, (err, mail) => {
resolve(mail);
});
});
});
Promise.all(promises).then(data=>{
let d = data.filter(obj=>obj.me).map(obj=>{
return {
from:obj.from.value.map(obj=>obj.address).join(','),
to:obj.to.value.map(obj=>obj.address).join(','),
subject:obj.subject,
attachments:obj.attachments,
message_id:obj.messageId,
date:obj.date
}
});
resolve(d);
})
});
});
});
}); }
I have tried this , it is returning whole inbox, I want particular message thread.
I tried this
var searchCriteria = [['HEADER','IN-REPLY-TO',messageId]];
it is working perfectly.
This line in your code means to search for all messages:
var searchCriteria = ['ALL'];
Really quite clear code, don't you agree? If you try something more like
var searchCriteria = ['OR HEADER "Message-ID" "' + id + '" HEADER "References" "' + id + '"'];
then you'll search for just the messages you want, and then you can retrieve their headers and bodies and do whatever you want.
Related
I am writing below code in Javascript to retrieve comment and navigating same page after repopulating the data
function MoveItem() {
var empId = document.getElementById('EMP_ID').value;
var commentValue = $("#RESPONSE").val();
if ($.trim(commentToSave).length > 0) {
showAjaxLoading();
var empData= "APPROVE";
var baseControllerUrl = '/Employee/EmpManagement/PushItem';
window.location.href = baseControllerUrl + "/" + empId + "?comment=" + commentValue + "&empData=" + empData + "¤tItem=" + itemData;
} else {
aet('Pelase enter comments', 'E');
}
}
In controller the method written as
[HttpGet]
public async Task<ActionResult> MoveItem(int id, string comment, string decision, string currentworkflow)
{
return RedirectToAction("EditEmpManagemnt", "EmpManagement", new { id = id });
}
I want to convert MoveItem action method to a [HttpPost] type and what all changes are needed in Javascript & action method ? Can anyone explain with a sample code.
You can send a POST request using the fetch method. We send the data with the JSON format. Replace your javascript with this:
function MoveItem() {
var empId = document.getElementById('EMP_ID').value;
var commentValue = $("#RESPONSE").val();
if ($.trim(commentToSave).length > 0) {
showAjaxLoading();
var empData = "APPROVE";
var baseControllerUrl = '/Employee/EmpManagement/PushItem';
var url = baseControllerUrl + "/" + empId;
//here we put the url as a first parameter
//then we configure the http method
//and in the body we pass in the object in JSON format
fetch(url, {
method: "POST",
body: JSON.stringify({
"comment": commentValue,
"empData": empData,
"currentItem": itemData
})
}).then(result => {
//do something with the result you get back
console.log("Completed with result: " + result);
}).catch(err => {
//if any error occured, then show it here
console.log("There is an error: " + err);
});
} else {
aet('Please enter comments', 'E');
}
}
And in your C# code just replace [HttpGet] attribute with [HttpPost]
I have a code snippet in db.js as below,
exports.asyncGetAllData = function (cb) {
connection.connect(function(err) {
connection.query("SELECT * FROM prices WHERE=" + "'" + ID + "'", function (err, result) {
//console.log("info:" + cb);
if (err) console.log("Error: " + err);
else
{
cb(result);
}
});
});
};
I want to pass and ID from app.js into asyncGetAllData function in db.js. The following code snippet is in app.js
app.get('/test/getPriceTrend/:parameter', function(req, res) {
console.log('SERVER::testGetPriceTrend');
console.log(req.url);
var str=req.url;
db_connection.asyncGetAllData(function(data) {
var obj = str.split("&");
var ID = obj[0].split("/")[3];
console.log(JSON.stringify(data));
res.setHeader('Accept', 'application/json');
res.writeHead(res.statusCode);
//The following piece of code will send information from the database
res.write("hello");
res.end();
});
});
In the above-mentioned code (app.js), I have parsed ID from a get request. I want to send this ID to asyncGetAllData function which resides in db.js. How can I send ID parameter and fetch the result?
Thanks in advance,
You can just extend the function with an additional argument
exports.asyncGetAllData = function (cb, ID) {
connection.connect(function(err) {
connection.query("SELECT * FROM prices WHERE=" + "'" + ID + "'" ...
And then pass it when you call the function in app.js
var str = req.url;
var obj = str.split("&");
var ID = obj[0].split("/")[3];
db_connection.asyncGetAllData(function(data) {
...
}, ID);
I have been trying to get the data from response and add it to controller, but no luck.
Here is my previous question.
How is it done in AngularJS?
The code that I used for this is like this:
invitePeersController.getGmailContacts = function(){
console.log("I come in gmail contacts");
var clientId = "contact key";
var apiKey = "apiKey";
var scopes = "https://www.googleapis.com/auth/contacts.readonly";
authorize();
function authorize() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
}
function handleAuthorization(authorizationResult){
invitePeersController.gmailContacts = [];
var gmailData = [];
if (authorizationResult && !authorizationResult.error){
var urlContact = "https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=50000&v=3.0";
var promiseGoogleData = HttpService.httpGetExternalLink(urlContact);
promiseGoogleData.then(function (response) {
var jsonChildData = response.data.feed.entry;
for(var i=0; i<jsonChildData.length ;i++){
var item = {};
try{
var name = jsonChildData[i].title.$t;
var email = jsonChildData[i].gd$email[0].address;
if(name.substring(1, name.length-1) && email.substring(1, email.length-1)){
item ["name"] = name.substring(1, name.length-1);
item ["email"] = email.substring(1, email.length-1);
item ["id"] = email.substring(1, email.length-1).replace(/[^a-zA-Z ]/g, "");
invitePeersController.gmailContacts.push(item);
gmailData.push(item);
}
}catch(error){
console.log("Error is thrown while trying to read gmail resposne");
}
}
$state.go("app.inviteContacts");
InvitePeersService.setGmailContactsData( invitePeersController.gmailContacts);
return response;
})
.catch(function (error) {
console.log("Something went terribly wrong while trying to get Gmail Data.");
});
}
}
}
Also don't forget to add the domain names in the credentials:
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am creating a weather app using Node.js to access the current weather.
When I call the openweatherapp API, the temperature variable retrieved through the JSON that I am trying to pass on to module.exports is nested within a series of closure functions.
Is there any way for me to access the temperature and pass it through module.exports so I can retrieve the data from another file?
var http = require('http')
const apiKey = "myAPIkey"
// Connect to API URL api.openweathermap.org/data/2.5/weather?q={city name}
function accessWeather(city, callback) {
var options = {
host: "api.openweathermap.org",
path: "/data/2.5/weather?q=" + city + "&appid=" + apiKey + "",
method: "GET"
}
var body = ""
var request = http.request(options, function(response) {
response.on('data', function(chunk) {
body += chunk.toString('utf8')
})
response.on('end', function() {
var json = JSON.parse(body)
var temperature = parseInt(json["main"]["temp"] - 273)
})
})
request.end()
}
temp = accessWeather("Calgary")
console.log(temp)
module.exports = {
accessWeather: accessWeather
}
Well here we have a misconception of how async works in JavaScript. You can't return data that are going to be loaded in the future.
There are few options to solve this.
1 ) Export a function that takes another function as a parameter and call that function when you resolve your data :
module.export = function accessWeather(city, callback) {
var options = {
host: "api.openweathermap.org",
path: "/data/2.5/weather?q=" + city + "&appid=" + apiKey + "",
method: "GET"
}
var body = ""
var request = http.request(options, function(response) {
response.on('data', function(chunk) {
body += chunk.toString('utf8')
})
response.on('end', function() {
var json = JSON.parse(body)
var temperature = parseInt(json["main"]["temp"] - 273);
callback(temperature);
})
})
request.end()
}
2 ) Because the callback style is legacy now, you can do something even better with Promises.
module.export = function accessWeather(city, callback) {
return new Promise(function(resolve, reject){
var options = {
host: "api.openweathermap.org",
path: "/data/2.5/weather?q=" + city + "&appid=" + apiKey + "",
method: "GET"
}
var body = ""
var request = http.request(options, function(response) {
response.on('data', function(chunk) {
body += chunk.toString('utf8')
})
response.on('end', function() {
var json = JSON.parse(body)
var temperature = parseInt(json["main"]["temp"] - 273);
resolve(temperature);
})
})
request.end()
});
}
You can use also ESNext features like Generators and what I prefer even more if using Observables.
I have been trying the code given in
How to use YQL to retrieve web results?
but it is not working.
Please suggest me something else or rectify that code.
I am just calling a function on page_load
<body onload = "load_content();">
In the load_content() method, I have to get the feed of other web site and display it on my HTML page.
Load_Content method
var query = "select * from html where url='http://www.imdb.com/title/tt0123865/'";
// Define your callback:
var callback = function(data) {
console.log("DATA : " + data);
};
// Instantiate with the query:
var firstFeedItem = new YQLQuery(query, callback);
// If you're ready then go:
console.log("FEED : " + firstFeedItem.fetch()); // Go!!
Function YQLQuery
function YQLQuery(query, callback)
{
this.query = query;
this.callback = callback || function(){};
this.fetch = function() {
if (!this.query || !this.callback) {
throw new Error('YQLQuery.fetch(): Parameters may be undefined');
}
var scriptEl = document.createElement('script'),
uid = 'yql' + +new Date(),
encodedQuery = encodeURIComponent(this.query.toLowerCase()),
instance = this;
YQLQuery[uid] = function(json) {
instance.callback(json);
delete YQLQuery[uid];
document.body.removeChild(scriptEl);
};
scriptEl.src = 'http://query.yahooapis.com/v1/public/yql?q='
+ encodedQuery + '&format=json&callback=YQLQuery.' + uid;
document.body.appendChild(scriptEl);
};
}
Nothing is coming in data variable
A simple get request is an answer to this.
$.get("http://www.imdb.com/title/tt1243957/",
function(data){
console.log(data);
}//end function(data)
);//end getJSON