I'm using the node.js SDK to create and send invoices on sandbox. The first 8-15ish creations and 0-2 sends return this error:
The requested resource (/v1/invoicing/invoices/) is not available.
It's not the JSON being sent, as sometimes an invoice goes through and sometimes it doesn't. I'm wondering if this is a sandbox issue (API is rate-limited in some manner), or if there's some initialization I should be doing before hand?
Roughly, here's my code:
paypal.configure ...
program // Commander
.parse(process.argv)
.args.forEach(function (arg) {
fs.createReadStream(arg).pipe(
parse({ columns: true, delimiter: '\t' }, function (error, data) {
data.forEach(function (row) {
// create invoice from each row in data
var invoice = ...
invoice
.setShipping()
.then(
function (invoice) {
return new Promise(function (resolve, reject) {
paypal.invoice.create(invoice, function (error, invoice) {
if (null === error) {
resolve(invoice);
} else {
reject(error);
}
});
});
}
)
.then(
function (invoice) {
paypal.invoice.send( invoice.id, function (error, invoice) {
});
}
);
})
})
);
});
I ended up running this on PayPal live and didn't run in to the issue above. My best guess is it's some sort of limiting on Sandbox.
Related
iv been setting up a lambda instance, it grabs data from a few different services and then its meant to update a custom Cognito attribute for that user, that works correctly and i get the return response "{}" along and no errors so im assuming that means its working correctly, however when i check the users attributes its not returning anything?
i have triple checked that the app clients have read and write permissions, so i have no idea whats happening, everything, as far as i can tell, is working, just that the attribute isnt changing.
return new Promise((resolve, reject) => {
console.log("TestInside");
// setTimeout(function() {
console.log("TimeoutFunction");
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
var params = {
UserAttributes: [
{
Name: 'locale',
Value: UserFarms
},
],
UserPoolId: 'UserPoolID',
Username: UserName
};
console.log("Executing call");
const cognitoD = cognitoidentityserviceprovider.adminUpdateUserAttributes(params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
//passon = err.message;
resolve('Error');
}
else {
// cognitodata = data;
console.log('Returned positive cognito admin update');
//UserName = data.Username;
//passon = data;
console.log(data);
resolve(data);
}
}).promise();
whats wrong, am i missing somthing really simple?
I am making a node.js application and part of my code requests for data from 193 different urls to download the json data from each url. Here is one of those urls: https://www.gemeentegeschiedenis.nl/gemeentenaam/json/Apeldoorn For the some the downloaded json data is fine and is complete. However towards the end, corruptions happen for some of the files. Part of the data becomes nullified and then there are some that have database errors. I think it has to do with requesting data from so many urls in a short amount of time (which is why I tried the "setTimeout" function (but that doesn't really work)).
function writeToFile(url) {
// get name to make each new file unique
var name = url.split("json/")[1];
var fileStream = fs.createWriteStream(`jsonFiles/${name}.json`);
var options = {
url: `${url}`,
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
json: true
}
}
//request the data from the site and download to the file.
request.get(options).pipe(fileStream);
}
function getMunicipalityGeoJsonData(req, res) {
//Get all the urls pointing to the JSON data for the province, Gelderland
getGelderlandJsonUrls((err, jsonUrls) => {
//for all those urls, write the data to files.
for (url of jsonUrls) {
console.log(url);
writeToFile(url);
}
})
}
function getGelderlandJsonUrls(callback) {
getMunicipalityJsonUrls("Gelderland", (err, data) => {
jsonUrls = data;
callback(null, jsonUrls);
});
}
function getMunicipalityJsonUrls(provinceName, callback) {
request({ uri: `https://www.gemeentegeschiedenis.nl/provincie/json/${provinceName}` }, (error, response, body) => {
body = JSON.parse(body);
// extracting each json URL from all the municipalities in Gelderland
var jsonUrls = [];
var numberMun = body.length;
for (var i = 0; i < numberMun; i++) {
var url = body[i].uri.naam;
var urlSplit = url.split("gemeentenaam");
var jsonUrl = urlSplit[0] + "gemeentenaam/json" + urlSplit[1];
jsonUrl = jsonUrl.replace("http://", "https://");
jsonUrls.push(jsonUrl);
}
callback(null, jsonUrls);
});
}
The last json data downloaded into the file as an html page with a database error from the url: https://www.gemeentegeschiedenis.nl/gemeentenaam/json/Zutphen which actually just took just under 6 seconds to load up looking at the network tab on Chrome
the 1812 has null for its properties when it should have a bunch of coordinates https://www.gemeentegeschiedenis.nl/gemeentenaam/json/Winssen (took just over a second to load on chrome
I am a noob at node, but please help me fix this issue maybe with some sort of checking if the data is corrupted or something. Thanks for the help in advanced:)
EDIT: I am trying to do up to 200 urls at a time in the for loop.
First off, add proper error handling to getMunicipalityJsonUrls() and to getGelderlandJsonUrls(). This means:
Check err parameter everywhere it's present and propagate the error back to the caller.
Capture possible errors from JSON.parse()
Check http statusCode.
Here's that fixed up code:
function getMunicipalityJsonUrls(provinceName, callback) {
request({ uri: `https://www.gemeentegeschiedenis.nl/provincie/json/${provinceName}` }, (error, response, body) => {
if (err) {
callback(err);
return;
}
if (response.statusCode !== 200) {
callback(new Error(`http status code ${response.statusCode}`));
return;
}
try {
const jsonUrls = JSON.parse(body).map(url => {
let urlSplit = url.split("gemeentenaam");
let jsonUrl = urlSplit[0] + "gemeentenaam/json" + urlSplit[1];
return jsonUrl.replace("http://", "https://");
});
callback(null, jsonUrls);
} catch(e) {
callback(e);
}
});
}
function getGelderlandJsonUrls(callback) {
getMunicipalityJsonUrls("Gelderland", (err, data) => {
if (err) {
callback(err);
} else {
callback(null, data);
}
});
}
Then, in writeToFile(), add error handling and completion monitoring and I chose to wrap it in a promise rather than a plain callback because I want to use it with some utilities that work with promises.
function writeToFile(url) {
return new Promise((resolve, reject) => {
// get name to make each new file unique
var name = url.split("json/")[1];
var fileStream = fs.createWriteStream(`jsonFiles/${name}.json`);
fileStream.on('error', (e) => {
reject(e);
});
var options = {
url: `${url}`,
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
json: true
}
}
//request the data from the site and download to the file.
request.get(options).pipe(fileStream).on('error', (e) => {
reject(e);
}).on('finish', () => {
resolve(url);
});
});
}
Now, we need to decide how to loop through all the URLs. If any of the urls could ever be attempting to write to the same file (if that's even a remote possibility), then you have to serialize the URLs to prevent them from ever having more than one asynchronous operation trying to write to the same file at the same time because that will just mess up that file. So, if that was the case, you could serialize the writing to the file like this:
// option 1 - serialize writing to files
async function getMunicipalityGeoJsonData(req, res) {
//Get all the urls pointing to the JSON data for the province, Gelderland
getGelderlandJsonUrls((err, jsonUrls) => {
if (err) {
console.log(err);
res.sendStatus(500);
} else {
try {
//for all those urls, write the data to files.
for (url of jsonUrls) {
console.log(url);
await writeToFile(url);
}
res.send("All done");
} catch(e) {
console.log(e);
res.sendStatus(500);
}
}
});
}
If you are absolutely sure that none of these URLs will ever cause writing to the same file, then you can run N of them at a time where you determine what the lowest value of N is that gets you decent performance. Higher values of N consume more peak resources (memory and file handles). Lower values of N run less things in parallel. If the target hostnames are all the same server, then usually you don't want N to be more than about 5. If the target hosts you are retrieving data from are all different, you can experiment with values of N up to maybe 20.
// option 2 - run N at a time in parallel
function getMunicipalityGeoJsonData(req, res) {
//Get all the urls pointing to the JSON data for the province, Gelderland
getGelderlandJsonUrls((err, jsonUrls) => {
if (err) {
console.log(err);
res.sendStatus(500);
} else {
//for all those urls, write the data to files.
const numConcurrent = 5;
mapConcurrent(jsonUrls, numConcurrent, writeToFile).then(() => {
res.send("All done");
}).catch(err => {
console.log(err);
res.sendStatus(500);
});
}
})
}
The mapConcurrent() function comes from this answer Promise.all consumes all my RAM and is as follows. It expects you to pass it an array of items to be iterated over, the max you want in flight at the same time and a function that will be passed an array item and will return a promise connected to when it's done or has an error:
function mapConcurrent(items, maxConcurrent, fn) {
let index = 0;
let inFlightCntr = 0;
let doneCntr = 0;
let results = new Array(items.length);
let stop = false;
return new Promise(function(resolve, reject) {
function runNext() {
let i = index;
++inFlightCntr;
fn(items[index], index++).then(function(val) {
++doneCntr;
--inFlightCntr;
results[i] = val;
run();
}, function(err) {
// set flag so we don't launch any more requests
stop = true;
reject(err);
});
}
function run() {
// launch as many as we're allowed to
while (!stop && inflightCntr < maxConcurrent && index < items.length) {
runNext();
}
// if all are done, then resolve parent promise with results
if (doneCntr === items.length) {
resolve(results);
}
}
run();
});
}
There are comparable functions in Bluebird's Promise.map() and in the Async library.
So, using this code you now have the ability to control how many of your requests/writeToFile() operations are in-process at the same time and you are capturing and logging all possible errors. Do, you can tune how many can be in flight at the same time for best performance and lowest resource use and, if there are any errors, you should be logging those errors so you can debug.
This code is currently set to stop processing any further URLs if it gets an error. You can change that if you want to continue on to the other URLs if you get an error by tweaking mapConcurrent(). But, I would still make sure you log any errors so you know when there are errors and can investigate why you are seeing errors.
One other note. If this was my code, I would convert everything to promises (no plain callbacks) and I'd use the got() library instead of the now deprecated request() library. I don't write any new code using the request() library.
I am building a MERN stack social media application. On the application, a user can have a profile with posts which can either be a photo or a video.
My photos are stored in the posts collection, however, videos are stored in a collection named media.
When the user wants to view their posts, I have a function that gets all data from both collections, sorts them by their date of creation and returns them to the frontend. This has been working fine until the user builds up a large number of photos/videos, and now MongoDB won't allow that user to make the request anymore as it takes too much RAM.
I want to implement a lazy-load onto this so I'm not requesting all this data that the user doesn't even need, and I know how to do this using a single collection, however, I'm not sure how I would go about doing it when using two collections.
I know I would limit each collection to 2 objects at one time and add a skip to each to request the next two objects, but I don't know how to keep track of which needs to come next, a photo or a video?
My current code:
//First function, called by route
const listPostAndMediaByUser = (req, res) => {
sortMediaAndPosts(req)
.then(function(postsAndMedia) {
return res.json(postsAndMedia);
})
.catch(function(error) {
console.log("Error getting posts", error)
return res.status(400).json({
error: errorHandler.getErrorMessage(error)
});
});
};
//Sorting function
//This function runs getPosts, and getMedia
//And sorts them by their creation date
const sortMediaAndPosts = function(req) {
return new Promise(async function(resolve, reject) {
let postsAndMedia = [];
try {
const posts = await getPosts(req);
const media = await getMedia(req);
postsAndMedia = [...posts, ...media].sort(
(a, b) => new Date(b.created) - new Date(a.created)
);
} catch (error) {
console.log('Error: ', error);
reject(error);
}
resolve(postsAndMedia);
});
};
//Get posts function
const getPosts = function(req) {
return new Promise(async function(resolve, reject) {
try {
Post.find({ postedBy: req.profile._id })
.limit(2)
.select('-photo')
.populate('postedBy', '_id name')
.populate('comments.postedBy', '_id name')
.sort('-created')
.exec((err, posts) => {
if (err) reject(err);
else resolve(posts);
});
} catch(e) {
console.log('error!', e)
reject(e);
}
});
};
//Get Media function
const getMedia = function (req) {
return new Promise(async function(resolve, reject) {
Media.find({postedBy: req.profile._id})
.limit(2)
.populate('postedBy', '_id name')
.populate('comments.postedBy', '_id name')
.sort('-created')
.exec((err, media) => {
if(err) reject(err)
else resolve(media)
})
})
}
Any input would be greatly appreciated.
Thanks
Your schemas for Post and Media look very similar. You should consider merging them into a single schema. This would resolve your problem.
If you don't want to change your schema you should look into the mongodb aggregation pipeline which allows you to join data from multiple collections (using $lookup).
I want to buy one phone number from Twilio which has the same area code as a customer. When I run the code below, sometimes several numbers are purchased instead. This is not ideal as it runs up my costs.
exports.buy_twilio_phone_number = function () {
prefix = "+1415";
return new Promise (function (resolve, reject) {
client.availablePhoneNumbers ('US')
.local.list ({
contains: prefix
})
.then (function (data) {
if (data == undefined || data.length == 0) {
reject (new Error ("couldn't get a phone number"));
} else {
client.incomingPhoneNumbers.create (
{
phoneNumber: data[0].phoneNumber,
}).then (function (new_twilio_number) {
console.log ("new twilio number purchased " + JSON.stringify (new_twilio_number));
resolve ( new_twilio_number);
}).catch(function(error){
console.log ("could not get the number error");
reject (new Error ("could not add phone number"));
});
} // end else
}); // end then
}); // end Promise
} // end function
The function to purchase twilio number is called from a post request (after the user creates an account and hits the submit button). This is the gist of the code.
exports.editPatientPost = function (req,res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields){
// process user's account
buy_twilio_phone_number ()
.then(function (twilio_number) {
if (err) console.log (err);
updateUserWithTwilioNumber (twilio_number, function (err, user) {
if (err) console.log (err);
return res.redirect (303, /'account_created');
});
}) // end then
}) // end form parse
} // end function
I think .local.list is the problem where it calls the .then more than once. How can I ensure only one phone number is purchased?
I am work with isntagram api in node js. i have one array and in the array store above 20k up instagram id. and then i am do foreach on that array and one by one take instagram id and go for the take bio but that time i am getting error like this RequestsLimitError: You just made too many request to instagram API. i am try every 5 call after set time out also but still i am getting same error so how can resolved this error any one know how can fix it then please let me know.
Here this is my code =>
var InstaId = ["12345687",20k more id store here in the array]
var changesessionFlage = 0;
async.each(InstaId, function (id, callback) {
async.parallel([
function (cb) {
if (id) {
setTimeout(function () {
Client.Account.getById(sess, id).then(function (bio) {
console.log("changesessionFlage" + changesessionFlage);
changesessionFlage++
//console.log("bio : ", bio._params); // here i am getting bio one by one user
if (changesessionFlage == 6) {
changesessionFlage = 0;
}
cb(null, bio._params);
})
.catch(function (err) {
console.log("get boi: ", err)
cb(null, bio._params);
})
}, (changesessionFlage == 5) ? 10000 : 0)
}
}
], function (err, results) {
if (err) {
console.log(err);
return;
}
Result = results
callback();
});
}, function (err) {
if (err) {
console.log(err);
return;
}
else {
console.log("Result=>", Result)
if (Result) {
console.log("Result[0]=>", Result[0])
var ws = XLSX.utils.json_to_sheet(Result[0]);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "People");
var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
res.end(wbout, 'binary');
}
}
});
any one know how can fix this issue then please help me.
Your setTimeout is use incorrectly, all API calls are made at once after 10000 delay.
Since this is a one time job, just split the 20K usernames to 4K batches and execute them every hour. This way you will be under the 5k/hr API limit