Accessing response headers using NodeJS - node.js

I'm having a problem right now which I can't seem to find a solution to.
I'm using Uservoice's NodeJS framework to send some requests to UserVoice regarding Feedback posts. A problem I've run into are ratelimits so I want to save the header values X-Rate-Limit-Remaining, X-Rate-Limit-Limit and X-Rate-Limit-Reset locally. I've made a function for updating and getting that value and am calling it like this:
var content = "Test"
c.post(`forums/${config.uservoice.forumId}/suggestions/${id}/comments.json`, {
comment: {
text: content
}
}).then(data => {
rl.updateRL(data.headers['X-Rate-Limit-Limit'],data.headers['X-Rate-Limit-Remaining'],data.headers['X-Rate-Limit-Reset'])
When running this code I get the error Cannot read property 'X-Rate-Limit-Limit' of undefined.
This is not a duplicate, I've also tried it lowercase as described here but had no luck either. Thanks for helping out!
EDIT:
The function takes the following parameters:
module.exports = {
updateRL: (lim, rem, res) {SAVING STUFF HERE}
}
It is defined in the file rates.jsand is imported in the above file as const rl = require('../rates').

Related

Problems with getRoutingService().calculateRoute parameters

I am looking into the HereMaps as a possible map provider for our company and am having difficulty with the return params for calculateRoute. I am trying to get the route instructions to be returned from the endpoint but it fails when trying to do so. I am currently passing in ...
var routingParameters = {
routingMode: 'fast',
transportMode: 'truck',
// The start point of the route:
origin: position.coords.latitude + ',' + position.coords.longitude,
// The end point of the route:
destination: '50.672770,-120.375370',
return: 'polyline',
};
This seems to work however when i try to do return: 'polyline, actions, instructions', to get the instruction info the route request fails. I noticed in the docs that these are available but don't seem to work for my case. My guess is it may be due to being on the free version for now. Any help is appreciated.

why does this post implementation return 404 in node/express?

The following URL provides a pretty good walkthrough of how to wire up a node/express implementation to read from Google Cloud Platform Cloud SQL:
https://medium.com/#austinhale/building-a-node-api-with-express-and-google-cloud-sql-9bda260b040f
I implemented the steps in this article and my local implementation is working as expected. However, this URL doesn't cover how to wire up inserts/updates. Based on some googling, I came up with the following implementation for a post/insert:
// POST method route
app.post('/users', function (req, res) {
var post = { FirstName: req.FirstName, LastName: req.LastName };
var query = connection.query('INSERT INTO User SET ?', post, function (error, results, fields) {
if (error){
console.log(error.message);
}
});
})
I'm POST-ing the following request from Postman as raw JSON:
http://localhost:3000/users/
{
"FirstName":"John",
"LastName":"Smith"
}
However, the response status is 404 Not Found. The standard GET is working as expected though. Any idea what I might be doing wrong here? Also, I'm new to Node/Express. What's the easiest way to get started debugging? For example, is there a recommended plugin for CDT that I can use for this? The sample code that I used for the GET used console.log("message") but when I tried this approach, nothing appeared to be written out to the node console window or to CDT?

How to send code written in code editor to server using POST method

I'm working on building a snippet manager app and through the interface you can create new snippets and edit them using a code editor but what I'm stuck at is how can I send the snippet code to my server using POST for it to create a new file for that snippet.
For ex. -
const getUser = async (name) => {
let response = await fetch(`https://api.github.com/users/${name}`);
let data = await response.json()
return data;
}
One solution that I can think of is to parse the code into JSON equivalent that'll contain all the tokens in JSON format but for that I'll have to add parsers for every language and select a parser based on what language the user selected. I'm trying to figure out a way to avoid having to add all the parsers unless there isnt any solution for this.
Another solution I can think of is to generate the file from the frontend and send that file through POST request.
My current stack is Node+React
Using the second solution is working for me right now. I've written the code below for it -
app.post("/create", isFileAttached, function(req, res) {
const { file } = req.files;
const saveLocation = `${saveTo}/${file.mimetype.split("/")[1]}`;
const savePath = `${saveLocation}/${file.name}`;
if (!fs.existsSync(saveLocation)) {
fs.mkdirSync(saveLocation, { recursive: true });
}
fs.writeFile(savePath, file.data.toString(), err => {
if (err) throw err;
res.status(200).send({ message: "The file has been saved!" });
});
});
With this solution I no longer have to add any parsers, since whatever's written in the files are no longer a concern anymore.

How to get Scenario name from cucumber js?

In case of error I want to be able to log the scenario name. I'm using cucumber.js and node.
Feature file
Scenario: As me I can go to google
Given that I have a computer
When I go to google
Then I see wondrous stuff
I have tried the code below, but the name comes back as an empty string.
When(/^I go to google$/, (scenario) => {
// do something
var scenarioName = scenario.name;
});
By stepping through the code I can see that it's a function.
It has :
[[FunctionLocation]] = Object
[[Scopes]] = Scopes(6)
length = 2
name= ""
It seems like you can't do this in a Given or When, it has to be done in the Before or After hook:
Before((scenario) => {
const scenarioName = scenario.name;
console.log(`${scenarioName}`);
});
I could get the scenario name using this code:
Before((scenario: any) => {
console.log(`Starting scenario ${scenario.sourceLocation.uri}:${scenario.sourceLocation.line} (${scenario.pickle.name})`);
});
As you can see, there's more in there than just the scenario name. The entire test, with all the steps, tags, etc is in the object. I'm using CucumberJS 5.0.3.
I found the scenario name using below code
console.log(`The scenario is ${JSON.stringify(scenario.pickle.name)}.`);

Sails JS new response in WebStorm

I'm newbie in Sails JS..
I'm trying to create a new custom response, I didn't find any auto-generator so I created it manually.
//someName.js
module.exports = function someName(data, options) {
console.log('test');
};
I'm trying to access this response from controller:
//someController.js
module.exports = {
someController: function(req, res) {
res.someName();
}
}
The problem is that WebStorm isn't recognize this response..
Unresolved function or method someName.
But when executing the app-it's working..(WebStorm recognize the default responses which came with the 'sails new someApp').
Thanks for your help!
The code in the Sails.js library that loads custom responses probably does something like this:
files = getFilesInApiResponsesDirectory()
files.forEach(function(file) {
name = extractName(file);
res[name] = require(file); // <-- too dynamic to infer at this point
})
There is no way that WebStorm code analyzer could infer the relationship between res and your custom response function without actually running Sails.js code or receiving a (less dynamic, more explicit) hint.
Anyway, the message you got does not necessarily represent a critical error, it's a "code inspection" you can disable or suppress.

Resources