張凱迪(KD Chang)
Node.js 上的 Ruby on Rails
What's Sails?
Conclusion
Getting Started
Model, View, Controller
Convention Over Configuration
Router and Blueprint API
Asset Management
A platform built on Chrome's JavaScript runtime(V8)
Build fast, scalable network applications easily
Use an event-driven, non-blocking I/O model
JavaScript beyond the browser
Node's Rails(Convention Over Configuration)
Good for building chat, realtime app, or multiplayer games
Build on the top of Express
Support NoSQL & RDB, Power ORM (Waterline)
MVC pattern Web framework
Auto-generate REST APIs (Blueprint)
Easy WebSocket Support
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, and not necessarily losing flexibility. - Wikipedia
用一些簡單的常規、慣例(convention)來取代繁雜的設定(configuration),開發者僅需規定應用中不符慣例的部分!
約定了檔案結構。僅需少量 config 即可自動完成編譯,測試和打包等工作。Ex. JavaBeans
1. Preinstall Node.js
// Install the latest stable release sails:
sudo npm -g install sails
// On Windows (or Mac OS with Homebrew), you don't need sudo:
npm -g install sails
2. Install Sails.js (we use v0.11.4)
sails new sailsProject
1. Create New Sails Project
2. Create New Sails Project
cd sailsProject
3. Start the server
sails lift
A software architectural pattern mostly for implementing user interfaces on computers
sails generate [ModelName] [Attribute:Type]…
• Generate Model
• Path
Path: api/models
• Example
sails generate model Todo title:string content:text status:boolean
sails generate [ModelName] [Attribute:Type]…
• Generate Model
• Path
Path: api/models
• Example
sails generate model Todo title:string content:text status:boolean
module.exports = {
attributes: {
id: {
type: 'integer',
unique: true,
primaryKey: true,
autoIncrement: true
},
content: {
type: 'string'
},
status: {
type: 'boolean'
}
}
};
sails generate controller [ControllerName] [Action]
• Generate Controller
Path: api/controllers
• Path
• Example
sails generate controller Todo addTodo getTodos getTodo editTodo deleteTodo
module.exports = {
getTodos: function(req, res) {
TodoService.getTodos(function(todos) {
res.view("homepage", {
'todos': todos
});
});
},
addTodo: function(req, res) {
var todoVal = req.body.content;
TodoService.addTodo(todoVal, function(success) {
res.redirect('/');
});
},
deleteTodo: function(req, res) {
var todoId = req.params.id;
TodoService.deleteTodo(todoId, function(success) {
res.redirect('/');
});
}
}
• Views are what user look
Path: views/...
• Format
• Path
1. EJS(Default)
2. Jade
• req.param() searches the url path
POST /product/123
POST /product?sku=123
POST /product with a JSON request body: { "sku": 123 }
req.param('sku');
// ->123
• url path parameters (req.params)
• query string parameters (req.query)
a request "/foo?email=5" has query params { email: 5 }
a request "/foo/4" to route /foo/:id has url path params { id: 4 }
request with a parseable body (e.g. JSON, url-encoded, or XML) has body parameters equal to its parsed value
• res.view([view, options[, fn]])
• res.json(obj[, headers|status[, status]])
• res.redirect(url[, status])
• res.send(body|status[, headers|status[, status]])
• Blueprints are Sails’ way of quickly generating API routes and actions based on your application design.
RESTful routes
Shortcut routes
Action routes
• Sails will create RESTful routes whenever it loads a controller and model file with the same identity.
RESTful routes are activated by default in new Sails apps, and can be turned off by setting sails.config.blueprints.rest to false (typically in /config/blueprints.js.)
sails generate api pet
Implicit actions :
find, create, update, destroy, populate, add and remove
• Action to take is encoded in the path
Shortcut routes are activated by default in new Sails apps, and can be turned off by setting sails.config.blueprints.shortcuts to false (typically in /config/blueprints.js)
Should be disable in production
// shortcut creates a new user
/user/create?name=joe
// updates user #1.
/user/update/1?name=mike
These routes only respond to GET requests.
• Exposed as a route at the URL <controller>/<property>
RESTful routes are activated by default in new Sails apps, and can be turned off by setting sails.config.blueprints.actions to false (typically in /config/blueprints.js.)
Use req.method to determine which method was used
controller / method
/todo/read
// TodoController.js
module.exports {
read: function (req, res) {
res.send("I like todo!");
}
}
• Defining a _config key in your controller definition
// In your controller
module.exports = {
_config: {
actions: false,
shortcuts: false,
rest: false
}
}
• authorization and access control (more about policies)
{
ProfileController: {
/* Apply 'isLoggedIn' by default to
all actions that are NOT specified below */
'*': 'isLoggedIn',
/* Apply the 'isAdmin' policy,
in that order, to the 'create' action */
create: ['isAdmin'']
}
}
• Routes urls to controllers/actions
• Path
Path: config/routes.js
• Point to a static view
• Point to 'views/index.ejs'
'/': {
view: 'index',
},
• Point to controller and action
• Point to 'api/controllers/TodoController'
'/': {
controller: 'TodoController',
action: 'getTodos'
},
• Static Assets
• Path
CSS, JavaScript, images
• Tasks Runner
tasks/pipeline.js
Path: assets/...
Pros
• Good MVC framework for Node.js
Cons
• Build routes / Restful API fast
• It's still very new
• Short of resources
• Build real-time app easily