Created
June 26, 2013 10:10
-
-
Save devrishik/5866333 to your computer and use it in GitHub Desktop.
A Javascript noob's guide to Node + Express + Compound.JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This blog represents all the wrong doings of a first time programmer into javascript domain | |
To start with lets beging with a short explaination of these technologies | |
Node: The very basic layer required by you to create a website | |
Thats the best thing about it, imagine an app working without any middle-ware, thus improving the performance | |
Express: An upper layer for Node to make things a little easier and more abstract | |
Compound: The top layer built specially to be used over Express. It is down right translation of RoR | |
It adds a much higher level of abstraction into the app | |
The application which we will be developing will go step by step | |
1st: A Sample app just using Node.js | |
2nd: A Sample app using Node.js + Express.js | |
3rd: Using The templating Library Jade | |
4th: Links and instructions to understand Compound.js | |
5th: Development of a sample login app with apt utilization of MVC architectures | |
----------------------------------------------------------------------------------- | |
1st: | |
Read through node.js API and developed a sample "hello world" app | |
It is very important to refer to the documentation again and again, most of the solutions to problems are | |
found in the docs | |
http://nodejs.org/api/all.html | |
Now an issue will be there: accepting request data | |
the request data(req) we assumed was not the request from http.IncomingMessage, | |
it was for the request data sent from one server to another | |
hence in the confusion we faced such issues (listed below ) | |
( | |
the api wants the request to read through complete data before posting the response | |
below is the code | |
if request variable is omitted the code works fine. | |
) | |
var http = require("http"), | |
url = require("url"); | |
http.createServer(function (request, response) { | |
var _get = url.parse(request.url, true).query; | |
response.writeHead(200, { | |
'Content-Type': 'text/plain' | |
}); | |
console.log( _get ); | |
response.end('Here is your data: ' + _get['data']); | |
}).listen(8080); | |
------------------------------------------------------------------------------------ | |
2nd: | |
Now lets start with Express.js, it is a web application framework for node | |
http://expressjs.com | |
Read Express.js API and the guide | |
Develop form with get and post methods | |
var express = require('express'); | |
var app = express(); | |
app.listen(3001); | |
app.get('/',function(req,res){ | |
res.send('<form method="post" action="users"><label>Name</label><input type="text" id="name" name="name"></p><input type="submit" value="Submit" /></form>'); | |
}) | |
app.post('/users', function(req, res){ | |
app.use(express.bodyParser()); | |
console.log(req.body); | |
res.send(req.body.name); | |
}); | |
Experiments with Sessions | |
eg: http://blog.modulus.io/nodejs-and-express-sessions | |
Read about sessions | |
got stuck at the use of repetitive html codes as res.send can not be used twice as every time we use it, it overwrites the previous data on the html, thus a complete html template will be required to post various data | |
Solution : Templates | |
Start reading Jade. | |
----------------------------------------------------------------------------------- | |
3rd: | |
JADE | |
jade-lang.com | |
Jade is a templating library which translates to HTML 5 | |
For newbies, a template is kind of a board on which a programmer defines the position where he wants the data to be displayed | |
It is usefull as the template can be used again and again | |
and templating brings a sense of modularity to the code | |
Make an app with maintaining session and routing between urls and using jade templates | |
Any random variable can be declared with "req.session.[variable]" to store a session variable, So if you want to store count | |
or a string or anything required by you, it can be added to the req.session | |
app.bodyParser is already mentioned in default declarations | |
so we dont need to rewrite it when parsing post data from the form post request. | |
Here is what I have developed -> | |
https://github.com/devrishik/eashmart/blob/master/ | |
useful links | |
https://github.com/shapeshed/express_example | |
http://naltatis.github.io/jade-syntax-docs/ | |
http://blog.modulus.io/nodejs-and-express-sessions | |
-------------------------------------------------------------------------------------- | |
4th: | |
Compound.JS | |
http://compoundjs.com/docs/ | |
Now lets start with compound.js | |
to get a quick overview just read through | |
https://github.com/compoundjs/guides/blob/master/basics/crash-course.md | |
Reading the API will be simple, but then trying out the sample app will create problems | |
Issues: | |
compound uses EJS as a default library for templating, we have to use jade | |
so following | |
http://tysonjs.com/blog/how-do-yo-make-a-compoundjs-app#.UcKjjvEW3Zg | |
will help, but not to much. | |
After sirfing through blogs and google groups for some time you will get the solution | |
so saving on your time, here it is -> | |
compound init [project_name] --tpl jade --db mysql | |
This commands initiates the development of a project and specifying the template 'jade' and database 'mysql' | |
cd [project_name] | |
compound generater crud ............. | |
Here we use generater CRUD ( Create Read Update Delete ) will generate an app for you | |
compound generater crud name | |
another error, after using the crud generator for generating your sample app, all the views | |
will be compiled in EJS. | |
Start reading up on a sample app | |
http://nyukapiszka.wordpress.com/2013/02/16/node-js-mvc-frameworks-getting-started-with-compoundjs/ | |
Amit gave us a huge tip.... "follow RoR blog tutorial to learn about MVC and compound.js" | |
http://guides.rubyonrails.org/getting_started.html | |
things learnt: | |
there are two types of models - non persistent defined in app/models | |
and | |
persistent defined in the database schema /config/database.js | |
https://github.com/compoundjs/guides/blob/master/basics/elements-explained.md | |
Update the schema required in db/schema.js | |
We have to make the database ourselves ..... i know thats a dumb thing not to know :D but please forgive my novice | |
Delete the non persistent model from app/model as this constricts the app from connecting to the persistent model | |
After all this, you expect the app to run... well it will run but still no List created | |
then with all my genius and "persistent" hinting by Amit I realized... there is no table :-) | |
compound db migrate | |
Before executing this command follow these steps | |
go to config/database.js | |
specify the database your going to use and the driver as 'mysql' under the development | |
driver: 'mysql', | |
host: 'localhost', | |
port: 3306, | |
username: 'root', | |
password: '', | |
database: 'db_dev' | |
open mysql | |
mysql -u root | |
create database db_dev; | |
go to schema.js | |
check out your schema, which is the table which will be created in your database | |
This schema also represents the persisitent model for your program | |
Now execute this command | |
learn from http://stackoverflow.com/questions/16618094/compound-db-update-migrate-not-working-in-mysql | |
This command updates your table | |
Perform migrate on | |
- mysql | |
1 | |
DROP TABLE IF EXISTS `List` [89 ms] | |
CREATE TABLE `List` ( | |
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, | |
`dev` VARCHAR(255) NULL | |
) [156 ms] | |
Now, the app works persistently :P | |
Here is the complete source -> | |
https://github.com/devrishik/To-Do-List/tree/master/todo-list-app | |
---------------------------------------------------------------------------------- | |
5th: | |
Creating a Sample App in Compound.JS | |
task : Start preparing the login/signup app | |
lets start with reading up on models and how to play with data | |
In simple words, model is that part of MVC framework where all the data manipulations come | |
1st : Defining unique key or a primary key | |
in order to make a login app, its common sense that you would want your username to be unique | |
inumerable examples available for mongoose db schema | |
hours of searching = https://github.com/jugglingdb/mysql-adapter/issues/5 | |
property('name', {index: { kind: 'unique' ,required: true} }); | |
We have to specify the kind and required attributes inside the index in this very format | |
this takes care of the duplication and empty fields you would require for your primary field | |
as the controller instantiates the sql to write data and error will be returned for an invalid entry | |
which will be handled by the event handler | |
code := | |
this.list.updateAttributes(body.List, function (err) { | |
respondTo(function (format) { | |
format.json(function () { | |
if (err) { | |
send({code: 500, error: list && list.errors || err}); | |
} else { | |
send({code: 200, data: list}); | |
} | |
}); | |
format.html(function () { | |
if (!err) { | |
flash('info', 'List updated'); | |
redirect(path_to.list(list)); | |
} else { | |
flash('error', 'List can not be updated'); | |
render('edit'); | |
} | |
}); | |
}); | |
}); | |
2nd : Use Hooks http://jugglingdb.co/hooks.3.html | |
It is best to use the beforeCreate hook as it will be called on both edit and create | |
code := | |
module.exports = function (compound, List) { | |
List.beforeSave = function(next){ | |
console.log("before"); | |
next(); | |
} | |
}; | |
3rd : Bcrypt encryption algorithm | |
https://github.com/ncb000gt/node.bcrypt.js/ | |
The basic idea is to never save a password as String into the database | |
therefore, whenever saving a password we hash it using Bcrypt | |
and when comparing passwords we just have to compare the hashs | |
Here is the compiled version :) | |
https://github.com/devrishik/Basic_Login_App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment