MEAN stack: Wondering api.js and crud.js - node.js

I'm studying MEAN stack these day, So I make some sample apps following guidance. I made up "Bookshelf" application just few hours ago, this is provided by google cloud service, so I should delve into sample code to understand how it works.
Whole source code : https://github.com/GoogleCloudPlatform/nodejs-getting-started/tree/master/2-structured-data
Sample application : http://mymongo-1165.appspot.com/books
books/api.js
router.get('/', function list(req, res) {
model.list(10, req.query.pageToken,
function(err, entities, cursor) {
if (err) { return handleRpcError(err, res); }
res.json({
items: entities,
nextPageToken: cursor
});
});
});
books/curd.js
router.get('/', function list(req, res) {
model.list(10, req.query.pageToken,
function(err, entities, cursor) {
if (err) { return handleRpcError(err, res); }
res.render('books/list.jade', {
books: entities,
nextPageToken: cursor
});
}
);
});
these 2 codes are similar, but I don't know why these similar codes comes up. I think crud.js enough, but why api.js comes up. Could you explain how these 2 codes work?

In this sample application, there are two interface:
graphic user interface (GUI) - curd.js handles generating HTML that is rendered later in the browser (in our case jade tempting language is involved)
application programming interface (API) - api.js provides the way to interact with application programmatically, without browser (ex: create new record in database, or query some data by making specific call to particular route)
For deeper understanding I would suggest learning more about express.js, that will give better idea what those outputs are.
P.S. Welcome to MEAN world :)

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.

Nodejs - tips for creating multiple endpoints

I have a nodejs/express server being used by both Web application and Mobile application, but for now they use the same end points. But I want to divide my api into 2 one of which is for mobile and obviously the other is for web. The requests are going to be "exactly" the same. What comes to my mind as a solution is duplicating all the request where paths for newly created ones are different(so that in the mobile app, these request can be used). But this solution does not seem right, as it may mean making big changes on the client side. Is there an elegant and also favourably easier solution? Any suggestion would be appreciated.
router.get('api/snow/manuel',
function (req, res, next) {
const snowProjection = {_id: 0};
snowThick.find({}, snowProjection)
.toArray(function (err, data) {
if (err) return next(new APIError.ServerError("An error occured" + " " + err));
return res.send(data);
})
});
Here is an sample get request in my server.

How to achieve MVC pattern in sails?

I'm wondering what is the best way to achieve the MVC pattern is sails.js.
Now I have the following structure: I have a route which redirects the request to the controller:
'POST /api/user/...': {controller: 'UserController', action: 'someFunction'},
My user model:
module.exports = {
...
attributes: {...}
}
I have the controller:
someFunction: function(req, res) {
let param = req.body.param;
let userId = req.session.userId;
userService.someFunction(userId, param, function (result) {
return res.json({result});
});
},
And in the userService I have methods for manipulating the database, for example:
someFunction: function(userId, param, callback){
User.findOne(userId).exec(function (err, user){
if (err) {
callback(false);
} else {
// find the user's additional info
User.update({name: param}, { ... })
}
My real question is that is this a good pattern to follow or I'm on the wrong path.
Thanks for any kind of response.
Note: Answer to this question can be opinion-based. Here is my opinion.
Sails project is scaffolded in MVC pattern. There are separate folders for Models (api/models), Controllers (api/controllers), and Views (views).
You're doing right thing having database methods in Services.
Anything that can be required by more than one controller action should go into services.
Other thoughts:
Any logic which deals with a single model should be in that Model
Prefer to apply constraints, foreign keys at database level as well
With Node.js v7.6+, you can use async/await. Sails (Waterline) methods return Bluebird promises which works well with async/await.

Azure mobile apps CRUD operations on SQL table (node.js backend)

This is my first post here so please don't get mad if my formatting is a bit off ;-)
I'm trying to develop a backend solution using Azure mobile apps and node.js for server side scripts. It is a steep curve as I am new to javaScript and node.js coming from the embedded world. What I have made is a custom API that can add users to a MSSQL table, which is working fine using the tables object. However, I also need to be able to delete users from the same table. My code for adding a user is:
var userTable = req.azureMobile.tables('MyfUserInfo');
item.id = uuid.v4();
userTable.insert(item).then( function (){
console.log("inserted data");
res.status(200).send(item);
});
It works. The Azure node.js documentation is really not in good shape and I keep searching for good example on how to do simple things. Pretty annoying and time consuming.
The SDK documentation on delete operations says it works the same way as read, but that is not true. Or I am dumb as a wet door. My code for deleting looks like this - it results in exception
query = queries.create('MyfUserInfo')
.where({ id: results[i].id });
userTable.delete(query).then( function(delet){
console.log("deleted id ", delet);
});
I have also tried this and no success either
userTable.where({ id: item.id }).read()
.then( function(results) {
if (results.length > 0)
{
for (var i = 0; i < results.length; i++)
{
userTable.delete(results[i].id);
});
}
}
Can somebody please point me in the right direction on the correct syntax for this and explain why it has to be so difficult doing basic stuff here ;-) It seems like there are many ways of doing the exact same thing, which really confuses me.
Thanks alot
Martin
You could issue SQL in your api
var api = {
get: (request, response, next) => {
var query = {
sql: 'UPDATE TodoItem SET complete=#completed',
parameters: [
{ name: 'completed', value: request.params.completed }
]
};
request.azureMobile.data.execute(query)
.then(function (results) {
response.json(results);
});
}};
module.exports = api;
That is from their sample on GitHub
Here is the full list of samples to take a look at
Why are you doing a custom API for a table? Just define the table within the tables directory and add any custom authorization / authentication.

Resources