Sails.js Intro

張凱迪(KD Chang)

Node.js 上的 Ruby on Rails

Outline

What's Sails?

Conclusion

Getting Started 

Model, View, Controller

Convention Over Configuration

Router and Blueprint API

Asset Management

What's Sails?

What's Node?

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

What's Sails?

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

Convention Over Configuration

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),開發者僅需規定應用中不符慣例的部分!

Convention Over Configuration

約定了檔案結構。僅需少量 config 即可自動完成編譯,測試和打包等工作。Ex. JavaBeans

Getting Started 

Getting Started 

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)

Your First Sails App

sails new sailsProject

1. Create New Sails Project

2. Create New Sails Project

cd sailsProject

3. Start the server

sails lift

Lift Your App

Default Look

Model, View, Controller

MVC

A software architectural pattern mostly for implementing user interfaces on computers

File Structure

Generate Model

sails generate [ModelName] [Attribute:Type]…

• Generate Model 

• Path

Path: api/models

• Example

sails generate model Todo title:string content:text status:boolean

Model

sails generate [ModelName] [Attribute:Type]…

• Generate Model 

• Path

Path: api/models

• Example

sails generate model Todo title:string content:text status:boolean

Model

module.exports = {
    attributes: {
        id: {
            type: 'integer',
            unique: true,
            primaryKey: true,
            autoIncrement: true
        },
        content: {
            type: 'string'
        },
        status: {
            type: 'boolean'
        }
    }
};

Generate Controller

sails generate controller [ControllerName] [Action]

• Generate Controller

Path: api/controllers

• Path

• Example

sails generate controller Todo addTodo getTodos getTodo editTodo deleteTodo

Controller

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('/');
        });
    }
}

View​

• Views are what user look

Path: views/...

• Format

• Path

1. EJS(Default)
2. Jade

Router and Blueprint API

Request

• 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

Request

• 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 }

• body parameters (req.body)

 

request with a parseable body (e.g. JSON, url-encoded, or XML) has body parameters equal to its parsed value

Response

• res.view([view, options[, fn]]) 

• res.json(obj[, headers|status[, status]])

• res.redirect(url[, status])

• res.send(body|status[, headers|status[, status]]) 

Blueprints API

• Blueprints are Sails’ way of quickly generating API routes and actions based on your application design.

RESTful routes

Shortcut routes

Action routes

RESTful 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

Shortcut routes

• 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.

Action routes

• 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!");
  }
}

Override settings

• Defining a _config key in your controller definition

// In your controller
module.exports = {
  _config: {
    actions: false,
    shortcuts: false,
    rest: false
  }
}

Policies

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'']
  }
}

Routing

• Routes urls to controllers/actions

• Path

Path: config/routes.js

Static Routes

• Point to a static view

• Point to 'views/index.ejs'

    '/': {
        view: 'index',
    },

Routes

• Point to controller and action

• Point to 'api/controllers/TodoController'

    '/': {
        controller: 'TodoController',
        action: 'getTodos'
    },

Asset Management

Asset Management

• Static Assets

• Path

CSS, JavaScript, images 

• Tasks Runner

tasks/pipeline.js

Path: assets/...

Conclusion

Pros & Cons

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

Let's lift!

Sails.js Introduction

By 張凱迪(KD Chang)

Sails.js Introduction

Sails.js 入門簡介(Sails.js Introduction)

  • 2,101