Sails JS new response in WebStorm - node.js

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.

Related

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?

What is the reason for using GET instead of POST in this instance?

I'm walking through the Javascript demos of pg-promise-demo and I have a question about the route /api/users/:name.
Running this locally works, the user is entered into the database, but is there a reason this wouldn't be a POST? Is there some sort of advantage to creating a user in the database using GET?
// index.js
// --------
app.get('/api/users/:name', async (req, res) => {
try {
const data = (req) => {
return db.task('add-user', async (t) => {
const user = await t.users.findByName(req.params.name);
return user || t.users.add(req.params.name);
});
};
} catch (err) {
// do something with error
}
});
For brevity I'll omit the code for t.users.findByName(name) and t.users.add(name) but they use QueryFile to execute a SQL command.
EDIT: Update link to pg-promise-demo.
The reason is explained right at the top of that file:
IMPORTANT:
Do not re-use the HTTP-service part of the code from here!
It is an over-simplified HTTP service with just GET handlers, because:
This demo is to be tested by typing URL-s manually in the browser;
The focus here is on a proper database layer only, not an HTTP service.
I think it is pretty clear that you are not supposed to follow the HTTP implementation of the demo, rather its database layer only. The demo's purpose is to teach you how to organize a database layer in a large application, and not how to develop HTTP services.

Load Node 'code' from database while server running

I'm looking to build my project in a modular fashion so that API endpoints can be added while the server is added.
Adding routes dynamically I should be able to figure out, it's getting the recently uploaded server code running that I can't figure out.
My project has a 'class-per-endpoint' structure. An endpoint has a class attached that can run code and do this and that.
An endpoint can also be dependent on another endpoint/class, so what I want to be able to do is call the constructor of a dynamically added class and run the code efficiently on the server (without the API calling itself).
Example where "NewAdder" endpoint was just added. Rudimentary stuff, but I just hope it's clear what I'm trying to achieve. Basically trying to add to the server's code base dynamically.
modifier.ts
class Modifier {
constructor(initiatedBy) {
this.initBy = initiatedBy;
this.modifierValue = db.getValue("modifier", {user = this.initBy})
}
function modify(toModify) {
return toModify * this.modifierValue
}
}
newAdder.ts
class NewAdder {
constructor(initiatedBy) {
this.initBy = initiatedBy;
}
modifier = new Modifier(this.initBy);
function addAndModify(a,b) {
return modifier.modify(a + b)
}
}
router.ts (this would be dynamic in real life)
app.get('/newadder/addandmodify/', function(req, res){
adder = new NewAdder(req.params.user);
res.send(adder.addAndModify(req.params.first, req.params.second);
});
Hope I made some sense.
After some more research I suppose I could use http to get and then require the module dynamically.
The code will come from our own server, so it should be safe to run in the server.
But if anyone has any idea how to go about this, would be much appreciated.

How do I make sure a promise has been returned before responding to an incoming request (Swagger/Express)

I'm trying to write a simple Swagger API that will allow me to sync a couple of systems on demand. The syncing is one way, so basically the end goal will be to send a request to both system, see what's new/changed/removed on the origin, then update the destination. I've been trying to do this using node.js instead of Java, to which I'm more used to, as a learning experience, but I'm really having a hard time figuring out a key issue due to the async nature.
As a test, I constructed a simple Express node.js app on IntelliJ, where in one of the routes I'm calling a function exported from a different file and trying to get the response back. Unfortunately, this isn't working so well. What I've done is this:
getit.js - (this goes to the Ron Swanson generator to get a quote)
const rp = require('request-promise');
async function dorequest() {
const response = await rp(uri);
return Promise.resolve(response);
};
module.exports = {dorequest}
In the route I've done this:
var getit = require ('./getit.js');
/* GET users listing. */
router.get('/', function(req, res, next) {
var ret = getit.dorequest();
res.send(ret);
console.log('res out' + ret);
});
What I get in the console is
res out[object Promise]
and the response is of course empty.
What am I doing wrong? I've been playing with this for a week now, tried various methods, but I keep getting similar results. I'm obviously missing something out, and would appreciate some help.
Thanks!
Object is empty because it was written on the console before the Promise is resolved. You have to wait until Promise is resolved and then send the response back so try to change your code like this:
var getit = require ('./getit.js');
/* GET users listing. */
router.get('/', function(req, res, next) {
getit.dorequest().then(function(data) {
console.log('res out' + data);
res.send(data);
});
});
Since you are using async/await approach all you need to do is to place await before getit.dorequest();
so this line will look like var ret = await getit.dorequest();

Accessing response headers using NodeJS

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').

Resources