SlideShare a Scribd company logo
SailsJS
Developing REST services
• MVC backend framework for Node.js
• Built on top of Express
• Inspired by Ruby on Rails / Zend
• Convention over configuration
• Ideal for real time applications, games, REST
services
What is SailsJS?
• Database agnostic (Waterline ORM)
• Front end agnostic
• Auto generated REST API
• Auto generated model methods
• DB migration support
• Easy web socket support
• Flexible configuration
• Multiple environments support
• Localization support
• Still allows to use Express or integrate other
frameworks
Core features
• npm I –g sails //installs framework
• cd to your project folder
• sails new //or you can pass path as argument
• npm install //installing package dependencies
• run sails lift
Installation and first application
Running application
• api/controller – controllers
• api/model – models
• api/policies – policies
• api/responses – application responses
• api/services – reusable services
• assets – static assets
• config – application configuration settings
• views – application views
• tasks – grunt cli tasks
Project structure
• Sails generate api Category
• What just has happened:
– CategoryController is created
– Category model is created
– Sails created blueprint for route /category
• Let’s run the app
• Model and controller can be generated
same way
Generate API Sample
Generate API Sample
• Located at: Api/models
• Describes DB mapping, validation rules,
custom functions
• Please refer to Waterline ORM
documentation
Models
• PostgreSQL
• MySQL
• MongoDB
• Memory
• Disk
• Redis
• Riak
• OrientDB
• Neo4j
• FoundationDB SQL Layer
• And others
Supported databases
Model sample
module.exports = {
//by default will match model name
tableName: 'user',
//each model may have its own adapter and stored in separate database
//if not specified default adapter is used
adapter: 'postgresql',
attributes: {
name: {
type: 'string',
required: true,
indexed: true,
maxLength: 50
//custom validation can be added here like contains, before, after etc.
},
//supports associations 1 to 1, 1 to many and many to many
items:{ collection: "item“, via: ‘user’},
//supports custom functions
formattedName: function(){
return this.name;
}
},
//supports lifecycle callbacks: beforeValidate, afterValidate, beforeUpdate,
// afterUpdate, beforeCreate, afterCreate. beforeDestroy, afterDestroy
beforeCreate: function(values, cb) {
//do something with values
//then call callback, callback expects error arg if occurred
cb();
}
};
Model blueprints
• following methods are available for each property:
– findOneByPropertyName
– findOneByPropertyNameIn
– findOneByPropertyNameLike
– findByPropertyName
– findByPropertyNameIn
– findByPropertyNameLike
– countByPropertyName
– countByPropertyNameIn
– countByPropertyNameLike
– propertyNameStartsWith
– propertyNameEndsWith
– propertyNameContains
Data filtering
• find() – accepts object with field definition like {filter:
{name:{startsWith:”A”}}}
• Or it can an be called as chain:
Category.find().skip(10).limit(10)
• Supports:
– Filtering
– Paging
– Sorting
Controller
• Full support for RESTful routes
• Shortcut routes
• Can have custom actions
• Can be put in subdirs and subdir becomes part of the
route
• Has standard methods for CRUD support which can
be overridden
• Policies either per action or for entire controller
Controller: custom action sample
//register route
module.exports.routes = {
'post /category/:id/activate': 'CategoryController.activate'
};
//add method to the controller
module.exports = {
activate: function(req,res){
Category.findOne({id: req.param.id}, function(err, model){
if(err || !model)
return res.badRequest("Category not found");
model.active = true;
model.save(function(err){
return res.ok(model);
});
});
}
};
Policies
• Used for authentication/authorization or like
simple handlers
• Integrated with controllers
• Can be integrated with Passport
Policy sample
// api/policies/canWrite.js
module.exports = function canWrite(req, res, next) {
var categoryId = req.param('id');
CategoryPermissions.findOneByCategoryId(categoryId, function (err, permission) {
//skip to default error handler
if (err) return next(err);
//if there is no permission or write is not allowed
if(!permission || permission.type !== 'write')
return res.forbidden('You do not have access to perform this action');
next();
});
};
//in config/policies.js
module.exports.policies = {
//specifying controller policies will be applied against
CategoryController: {
// Apply the 'isLoggedIn' policy to all actions
'*': 'isLoggedIn',
// Apply the 'canWrite' to create
create: ['canWrite']
}
};
Services
• Used for authentication/authorization or like simple
handlers
• Contains reusable logic across application
• Automatically registered by Sails like Model or
Controller
• Sample: https://github.com/balderdashy/sails-
docs/blob/0.9/services.md
Assets
• This folder is just for static content
• No need to assets in URL
Configuration
• Allows to configure:
– Environments
– Locales
– Blueprints – routing rules
– Connection strings
– Application bootstrap
– Sessions
– Sockets
– View engine
– Logging
Views
• View is simple HTML page
• Multiple view engines are supported
• Default is EJB
displayCategories: function(req,res){
Category.find({},function(error, categories){
//returning res.view will look up view
//if view name is not passed it will try to find it by action name
//object can be passed to view as a model
return res.view('display-categories', {title:'Display categories',
categories: categories});
});
Web socket support
• Integrated with socket.io
• You need to write just client side code for web
sockets
• Still you may subscribe to the model change events
for fallbacks
• You may broadcast your own messages
Demo
Demo
https://github.com/AndreyKol/lohika-tech-talk-sailsjs
Sum Up
• Runs on any platform
• DB agnostic
• Front end agnostic
• Good for prototyping
• Incredibly speeds up implementation
• Does not require sails to be installed in production
Thank You!

More Related Content

PDF
Sails.js Model / ORM introduce
PDF
Sails Framework Instroduction
PDF
Sails.js Intro
PPTX
Javascript Bundling and modularization
PPT
Node.js Express Framework
PPTX
WordCamp Ann Arbor 2015 Introduction to Backbone + WP REST API
PPTX
Express JS
PPTX
Packing for the Web with Webpack
Sails.js Model / ORM introduce
Sails Framework Instroduction
Sails.js Intro
Javascript Bundling and modularization
Node.js Express Framework
WordCamp Ann Arbor 2015 Introduction to Backbone + WP REST API
Express JS
Packing for the Web with Webpack

What's hot (20)

PDF
Ansible 101 - Presentation at Ansible STL Meetup
PDF
Running Node.js in Production using Passenger
PDF
RESTful web apps with Apache Sling - 2013 version
PDF
JBoss, Rails and the cloud
PDF
The SPDY Protocol
PDF
buk.io Serverless deployment
PPTX
Spring Boot Update
PDF
The Evolution of Airbnb's Frontend
PDF
OSGi, Scripting and REST, Building Webapps With Apache Sling
PDF
遠端團隊專案建立與管理 remote team management 2016
PDF
Секретный доклад о React Router - OdessaJS 2014
PPTX
An Overview on Nuxt.js
PDF
Highly available Drupal on a Raspberry Pi cluster
PDF
FITC - Here Be Dragons: Advanced JavaScript Debugging
PPTX
Module design pattern i.e. express js
PDF
KOWAZA for mackerel
PDF
Bundle your modules with Webpack
PDF
Effective Web Application Development with Apache Sling
PDF
WordPress as the Backbone(.js)
PDF
Integrating Browserify with Sprockets
Ansible 101 - Presentation at Ansible STL Meetup
Running Node.js in Production using Passenger
RESTful web apps with Apache Sling - 2013 version
JBoss, Rails and the cloud
The SPDY Protocol
buk.io Serverless deployment
Spring Boot Update
The Evolution of Airbnb's Frontend
OSGi, Scripting and REST, Building Webapps With Apache Sling
遠端團隊專案建立與管理 remote team management 2016
Секретный доклад о React Router - OdessaJS 2014
An Overview on Nuxt.js
Highly available Drupal on a Raspberry Pi cluster
FITC - Here Be Dragons: Advanced JavaScript Debugging
Module design pattern i.e. express js
KOWAZA for mackerel
Bundle your modules with Webpack
Effective Web Application Development with Apache Sling
WordPress as the Backbone(.js)
Integrating Browserify with Sprockets
Ad

Similar to Sails js (20)

PDF
Module, AMD, RequireJS
PPSX
RequireJS
KEY
How and why i roll my own node.js framework
PPTX
Docker based Architecture by Denys Serdiuk
PDF
BP-6 Repository Customization Best Practices
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
PPTX
Ember - introduction
PPTX
Ansible benelux meetup - Amsterdam 27-5-2015
PPT
Integrating AngularJS with Drupal 7
PPTX
Introduction to Monsoon PHP framework
PDF
JavaOne India 2011 - Servlets 3.0
PDF
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
PPTX
Spring boot Introduction
PDF
Staying Sane with Drupal NEPHP
PDF
Decoupled Libraries for PHP
PDF
TechBeats #2
PDF
Voorhoede - Front-end architecture
PPTX
CodeIgniter & MVC
PDF
Staying Sane with Drupal (A Develper's Survival Guide)
Module, AMD, RequireJS
RequireJS
How and why i roll my own node.js framework
Docker based Architecture by Denys Serdiuk
BP-6 Repository Customization Best Practices
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Ember - introduction
Ansible benelux meetup - Amsterdam 27-5-2015
Integrating AngularJS with Drupal 7
Introduction to Monsoon PHP framework
JavaOne India 2011 - Servlets 3.0
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Spring boot Introduction
Staying Sane with Drupal NEPHP
Decoupled Libraries for PHP
TechBeats #2
Voorhoede - Front-end architecture
CodeIgniter & MVC
Staying Sane with Drupal (A Develper's Survival Guide)
Ad

Recently uploaded (20)

PDF
Digital Logic Computer Design lecture notes
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Welding lecture in detail for understanding
PPTX
web development for engineering and engineering
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPT
Mechanical Engineering MATERIALS Selection
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPT
Project quality management in manufacturing
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Geodesy 1.pptx...............................................
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Digital Logic Computer Design lecture notes
CH1 Production IntroductoryConcepts.pptx
OOP with Java - Java Introduction (Basics)
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Foundation to blockchain - A guide to Blockchain Tech
additive manufacturing of ss316l using mig welding
Welding lecture in detail for understanding
web development for engineering and engineering
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Mechanical Engineering MATERIALS Selection
Automation-in-Manufacturing-Chapter-Introduction.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Project quality management in manufacturing
UNIT 4 Total Quality Management .pptx
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Geodesy 1.pptx...............................................
UNIT-1 - COAL BASED THERMAL POWER PLANTS

Sails js

  • 2. • MVC backend framework for Node.js • Built on top of Express • Inspired by Ruby on Rails / Zend • Convention over configuration • Ideal for real time applications, games, REST services What is SailsJS?
  • 3. • Database agnostic (Waterline ORM) • Front end agnostic • Auto generated REST API • Auto generated model methods • DB migration support • Easy web socket support • Flexible configuration • Multiple environments support • Localization support • Still allows to use Express or integrate other frameworks Core features
  • 4. • npm I –g sails //installs framework • cd to your project folder • sails new //or you can pass path as argument • npm install //installing package dependencies • run sails lift Installation and first application
  • 6. • api/controller – controllers • api/model – models • api/policies – policies • api/responses – application responses • api/services – reusable services • assets – static assets • config – application configuration settings • views – application views • tasks – grunt cli tasks Project structure
  • 7. • Sails generate api Category • What just has happened: – CategoryController is created – Category model is created – Sails created blueprint for route /category • Let’s run the app • Model and controller can be generated same way Generate API Sample
  • 9. • Located at: Api/models • Describes DB mapping, validation rules, custom functions • Please refer to Waterline ORM documentation Models
  • 10. • PostgreSQL • MySQL • MongoDB • Memory • Disk • Redis • Riak • OrientDB • Neo4j • FoundationDB SQL Layer • And others Supported databases
  • 11. Model sample module.exports = { //by default will match model name tableName: 'user', //each model may have its own adapter and stored in separate database //if not specified default adapter is used adapter: 'postgresql', attributes: { name: { type: 'string', required: true, indexed: true, maxLength: 50 //custom validation can be added here like contains, before, after etc. }, //supports associations 1 to 1, 1 to many and many to many items:{ collection: "item“, via: ‘user’}, //supports custom functions formattedName: function(){ return this.name; } }, //supports lifecycle callbacks: beforeValidate, afterValidate, beforeUpdate, // afterUpdate, beforeCreate, afterCreate. beforeDestroy, afterDestroy beforeCreate: function(values, cb) { //do something with values //then call callback, callback expects error arg if occurred cb(); } };
  • 12. Model blueprints • following methods are available for each property: – findOneByPropertyName – findOneByPropertyNameIn – findOneByPropertyNameLike – findByPropertyName – findByPropertyNameIn – findByPropertyNameLike – countByPropertyName – countByPropertyNameIn – countByPropertyNameLike – propertyNameStartsWith – propertyNameEndsWith – propertyNameContains
  • 13. Data filtering • find() – accepts object with field definition like {filter: {name:{startsWith:”A”}}} • Or it can an be called as chain: Category.find().skip(10).limit(10) • Supports: – Filtering – Paging – Sorting
  • 14. Controller • Full support for RESTful routes • Shortcut routes • Can have custom actions • Can be put in subdirs and subdir becomes part of the route • Has standard methods for CRUD support which can be overridden • Policies either per action or for entire controller
  • 15. Controller: custom action sample //register route module.exports.routes = { 'post /category/:id/activate': 'CategoryController.activate' }; //add method to the controller module.exports = { activate: function(req,res){ Category.findOne({id: req.param.id}, function(err, model){ if(err || !model) return res.badRequest("Category not found"); model.active = true; model.save(function(err){ return res.ok(model); }); }); } };
  • 16. Policies • Used for authentication/authorization or like simple handlers • Integrated with controllers • Can be integrated with Passport
  • 17. Policy sample // api/policies/canWrite.js module.exports = function canWrite(req, res, next) { var categoryId = req.param('id'); CategoryPermissions.findOneByCategoryId(categoryId, function (err, permission) { //skip to default error handler if (err) return next(err); //if there is no permission or write is not allowed if(!permission || permission.type !== 'write') return res.forbidden('You do not have access to perform this action'); next(); }); }; //in config/policies.js module.exports.policies = { //specifying controller policies will be applied against CategoryController: { // Apply the 'isLoggedIn' policy to all actions '*': 'isLoggedIn', // Apply the 'canWrite' to create create: ['canWrite'] } };
  • 18. Services • Used for authentication/authorization or like simple handlers • Contains reusable logic across application • Automatically registered by Sails like Model or Controller • Sample: https://github.com/balderdashy/sails- docs/blob/0.9/services.md
  • 19. Assets • This folder is just for static content • No need to assets in URL
  • 20. Configuration • Allows to configure: – Environments – Locales – Blueprints – routing rules – Connection strings – Application bootstrap – Sessions – Sockets – View engine – Logging
  • 21. Views • View is simple HTML page • Multiple view engines are supported • Default is EJB displayCategories: function(req,res){ Category.find({},function(error, categories){ //returning res.view will look up view //if view name is not passed it will try to find it by action name //object can be passed to view as a model return res.view('display-categories', {title:'Display categories', categories: categories}); });
  • 22. Web socket support • Integrated with socket.io • You need to write just client side code for web sockets • Still you may subscribe to the model change events for fallbacks • You may broadcast your own messages
  • 23. Demo
  • 25. Sum Up • Runs on any platform • DB agnostic • Front end agnostic • Good for prototyping • Incredibly speeds up implementation • Does not require sails to be installed in production

Editor's Notes

  • #8: Controller or Model
  • #10: Controller or Model
  • #11: Controller or Model