How to change order of mail folders? - javascript

I have this function for getting user folders.
function getUserFolders(callback) {
getAccessToken(function(accessToken) {
if (accessToken) {
// Create a Graph client
var client = MicrosoftGraph.Client.init({
authProvider: done => {
// Just return the token
done(null, accessToken);
}
});
// Get all folders
client
.api("/me/MailFolders")
.orderby("")
.get((err, res) => {
if (err) {
callback(null, err);
} else {
callback(res.value);
}
});
console.log(client);
} else {
var error = { responseText: "Could not retrieve access token" };
callback(null, error);
}
});
}
When I get a response back, the order of folders is:
I have read documentation and couldn't find how to change order of folders. The order i would like to have is the same one as on outlook. Thank you for your help!!

You cannot retrieve folders in the order a user organized them in a given client.
I'm also not sure what you expect to get from .orderby(""). Unless you provide a field to order by, it won't know how you want to sort them.

Related

Create route Express.js and MySql

I am playing with Express.js and MySQL. I am trying to create a route in order to display data via API.
In my database, I have a price field and I am trying to display all properties in the a price range. 
SELECT * FROM properties
WHERE price BETWEEN 10000 AND 20000;
In my model.js file I set up like this:
Property.findBy = (valueMin, valueMax, result) => {
sql.query(`SELECT * FROM properties WHERE price BETWEEN ${valueMin} AND ${valueMax}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("No price: ", res[0]);
result(null, res[0]);
return;
}
result({ kind: "range" }, null);
});
};
In my controller.js file
exports.findMaxi = (req, res) => {
Property.findBy(req.params.valueMin, req.params.valueMax, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found property for range ${req.params.valueMin} and ${req.params.valueMax}`
});
} else {
res.status(500).send({
message: "Error found property for range " + req.params.valueMin + req.params.valueMax
});
}
} else res.send(data);
});
};
And finally, my routes:
app.get("/properties/:valueMin&valueMax", propertis.findMaxi);
This route doesn’t work. I don’t know how to solve this problem. Can someone offer assistance?
I think it's because your route is like
app.get("/properties/:valueMin&valueMax", propertis.findMaxi);
you'll only be able to pass 1 value and the other is the string "&valueMax", so you can't change the value of valueMax... for example, if you want to have valueMin = 100, the query is like GET /properties/100&valueMax.
So, each value you want to pass in this way, use ':' before each variable, like
app.get("/properties/:valueMin&:valueMax", propertis.findMaxi);
and a query like //GET /properties/100&200 will work
But I think it's better to pass the variables as query params GET /properties?min=100&max=200
You most likely want to pass min and max as query parameters.
// GET /properties?min=10000&max=20000
console.log(req.query.min) // => '10000'
console.log(req.query.max) // => '20000'
The way you did is that you have one value that you can access with req.params and it is valueMin&valueMax (I don't think it is even valid to have a variable that contains & character).
You could have a route like /properties/:min/:max to access those two separately, or just use query parameters which is made for that purpose

SQLITE_MISUSE: bad parameter or other API misuse [duplicate]

I've searched on how to create a sqlite3 database with a callback in Node.js and have not been able to find any links. Can someone point me towards documentation or provide a 2-3 line code sample to achieve the following:
Create a sqlite3 database and catch an error if the creation fails for any reason.
Here is what I've tried:
let dbCreate = new sqlite3.Database("./user1.db", sqlite3.OPEN_CREATE, function(err){
if(!err){
logger.infoLog("Successfully created DB file: " + dbFileForUser + " for user: " + username );
} else {
logger.infoLog("Failed to create DB file: " + dbFileForUser + ". Error: " + err );
}
});
dbHandler[username] = dbCreate;
When I execute this, I get the following error:
"Failed to create DB file: ./database/user1.db. Error: Error: SQLITE_MISUSE: bad parameter or other API misuse"
This call without callback works just fine.
var customDB = new sqlite3.Database("./custom.db", sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
But in this, I will not know if I run into any errors while creating the Database.
Try this:
let userDB = new sqlite3.Database("./user1.db",
sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
(err) => {
// do your thing
});
Example.
#Irvin is correct, we can have a look at http://www.sqlitetutorial.net/sqlite-nodejs/connect/ and
check it says if you skip the 2nd parameter, it takes default value as sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
and in this case if database does not exist new database will be created with connection.
sqlite3.OPEN_READWRITE: It is to open database connection and perform read and write operation.
sqlite3.OPEN_CREATE : It is to create database (if it does not exist) and open connection.
So here is the first way where you have to skip the 2nd parameter and close the problem without an extra effort.
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.|');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});
And this is the 2nd way to connect with database (already answered by #Irvin).
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});

Promise either never get called, or is rejected (Parse JS SDK)

I am trying to write a function that add or edit some fields on a User object.
The problem come when I try to save the user, if I use user.save, the Promise is rejected with error 206 UserCannotBeAlteredWithoutSessionError.
However, if I get the session id (and documentation about that is scarce), the promise never get resolve, nor rejected. The app seems to just jump to the callback.
My function:
function update(user, callback) {
let query = new Parse.Query(Parse.User);
query.equalTo("username", user.email);
query.find().then(
(users) => {
if(users.length === 0) {
callback('Non existent user');
} else {
let user = users[0];
// user.set('some', 'thing');
console.log('save');
user.save(/*{
sessionToken: user.getSessionToken()
}*/).then(
(test) => {
console.log('OK - ' + test);
callback();
}, (err) => {
console.log('ERR- ' + require('util').inspect(err));
// console.log(callback.toString());
callback(error.message);
}
);
}
},
(error) => {
callback(error.message);
}
);
}
Called with:
var async = require('async'),
baas = require('./baas.js');
async.waterfall([
(callback) => {
callback(null, {
email: 'user#test.com',
password: 'password'
});
},
(user, callback) => {
console.log('connect');
baas.connect(() => { //Initialize the connection to Parse, and declare use of masterKey
callback(null, user);
});
},
(user, callback) => {
console.log('update');
baas.update(user, (err) => {
callback(err);
});
}
], (err) => {
console.log('Error: ' + err);
});
The logs become:
Without session token:
connect
update
save
ERR- ParseError { code: 206, message: 'cannot modify user sA20iPbC1i' }
With session token:
connect
update
save
I do not understand how it is possible that the promise just callback without printing anything, nor why no error are raised anywhere.
Edit:
Following #user866762 advice, I tried to replace the query with Parse.User.logIn and use the resulting User object.
While this solution give me a sessionToken, the end result is the same, parse crash if I don t provide the session token, or give me a error if I do.
According to the Parse Dev guide:
...you are not able to invoke any of the save or delete methods unless the Parse.User was obtained using an authenticated method, like logIn or signUp.
You might also try becoming the user before saving, but I have my doubts that will work.
When you're "get[ting] the session id" my guess is that you're really breaking something. Either Parse is having a heart attack at you asking for the session token, or when you're passing it in save you're causing something there to explode.

Async confusion in nodejs function

I always have multiple operations in one route or endpoint. Take an example below, when a user deletes an item, I want the related file be deleted in s3 too besides deleting related collection from the database.
So is the code below ok? Does it matter if I put the first function (delete file from s3) inside the DeleteItem function?
router.post('/item/delete', function(req, res) {
if(req.body.dlt_item){
var tempArray = [];
tempArray.push({"Key":req.body.dlt_item});
s3Bucket.deleteObjects({
Bucket: 'myS3',
Delete: {
Objects: req.body.dlt_item
}
}, function(err, data) {
if (err)
return console.log(err);
});
}
Item.DeleteItem(req.body.item_id, function(err,result){
if(err){console.log(err)}
res.send({result:1});
})
});
You should organise your code like this. This will ensure that s3 deletion will start only when mongodb deletion has finished.
In your code both things happen simultaneously. this may cause issue in some cases.
If one fails and other succeeds then there will be trouble. Suppose s3 files get deleted successfully and mongo deletion fails. Then you will have many references to non existing resources.
router.post('/item/delete', function(req, res) {
if(req.body.dlt_item){
var tempArray = [];
tempArray.push({"Key":req.body.dlt_item});
Item.DeleteItem(req.body.item_id, function(err,result){
if(err)
{
console.log(err)
res.send(err);
}
else
{
//deletion from mongodb is succesful now delete from s3
s3Bucket.deleteObjects({
Bucket: 'myS3',
Delete: {
Objects: req.body.dlt_item
}
},function(err, data) {
if (err)
{
// deletion from s3 failed you should handle this case
res.send({result:1});
return console.log(err);
}
else
{
// successful deletion from both s3 and mongo.
// If you do not want to wait for this then send the response before this function.
res.send({result:1});
}
});
}
})
});

AWS Cognito - offline data availability

I am building a phonegap app and use AWS Cognito to store the User data. In the description of Cognito, it is said, that the data is offline available. This does not work in my code:
var add_data;
function getCognitoData(){
var params = {
IdentityPoolId: COGNITO_IDENTITY_POOL_ID,
Logins: {
'graph.facebook.com': FACEBOOK_TOKEN
}
};
AWS.config.region = AWS_REGION;
AWS.config.credentials = new AWS.CognitoIdentityCredentials(params);
AWS.config.credentials.get(function(err) {
if (err) {
console.log("Error: "+err);
return;
}
console.log("Cognito Identity Id: " + AWS.config.credentials.identityId);
var syncClient = new AWS.CognitoSyncManager();
syncClient.openOrCreateDataset('myDataset', function(err, dataset) {
dataset.get('myKey', function(err, value) {
console.log(value, err);
});
add_data = function(thisid, thisval) {
dataset.put(thisid, thisval, function(err, record){
dataset.synchronize({
onSuccess: function(data, newRecords) {
console.log("success", newRecords);
},
onFailure: function(err) {
console.log("error", err);
},
onConflict: function(dataset, conflicts, callback) {
console.log("sync conflict", dataset, conflicts);
var resolved = [];
for (var i=0; i<conflicts.length; i++) {
resolved.push(conflicts[i].resolveWithRemoteRecord());
}
dataset.resolve(resolved, function() {
return callback(true);
});
}
});
});
}
});
});
}
The AWS Credentials for the Identity Pool and the Facebook Token are previously set, and work in the online mode, but I don't get the dataset data, when being offline.
Am I doing something wrong or is it generally not possible to get the Cognito Dataset data while being offline? I read, that the data is actually being held in the local storage.
I am using the current AWS SKD (Release v2.1.42) and the Amazon Cognito JS.
It's possible to get the data offline. You need to synchronize the dataset to get whatever contents may be inside, otherwise them being empty is expected. Are you doing that? If not, try doing that, but if so, can you update your code above?
There was a bug with the aws-sdk-js causing the offline bug. CognitoSync depends on aws-sdk-js. Should be working now as of aws-sdk-js#2.7.21. Make sure you update.

Categories

Resources