├── api ├── models │ ├── .gitkeep │ ├── Customer.js │ ├── Driver.js │ ├── Store.js │ └── Car.js ├── services │ └── .gitkeep ├── controllers │ ├── .gitkeep │ └── CarController.js ├── policies │ └── sessionAuth.js └── responses │ ├── ok.js │ ├── badRequest.js │ ├── forbidden.js │ ├── serverError.js │ └── notFound.js ├── assets ├── images │ └── .gitkeep ├── templates │ └── .gitkeep ├── favicon.ico ├── robots.txt └── styles │ └── importer.less ├── config ├── locales │ ├── de.json │ ├── en.json │ ├── fr.json │ ├── es.json │ └── _README.md ├── bootstrap.js ├── env │ ├── development.js │ └── production.js ├── log.js ├── models.js ├── policies.js ├── routes.js ├── i18n.js ├── csrf.js ├── globals.js ├── cors.js ├── http.js ├── session.js ├── connections.js ├── local.js ├── views.js ├── blueprints.js └── sockets.js ├── tasks ├── register │ ├── default.js │ ├── syncAssets.js │ ├── build.js │ ├── compileAssets.js │ ├── buildProd.js │ ├── linkAssets.js │ ├── linkAssetsBuild.js │ ├── linkAssetsBuildProd.js │ └── prod.js ├── config │ ├── clean.js │ ├── uglify.js │ ├── cssmin.js │ ├── sync.js │ ├── less.js │ ├── concat.js │ ├── watch.js │ ├── coffee.js │ ├── copy.js │ ├── jst.js │ └── sails-linker.js ├── pipeline.js └── README.md ├── package.json ├── app.js ├── Gruntfile.js ├── views ├── layout.ejs ├── 403.ejs ├── 404.ejs ├── homepage.ejs └── 500.ejs └── README.md /api/models/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /api/services/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/images/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /api/controllers/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/templates/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /config/locales/de.json: -------------------------------------------------------------------------------- 1 | { 2 | "Welcome": "Willkommen", 3 | "A brand new app.": "Eine neue App." 4 | } 5 | -------------------------------------------------------------------------------- /config/locales/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "Welcome": "Welcome", 3 | "A brand new app.": "A brand new app." 4 | } 5 | -------------------------------------------------------------------------------- /assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fraygit/SailsJs-Mysql-Association-Tutorial/HEAD/assets/favicon.ico -------------------------------------------------------------------------------- /config/locales/fr.json: -------------------------------------------------------------------------------- 1 | { 2 | "Welcome": "Bienvenue", 3 | "A brand new app.": "Une toute nouvelle application." 4 | } 5 | -------------------------------------------------------------------------------- /config/locales/es.json: -------------------------------------------------------------------------------- 1 | { 2 | "Welcome": "Bienvenido", 3 | "A brand new app.": "Una aplicación de la nueva marca." 4 | } 5 | -------------------------------------------------------------------------------- /tasks/register/default.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('default', ['compileAssets', 'linkAssets', 'watch']); 3 | }; 4 | -------------------------------------------------------------------------------- /tasks/register/syncAssets.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('syncAssets', [ 3 | 'jst:dev', 4 | 'less:dev', 5 | 'sync:dev', 6 | 'coffee:dev' 7 | ]); 8 | }; 9 | -------------------------------------------------------------------------------- /tasks/register/build.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('build', [ 3 | 'compileAssets', 4 | 'linkAssetsBuild', 5 | 'clean:build', 6 | 'copy:build' 7 | ]); 8 | }; 9 | -------------------------------------------------------------------------------- /tasks/register/compileAssets.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('compileAssets', [ 3 | 'clean:dev', 4 | 'jst:dev', 5 | 'less:dev', 6 | 'copy:dev', 7 | 'coffee:dev' 8 | ]); 9 | }; 10 | -------------------------------------------------------------------------------- /tasks/register/buildProd.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('buildProd', [ 3 | 'compileAssets', 4 | 'concat', 5 | 'uglify', 6 | 'cssmin', 7 | 'linkAssetsBuildProd', 8 | 'clean:build', 9 | 'copy:build' 10 | ]); 11 | }; 12 | -------------------------------------------------------------------------------- /assets/robots.txt: -------------------------------------------------------------------------------- 1 | # The robots.txt file is used to control how search engines index your live URLs. 2 | # See http://www.robotstxt.org/wc/norobots.html for more information. 3 | 4 | 5 | 6 | # To prevent search engines from seeing the site altogether, uncomment the next two lines: 7 | # User-Agent: * 8 | # Disallow: / 9 | -------------------------------------------------------------------------------- /tasks/register/linkAssets.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('linkAssets', [ 3 | 'sails-linker:devJs', 4 | 'sails-linker:devStyles', 5 | 'sails-linker:devTpl', 6 | 'sails-linker:devJsJade', 7 | 'sails-linker:devStylesJade', 8 | 'sails-linker:devTplJade' 9 | ]); 10 | }; 11 | -------------------------------------------------------------------------------- /tasks/register/linkAssetsBuild.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('linkAssetsBuild', [ 3 | 'sails-linker:devJsRelative', 4 | 'sails-linker:devStylesRelative', 5 | 'sails-linker:devTpl', 6 | 'sails-linker:devJsRelativeJade', 7 | 'sails-linker:devStylesRelativeJade', 8 | 'sails-linker:devTplJade' 9 | ]); 10 | }; 11 | -------------------------------------------------------------------------------- /tasks/register/linkAssetsBuildProd.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('linkAssetsBuildProd', [ 3 | 'sails-linker:prodJsRelative', 4 | 'sails-linker:prodStylesRelative', 5 | 'sails-linker:devTpl', 6 | 'sails-linker:prodJsRelativeJade', 7 | 'sails-linker:prodStylesRelativeJade', 8 | 'sails-linker:devTplJade' 9 | ]); 10 | }; 11 | -------------------------------------------------------------------------------- /tasks/register/prod.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | grunt.registerTask('prod', [ 3 | 'compileAssets', 4 | 'concat', 5 | 'uglify', 6 | 'cssmin', 7 | 'sails-linker:prodJs', 8 | 'sails-linker:prodStyles', 9 | 'sails-linker:devTpl', 10 | 'sails-linker:prodJsJade', 11 | 'sails-linker:prodStylesJade', 12 | 'sails-linker:devTplJade' 13 | ]); 14 | }; 15 | -------------------------------------------------------------------------------- /api/models/Customer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Customer.js 3 | * 4 | * @description :: TODO: You might write a short summary of how this model works and what it represents here. 5 | * @docs :: http://sailsjs.org/#!documentation/models 6 | */ 7 | 8 | module.exports = { 9 | 10 | connection: 'someMysqlServer', 11 | 12 | attributes: { 13 | 14 | Name: { 15 | type: 'string', 16 | }, 17 | 18 | store: { 19 | model: 'Store' 20 | } 21 | 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /api/models/Driver.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Driver.js 3 | * 4 | * @description :: TODO: You might write a short summary of how this model works and what it represents here. 5 | * @docs :: http://sailsjs.org/#!documentation/models 6 | */ 7 | 8 | module.exports = { 9 | 10 | connection: 'someMysqlServer', 11 | 12 | attributes: { 13 | Name: { 14 | type: 'string', 15 | }, 16 | 17 | car: { 18 | model: 'Car', 19 | required: false 20 | } 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /api/models/Store.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Store.js 3 | * 4 | * @description :: TODO: You might write a short summary of how this model works and what it represents here. 5 | * @docs :: http://sailsjs.org/#!documentation/models 6 | */ 7 | 8 | module.exports = { 9 | 10 | connection: 'someMysqlServer', 11 | 12 | attributes: { 13 | name: { 14 | type: 'string' 15 | }, 16 | 17 | customers: { 18 | collection: 'Customer', 19 | via: 'store' 20 | } 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /tasks/config/clean.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Clean files and folders. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * This grunt task is configured to clean out the contents in the .tmp/public of your 7 | * sails project. 8 | * 9 | * For usage docs see: 10 | * https://github.com/gruntjs/grunt-contrib-clean 11 | */ 12 | module.exports = function(grunt) { 13 | 14 | grunt.config.set('clean', { 15 | dev: ['.tmp/public/**'], 16 | build: ['www'] 17 | }); 18 | 19 | grunt.loadNpmTasks('grunt-contrib-clean'); 20 | }; 21 | -------------------------------------------------------------------------------- /tasks/config/uglify.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Minify files with UglifyJS. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Minifies client-side javascript `assets`. 7 | * 8 | * For usage docs see: 9 | * https://github.com/gruntjs/grunt-contrib-uglify 10 | * 11 | */ 12 | module.exports = function(grunt) { 13 | 14 | grunt.config.set('uglify', { 15 | dist: { 16 | src: ['.tmp/public/concat/production.js'], 17 | dest: '.tmp/public/min/production.min.js' 18 | } 19 | }); 20 | 21 | grunt.loadNpmTasks('grunt-contrib-uglify'); 22 | }; 23 | -------------------------------------------------------------------------------- /tasks/config/cssmin.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Compress CSS files. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Minifies css files and places them into .tmp/public/min directory. 7 | * 8 | * For usage docs see: 9 | * https://github.com/gruntjs/grunt-contrib-cssmin 10 | */ 11 | module.exports = function(grunt) { 12 | 13 | grunt.config.set('cssmin', { 14 | dist: { 15 | src: ['.tmp/public/concat/production.css'], 16 | dest: '.tmp/public/min/production.min.css' 17 | } 18 | }); 19 | 20 | grunt.loadNpmTasks('grunt-contrib-cssmin'); 21 | }; 22 | -------------------------------------------------------------------------------- /api/models/Car.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Car.js 3 | * 4 | * @description :: TODO: You might write a short summary of how this model works and what it represents here. 5 | * @docs :: http://sailsjs.org/#!documentation/models 6 | */ 7 | 8 | module.exports = { 9 | 10 | connection: 'someMysqlServer', 11 | 12 | attributes: { 13 | Name: { 14 | type: 'string', 15 | }, 16 | 17 | Brand: { 18 | type: 'string' 19 | }, 20 | 21 | Model: { 22 | type: 'string' 23 | }, 24 | 25 | driver: { 26 | model: 'Driver', 27 | required: false 28 | } 29 | } 30 | }; 31 | 32 | -------------------------------------------------------------------------------- /config/bootstrap.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Bootstrap 3 | * (sails.config.bootstrap) 4 | * 5 | * An asynchronous bootstrap function that runs before your Sails app gets lifted. 6 | * This gives you an opportunity to set up your data model, run jobs, or perform some special logic. 7 | * 8 | * For more information on bootstrapping your app, check out: 9 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.bootstrap.html 10 | */ 11 | 12 | module.exports.bootstrap = function(cb) { 13 | 14 | // It's very important to trigger this callback method when you are finished 15 | // with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap) 16 | cb(); 17 | }; 18 | -------------------------------------------------------------------------------- /tasks/config/sync.js: -------------------------------------------------------------------------------- 1 | /** 2 | * A grunt task to keep directories in sync. It is very similar to grunt-contrib-copy 3 | * but tries to copy only those files that has actually changed. 4 | * 5 | * --------------------------------------------------------------- 6 | * 7 | * Synchronize files from the `assets` folder to `.tmp/public`, 8 | * smashing anything that's already there. 9 | * 10 | * For usage docs see: 11 | * https://github.com/tomusdrw/grunt-sync 12 | * 13 | */ 14 | module.exports = function(grunt) { 15 | 16 | grunt.config.set('sync', { 17 | dev: { 18 | files: [{ 19 | cwd: './assets', 20 | src: ['**/*.!(coffee)'], 21 | dest: '.tmp/public' 22 | }] 23 | } 24 | }); 25 | 26 | grunt.loadNpmTasks('grunt-sync'); 27 | }; 28 | -------------------------------------------------------------------------------- /api/policies/sessionAuth.js: -------------------------------------------------------------------------------- 1 | /** 2 | * sessionAuth 3 | * 4 | * @module :: Policy 5 | * @description :: Simple policy to allow any authenticated user 6 | * Assumes that your login action in one of your controllers sets `req.session.authenticated = true;` 7 | * @docs :: http://sailsjs.org/#!documentation/policies 8 | * 9 | */ 10 | module.exports = function(req, res, next) { 11 | 12 | // User is allowed, proceed to the next policy, 13 | // or if this is the last policy, the controller 14 | if (req.session.authenticated) { 15 | return next(); 16 | } 17 | 18 | // User is not allowed 19 | // (default res.forbidden() behavior can be overridden in `config/403.js`) 20 | return res.forbidden('You are not permitted to perform this action.'); 21 | }; 22 | -------------------------------------------------------------------------------- /tasks/config/less.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Compiles LESS files into CSS. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Only the `assets/styles/importer.less` is compiled. 7 | * This allows you to control the ordering yourself, i.e. import your 8 | * dependencies, mixins, variables, resets, etc. before other stylesheets) 9 | * 10 | * For usage docs see: 11 | * https://github.com/gruntjs/grunt-contrib-less 12 | */ 13 | module.exports = function(grunt) { 14 | 15 | grunt.config.set('less', { 16 | dev: { 17 | files: [{ 18 | expand: true, 19 | cwd: 'assets/styles/', 20 | src: ['importer.less'], 21 | dest: '.tmp/public/styles/', 22 | ext: '.css' 23 | }] 24 | } 25 | }); 26 | 27 | grunt.loadNpmTasks('grunt-contrib-less'); 28 | }; 29 | -------------------------------------------------------------------------------- /tasks/config/concat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Concatenate files. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Concatenates files javascript and css from a defined array. Creates concatenated files in 7 | * .tmp/public/contact directory 8 | * [concat](https://github.com/gruntjs/grunt-contrib-concat) 9 | * 10 | * For usage docs see: 11 | * https://github.com/gruntjs/grunt-contrib-concat 12 | */ 13 | module.exports = function(grunt) { 14 | 15 | grunt.config.set('concat', { 16 | js: { 17 | src: require('../pipeline').jsFilesToInject, 18 | dest: '.tmp/public/concat/production.js' 19 | }, 20 | css: { 21 | src: require('../pipeline').cssFilesToInject, 22 | dest: '.tmp/public/concat/production.css' 23 | } 24 | }); 25 | 26 | grunt.loadNpmTasks('grunt-contrib-concat'); 27 | }; 28 | -------------------------------------------------------------------------------- /tasks/config/watch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Run predefined tasks whenever watched file patterns are added, changed or deleted. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Watch for changes on 7 | * - files in the `assets` folder 8 | * - the `tasks/pipeline.js` file 9 | * and re-run the appropriate tasks. 10 | * 11 | * For usage docs see: 12 | * https://github.com/gruntjs/grunt-contrib-watch 13 | * 14 | */ 15 | module.exports = function(grunt) { 16 | 17 | grunt.config.set('watch', { 18 | api: { 19 | 20 | // API files to watch: 21 | files: ['api/**/*'] 22 | }, 23 | assets: { 24 | 25 | // Assets to watch: 26 | files: ['assets/**/*', 'tasks/pipeline.js'], 27 | 28 | // When assets are changed: 29 | tasks: ['syncAssets' , 'linkAssets'] 30 | } 31 | }); 32 | 33 | grunt.loadNpmTasks('grunt-contrib-watch'); 34 | }; 35 | -------------------------------------------------------------------------------- /config/env/development.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Development environment settings 3 | * 4 | * This file can include shared settings for a development team, 5 | * such as API keys or remote database passwords. If you're using 6 | * a version control solution for your Sails app, this file will 7 | * be committed to your repository unless you add it to your .gitignore 8 | * file. If your repository will be publicly viewable, don't add 9 | * any private information to this file! 10 | * 11 | */ 12 | 13 | module.exports = { 14 | 15 | /*************************************************************************** 16 | * Set the default database connection for models in the development * 17 | * environment (see config/connections.js and config/models.js ) * 18 | ***************************************************************************/ 19 | 20 | // models: { 21 | // connection: 'someMongodbServer' 22 | // } 23 | 24 | }; 25 | -------------------------------------------------------------------------------- /tasks/config/coffee.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Compile CoffeeScript files to JavaScript. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Compiles coffeeScript files from `assest/js` into Javascript and places them into 7 | * `.tmp/public/js` directory. 8 | * 9 | * For usage docs see: 10 | * https://github.com/gruntjs/grunt-contrib-coffee 11 | */ 12 | module.exports = function(grunt) { 13 | 14 | grunt.config.set('coffee', { 15 | dev: { 16 | options: { 17 | bare: true, 18 | sourceMap: true, 19 | sourceRoot: './' 20 | }, 21 | files: [{ 22 | expand: true, 23 | cwd: 'assets/js/', 24 | src: ['**/*.coffee'], 25 | dest: '.tmp/public/js/', 26 | ext: '.js' 27 | }, { 28 | expand: true, 29 | cwd: 'assets/js/', 30 | src: ['**/*.coffee'], 31 | dest: '.tmp/public/js/', 32 | ext: '.js' 33 | }] 34 | } 35 | }); 36 | 37 | grunt.loadNpmTasks('grunt-contrib-coffee'); 38 | }; 39 | -------------------------------------------------------------------------------- /tasks/config/copy.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copy files and folders. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * # dev task config 7 | * Copies all directories and files, exept coffescript and less fiels, from the sails 8 | * assets folder into the .tmp/public directory. 9 | * 10 | * # build task config 11 | * Copies all directories nd files from the .tmp/public directory into a www directory. 12 | * 13 | * For usage docs see: 14 | * https://github.com/gruntjs/grunt-contrib-copy 15 | */ 16 | module.exports = function(grunt) { 17 | 18 | grunt.config.set('copy', { 19 | dev: { 20 | files: [{ 21 | expand: true, 22 | cwd: './assets', 23 | src: ['**/*.!(coffee|less)'], 24 | dest: '.tmp/public' 25 | }] 26 | }, 27 | build: { 28 | files: [{ 29 | expand: true, 30 | cwd: '.tmp/public', 31 | src: ['**/*'], 32 | dest: 'www' 33 | }] 34 | } 35 | }); 36 | 37 | grunt.loadNpmTasks('grunt-contrib-copy'); 38 | }; 39 | -------------------------------------------------------------------------------- /assets/styles/importer.less: -------------------------------------------------------------------------------- 1 | /** 2 | * importer.less 3 | * 4 | * By default, new Sails projects are configured to compile this file 5 | * from LESS to CSS. Unlike CSS files, LESS files are not compiled and 6 | * included automatically unless they are imported below. 7 | * 8 | * The LESS files imported below are compiled and included in the order 9 | * they are listed. Mixins, variables, etc. should be imported first 10 | * so that they can be accessed by subsequent LESS stylesheets. 11 | * 12 | * (Just like the rest of the asset pipeline bundled in Sails, you can 13 | * always omit, customize, or replace this behavior with SASS, SCSS, 14 | * or any other Grunt tasks you like.) 15 | */ 16 | 17 | 18 | 19 | // For example: 20 | // 21 | // @import 'variables/colors.less'; 22 | // @import 'mixins/foo.less'; 23 | // @import 'mixins/bar.less'; 24 | // @import 'mixins/baz.less'; 25 | // 26 | // @import 'styleguide.less'; 27 | // @import 'pages/login.less'; 28 | // @import 'pages/signup.less'; 29 | // 30 | // etc. 31 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Tutorial", 3 | "private": true, 4 | "version": "0.0.0", 5 | "description": "a Sails application", 6 | "keywords": [], 7 | "dependencies": { 8 | "sails": "~0.10.5", 9 | "sails-disk": "~0.10.0", 10 | "rc": "~0.5.0", 11 | "include-all": "~0.1.3", 12 | "ejs": "~0.8.4", 13 | "grunt": "0.4.2", 14 | "grunt-sync": "~0.0.4", 15 | "grunt-contrib-copy": "~0.5.0", 16 | "grunt-contrib-clean": "~0.5.0", 17 | "grunt-contrib-concat": "~0.3.0", 18 | "grunt-sails-linker": "~0.9.5", 19 | "grunt-contrib-jst": "~0.6.0", 20 | "grunt-contrib-watch": "~0.5.3", 21 | "grunt-contrib-uglify": "~0.4.0", 22 | "grunt-contrib-cssmin": "~0.9.0", 23 | "grunt-contrib-less": "0.11.1", 24 | "grunt-contrib-coffee": "~0.10.1" 25 | }, 26 | "scripts": { 27 | "start": "node app.js", 28 | "debug": "node debug app.js" 29 | }, 30 | "main": "app.js", 31 | "repository": { 32 | "type": "git", 33 | "url": "git://github.com/anonymous node/sails user/Tutorial.git" 34 | }, 35 | "author": "anonymous node/sails user", 36 | "license": "" 37 | } -------------------------------------------------------------------------------- /config/locales/_README.md: -------------------------------------------------------------------------------- 1 | # Internationalization / Localization Settings 2 | 3 | > Also see the official docs on internationalization/localization: 4 | > http://links.sailsjs.org/docs/config/locales 5 | 6 | ## Locales 7 | All locale files live under `config/locales`. Here is where you can add translations 8 | as JSON key-value pairs. The name of the file should match the language that you are supporting, which allows for automatic language detection based on request headers. 9 | 10 | Here is an example locale stringfile for the Spanish language (`config/locales/es.json`): 11 | ```json 12 | { 13 | "Hello!": "Hola!", 14 | "Hello %s, how are you today?": "¿Hola %s, como estas?", 15 | } 16 | ``` 17 | ## Usage 18 | Locales can be accessed in controllers/policies through `res.i18n()`, or in views through the `__(key)` or `i18n(key)` functions. 19 | Remember that the keys are case sensitive and require exact key matches, e.g. 20 | 21 | ```ejs 22 |

<%= __('Welcome to PencilPals!') %>

23 |

<%= i18n('Hello %s, how are you today?', 'Pencil Maven') %>

24 |

<%= i18n('That\'s right-- you can use either i18n() or __()') %>

25 | ``` 26 | 27 | ## Configuration 28 | Localization/internationalization config can be found in `config/i18n.js`, from where you can set your supported locales. 29 | -------------------------------------------------------------------------------- /config/log.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Built-in Log Configuration 3 | * (sails.config.log) 4 | * 5 | * Configure the log level for your app, as well as the transport 6 | * (Underneath the covers, Sails uses Winston for logging, which 7 | * allows for some pretty neat custom transports/adapters for log messages) 8 | * 9 | * For more information on the Sails logger, check out: 10 | * http://sailsjs.org/#/documentation/concepts/Logging 11 | */ 12 | 13 | module.exports.log = { 14 | 15 | /*************************************************************************** 16 | * * 17 | * Valid `level` configs: i.e. the minimum log level to capture with * 18 | * sails.log.*() * 19 | * * 20 | * The order of precedence for log levels from lowest to highest is: * 21 | * silly, verbose, info, debug, warn, error * 22 | * * 23 | * You may also set the level to "silent" to suppress all logs. * 24 | * * 25 | ***************************************************************************/ 26 | 27 | // level: 'info' 28 | 29 | }; 30 | -------------------------------------------------------------------------------- /api/responses/ok.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 200 (OK) Response 3 | * 4 | * Usage: 5 | * return res.ok(); 6 | * return res.ok(data); 7 | * return res.ok(data, 'auth/login'); 8 | * 9 | * @param {Object} data 10 | * @param {String|Object} options 11 | * - pass string to render specified view 12 | */ 13 | 14 | module.exports = function sendOK (data, options) { 15 | 16 | // Get access to `req`, `res`, & `sails` 17 | var req = this.req; 18 | var res = this.res; 19 | var sails = req._sails; 20 | 21 | sails.log.silly('res.ok() :: Sending 200 ("OK") response'); 22 | 23 | // Set status code 24 | res.status(200); 25 | 26 | // If appropriate, serve data as JSON(P) 27 | if (req.wantsJSON) { 28 | return res.jsonx(data); 29 | } 30 | 31 | // If second argument is a string, we take that to mean it refers to a view. 32 | // If it was omitted, use an empty object (`{}`) 33 | options = (typeof options === 'string') ? { view: options } : options || {}; 34 | 35 | // If a view was provided in options, serve it. 36 | // Otherwise try to guess an appropriate view, or if that doesn't 37 | // work, just send JSON. 38 | if (options.view) { 39 | return res.view(options.view, { data: data }); 40 | } 41 | 42 | // If no second argument provided, try to serve the implied view, 43 | // but fall back to sending JSON(P) if no view can be inferred. 44 | else return res.guessView({ data: data }, function couldNotGuessView () { 45 | return res.jsonx(data); 46 | }); 47 | 48 | }; 49 | -------------------------------------------------------------------------------- /tasks/config/jst.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Precompiles Underscore templates to a `.jst` file. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * (i.e. basically it takes HTML files and turns them into tiny little 7 | * javascript functions that you pass data to and return HTML. This can 8 | * speed up template rendering on the client, and reduce bandwidth usage.) 9 | * 10 | * For usage docs see: 11 | * https://github.com/gruntjs/grunt-contrib-jst 12 | * 13 | */ 14 | 15 | module.exports = function(grunt) { 16 | 17 | var templateFilesToInject = [ 18 | 'templates/**/*.html' 19 | ]; 20 | 21 | grunt.config.set('jst', { 22 | dev: { 23 | 24 | // To use other sorts of templates, specify a regexp like the example below: 25 | // options: { 26 | // templateSettings: { 27 | // interpolate: /\{\{(.+?)\}\}/g 28 | // } 29 | // }, 30 | 31 | // Note that the interpolate setting above is simply an example of overwriting lodash's 32 | // default interpolation. If you want to parse templates with the default _.template behavior 33 | // (i.e. using
), there's no need to overwrite `templateSettings.interpolate`. 34 | 35 | 36 | files: { 37 | // e.g. 38 | // 'relative/path/from/gruntfile/to/compiled/template/destination' : ['relative/path/to/sourcefiles/**/*.html'] 39 | '.tmp/public/jst.js': require('../pipeline').templateFilesToInject 40 | } 41 | } 42 | }); 43 | 44 | grunt.loadNpmTasks('grunt-contrib-jst'); 45 | }; 46 | -------------------------------------------------------------------------------- /api/controllers/CarController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * CarController 3 | * 4 | * @description :: Server-side logic for managing Cars 5 | * @help :: See http://links.sailsjs.org/docs/controllers 6 | */ 7 | 8 | module.exports = { 9 | 10 | add: function(req, res){ 11 | var driver = {Name: 'Juan'}; 12 | Driver.create(driver).exec(function(err, result){ 13 | Car.create({ 14 | Name: 'My Car', 15 | Brand: 'Honda', 16 | Model: 'Civic', 17 | driver: result.id 18 | }).exec(function (e, r){ 19 | Driver.update({id: result.id}, {car: r.id}).exec(function(e1, r1){ 20 | return res.json({result: r, error: e}); 21 | }); 22 | }); 23 | }); 24 | }, 25 | 26 | viewCar: function(req, res){ 27 | Car.find().populate('driver').exec(function(e, r){ 28 | return res.json({Car: r}); 29 | }); 30 | }, 31 | 32 | viewDriver: function(req, res){ 33 | Driver.find().populate('car').exec(function(e, r){ 34 | return res.json({Car: r}); 35 | }); 36 | }, 37 | 38 | addStoreCustomer: function(req, res){ 39 | Store.create({Name: 'Sari Sari Store'}).exec(function(e,r){ 40 | Customer.create({Name: 'Pedro', store: r.id}).exec(function(err, result){ 41 | Customer.create({Name: 'Juan', store: r.id}).exec(function(err1, res1){ 42 | return res.json({ok: 'success'}); 43 | }); 44 | }); 45 | }); 46 | }, 47 | 48 | viewStore: function(req, res){ 49 | Store.find().populate('customers').exec(function (err, result){ 50 | res.json({Result: result}); 51 | }); 52 | } 53 | 54 | }; 55 | 56 | -------------------------------------------------------------------------------- /config/env/production.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Production environment settings 3 | * 4 | * This file can include shared settings for a production environment, 5 | * such as API keys or remote database passwords. If you're using 6 | * a version control solution for your Sails app, this file will 7 | * be committed to your repository unless you add it to your .gitignore 8 | * file. If your repository will be publicly viewable, don't add 9 | * any private information to this file! 10 | * 11 | */ 12 | 13 | module.exports = { 14 | 15 | /*************************************************************************** 16 | * Set the default database connection for models in the production * 17 | * environment (see config/connections.js and config/models.js ) * 18 | ***************************************************************************/ 19 | 20 | // models: { 21 | // connection: 'someMysqlServer' 22 | // }, 23 | 24 | /*************************************************************************** 25 | * Set the port in the production environment to 80 * 26 | ***************************************************************************/ 27 | 28 | // port: 80, 29 | 30 | /*************************************************************************** 31 | * Set the log level in production environment to "silent" * 32 | ***************************************************************************/ 33 | 34 | // log: { 35 | // level: "silent" 36 | // } 37 | 38 | }; 39 | -------------------------------------------------------------------------------- /config/models.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Default model configuration 3 | * (sails.config.models) 4 | * 5 | * Unless you override them, the following properties will be included 6 | * in each of your models. 7 | * 8 | * For more info on Sails models, see: 9 | * http://sailsjs.org/#/documentation/concepts/ORM 10 | */ 11 | 12 | module.exports.models = { 13 | 14 | /*************************************************************************** 15 | * * 16 | * Your app's default connection. i.e. the name of one of your app's * 17 | * connections (see `config/connections.js`) * 18 | * * 19 | ***************************************************************************/ 20 | // connection: 'localDiskDb', 21 | 22 | /*************************************************************************** 23 | * * 24 | * How and whether Sails will attempt to automatically rebuild the * 25 | * tables/collections/etc. in your schema. * 26 | * * 27 | * See http://sailsjs.org/#/documentation/concepts/ORM/model-settings.html * 28 | * * 29 | ***************************************************************************/ 30 | // migrate: 'alter' 31 | 32 | }; 33 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | /** 2 | * app.js 3 | * 4 | * Use `app.js` to run your app without `sails lift`. 5 | * To start the server, run: `node app.js`. 6 | * 7 | * This is handy in situations where the sails CLI is not relevant or useful. 8 | * 9 | * For example: 10 | * => `node app.js` 11 | * => `forever start app.js` 12 | * => `node debug app.js` 13 | * => `modulus deploy` 14 | * => `heroku scale` 15 | * 16 | * 17 | * The same command-line arguments are supported, e.g.: 18 | * `node app.js --silent --port=80 --prod` 19 | */ 20 | 21 | // Ensure a "sails" can be located: 22 | (function() { 23 | var sails; 24 | try { 25 | sails = require('sails'); 26 | } catch (e) { 27 | console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.'); 28 | console.error('To do that, run `npm install sails`'); 29 | console.error(''); 30 | console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.'); 31 | console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,'); 32 | console.error('but if it doesn\'t, the app will run with the global sails instead!'); 33 | return; 34 | } 35 | 36 | // Try to get `rc` dependency 37 | var rc; 38 | try { 39 | rc = require('rc'); 40 | } catch (e0) { 41 | try { 42 | rc = require('sails/node_modules/rc'); 43 | } catch (e1) { 44 | console.error('Could not find dependency: `rc`.'); 45 | console.error('Your `.sailsrc` file(s) will be ignored.'); 46 | console.error('To resolve this, run:'); 47 | console.error('npm install rc --save'); 48 | rc = function () { return {}; }; 49 | } 50 | } 51 | 52 | 53 | // Start server 54 | sails.lift(rc('sails')); 55 | })(); 56 | -------------------------------------------------------------------------------- /api/responses/badRequest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 400 (Bad Request) Handler 3 | * 4 | * Usage: 5 | * return res.badRequest(); 6 | * return res.badRequest(data); 7 | * return res.badRequest(data, 'some/specific/badRequest/view'); 8 | * 9 | * e.g.: 10 | * ``` 11 | * return res.badRequest( 12 | * 'Please choose a valid `password` (6-12 characters)', 13 | * 'trial/signup' 14 | * ); 15 | * ``` 16 | */ 17 | 18 | module.exports = function badRequest(data, options) { 19 | 20 | // Get access to `req`, `res`, & `sails` 21 | var req = this.req; 22 | var res = this.res; 23 | var sails = req._sails; 24 | 25 | // Set status code 26 | res.status(400); 27 | 28 | // Log error to console 29 | if (data !== undefined) { 30 | sails.log.verbose('Sending 400 ("Bad Request") response: \n',data); 31 | } 32 | else sails.log.verbose('Sending 400 ("Bad Request") response'); 33 | 34 | // Only include errors in response if application environment 35 | // is not set to 'production'. In production, we shouldn't 36 | // send back any identifying information about errors. 37 | if (sails.config.environment === 'production') { 38 | data = undefined; 39 | } 40 | 41 | // If the user-agent wants JSON, always respond with JSON 42 | if (req.wantsJSON) { 43 | return res.jsonx(data); 44 | } 45 | 46 | // If second argument is a string, we take that to mean it refers to a view. 47 | // If it was omitted, use an empty object (`{}`) 48 | options = (typeof options === 'string') ? { view: options } : options || {}; 49 | 50 | // If a view was provided in options, serve it. 51 | // Otherwise try to guess an appropriate view, or if that doesn't 52 | // work, just send JSON. 53 | if (options.view) { 54 | return res.view(options.view, { data: data }); 55 | } 56 | 57 | // If no second argument provided, try to serve the implied view, 58 | // but fall back to sending JSON(P) if no view can be inferred. 59 | else return res.guessView({ data: data }, function couldNotGuessView () { 60 | return res.jsonx(data); 61 | }); 62 | 63 | }; 64 | 65 | -------------------------------------------------------------------------------- /tasks/pipeline.js: -------------------------------------------------------------------------------- 1 | /** 2 | * grunt/pipeline.js 3 | * 4 | * The order in which your css, javascript, and template files should be 5 | * compiled and linked from your views and static HTML files. 6 | * 7 | * (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions 8 | * for matching multiple files.) 9 | */ 10 | 11 | 12 | 13 | // CSS files to inject in order 14 | // 15 | // (if you're using LESS with the built-in default config, you'll want 16 | // to change `assets/styles/importer.less` instead.) 17 | var cssFilesToInject = [ 18 | 'styles/**/*.css' 19 | ]; 20 | 21 | 22 | // Client-side javascript files to inject in order 23 | // (uses Grunt-style wildcard/glob/splat expressions) 24 | var jsFilesToInject = [ 25 | 26 | // Load sails.io before everything else 27 | 'js/dependencies/sails.io.js', 28 | 29 | // Dependencies like jQuery, or Angular are brought in here 30 | 'js/dependencies/**/*.js', 31 | 32 | // All of the rest of your client-side js files 33 | // will be injected here in no particular order. 34 | 'js/**/*.js' 35 | ]; 36 | 37 | 38 | // Client-side HTML templates are injected using the sources below 39 | // The ordering of these templates shouldn't matter. 40 | // (uses Grunt-style wildcard/glob/splat expressions) 41 | // 42 | // By default, Sails uses JST templates and precompiles them into 43 | // functions for you. If you want to use jade, handlebars, dust, etc., 44 | // with the linker, no problem-- you'll just want to make sure the precompiled 45 | // templates get spit out to the same file. Be sure and check out `tasks/README.md` 46 | // for information on customizing and installing new tasks. 47 | var templateFilesToInject = [ 48 | 'templates/**/*.html' 49 | ]; 50 | 51 | 52 | 53 | // Prefix relative paths to source files so they point to the proper locations 54 | // (i.e. where the other Grunt tasks spit them out, or in some cases, where 55 | // they reside in the first place) 56 | module.exports.cssFilesToInject = cssFilesToInject.map(function(path) { 57 | return '.tmp/public/' + path; 58 | }); 59 | module.exports.jsFilesToInject = jsFilesToInject.map(function(path) { 60 | return '.tmp/public/' + path; 61 | }); 62 | module.exports.templateFilesToInject = templateFilesToInject.map(function(path) { 63 | return 'assets/' + path; 64 | }); 65 | -------------------------------------------------------------------------------- /config/policies.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Policy Mappings 3 | * (sails.config.policies) 4 | * 5 | * Policies are simple functions which run **before** your controllers. 6 | * You can apply one or more policies to a given controller, or protect 7 | * its actions individually. 8 | * 9 | * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed 10 | * below by its filename, minus the extension, (e.g. "authenticated") 11 | * 12 | * For more information on how policies work, see: 13 | * http://sailsjs.org/#/documentation/concepts/Policies 14 | * 15 | * For more information on configuring policies, check out: 16 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.policies.html 17 | */ 18 | 19 | 20 | module.exports.policies = { 21 | 22 | /*************************************************************************** 23 | * * 24 | * Default policy for all controllers and actions (`true` allows public * 25 | * access) * 26 | * * 27 | ***************************************************************************/ 28 | 29 | // '*': true, 30 | 31 | /*************************************************************************** 32 | * * 33 | * Here's an example of mapping some policies to run before a controller * 34 | * and its actions * 35 | * * 36 | ***************************************************************************/ 37 | // RabbitController: { 38 | 39 | // Apply the `false` policy as the default for all of RabbitController's actions 40 | // (`false` prevents all access, which ensures that nothing bad happens to our rabbits) 41 | // '*': false, 42 | 43 | // For the action `nurture`, apply the 'isRabbitMother' policy 44 | // (this overrides `false` above) 45 | // nurture : 'isRabbitMother', 46 | 47 | // Apply the `isNiceToAnimals` AND `hasRabbitFood` policies 48 | // before letting any users feed our rabbits 49 | // feed : ['isNiceToAnimals', 'hasRabbitFood'] 50 | // } 51 | }; 52 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Gruntfile 3 | * 4 | * This Node script is executed when you run `grunt` or `sails lift`. 5 | * It's purpose is to load the Grunt tasks in your project's `tasks` 6 | * folder, and allow you to add and remove tasks as you see fit. 7 | * For more information on how this works, check out the `README.md` 8 | * file that was generated in your `tasks` folder. 9 | * 10 | * WARNING: 11 | * Unless you know what you're doing, you shouldn't change this file. 12 | * Check out the `tasks` directory instead. 13 | */ 14 | 15 | module.exports = function(grunt) { 16 | 17 | 18 | // Load the include-all library in order to require all of our grunt 19 | // configurations and task registrations dynamically. 20 | var includeAll; 21 | try { 22 | includeAll = require('include-all'); 23 | } catch (e0) { 24 | try { 25 | includeAll = require('sails/node_modules/include-all'); 26 | } 27 | catch(e1) { 28 | console.error('Could not find `include-all` module.'); 29 | console.error('Skipping grunt tasks...'); 30 | console.error('To fix this, please run:'); 31 | console.error('npm install include-all --save`'); 32 | console.error(); 33 | 34 | grunt.registerTask('default', []); 35 | return; 36 | } 37 | } 38 | 39 | 40 | /** 41 | * Loads Grunt configuration modules from the specified 42 | * relative path. These modules should export a function 43 | * that, when run, should either load/configure or register 44 | * a Grunt task. 45 | */ 46 | function loadTasks(relPath) { 47 | return includeAll({ 48 | dirname: require('path').resolve(__dirname, relPath), 49 | filter: /(.+)\.js$/ 50 | }) || {}; 51 | } 52 | 53 | /** 54 | * Invokes the function from a Grunt configuration module with 55 | * a single argument - the `grunt` object. 56 | */ 57 | function invokeConfigFn(tasks) { 58 | for (var taskName in tasks) { 59 | if (tasks.hasOwnProperty(taskName)) { 60 | tasks[taskName](grunt); 61 | } 62 | } 63 | } 64 | 65 | 66 | 67 | 68 | // Load task functions 69 | var taskConfigurations = loadTasks('./tasks/config'), 70 | registerDefinitions = loadTasks('./tasks/register'); 71 | 72 | // (ensure that a default task exists) 73 | if (!registerDefinitions.default) { 74 | registerDefinitions.default = function (grunt) { grunt.registerTask('default', []); }; 75 | } 76 | 77 | // Run task functions to configure Grunt. 78 | invokeConfigFn(taskConfigurations); 79 | invokeConfigFn(registerDefinitions); 80 | 81 | }; 82 | -------------------------------------------------------------------------------- /config/routes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Route Mappings 3 | * (sails.config.routes) 4 | * 5 | * Your routes map URLs to views and controllers. 6 | * 7 | * If Sails receives a URL that doesn't match any of the routes below, 8 | * it will check for matching files (images, scripts, stylesheets, etc.) 9 | * in your assets directory. e.g. `http://localhost:1337/images/foo.jpg` 10 | * might match an image file: `/assets/images/foo.jpg` 11 | * 12 | * Finally, if those don't match either, the default 404 handler is triggered. 13 | * See `api/responses/notFound.js` to adjust your app's 404 logic. 14 | * 15 | * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies 16 | * flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or 17 | * CoffeeScript for the front-end. 18 | * 19 | * For more information on configuring custom routes, check out: 20 | * http://sailsjs.org/#/documentation/concepts/Routes/RouteTargetSyntax.html 21 | */ 22 | 23 | module.exports.routes = { 24 | 25 | /*************************************************************************** 26 | * * 27 | * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, * 28 | * etc. depending on your default view engine) your home page. * 29 | * * 30 | * (Alternatively, remove this and add an `index.html` file in your * 31 | * `assets` directory) * 32 | * * 33 | ***************************************************************************/ 34 | 35 | '/': { 36 | view: 'homepage' 37 | } 38 | 39 | /*************************************************************************** 40 | * * 41 | * Custom routes here... * 42 | * * 43 | * If a request to a URL doesn't match any of the custom routes above, it * 44 | * is matched against Sails route blueprints. See `config/blueprints.js` * 45 | * for configuration options and examples. * 46 | * * 47 | ***************************************************************************/ 48 | 49 | }; 50 | -------------------------------------------------------------------------------- /api/responses/forbidden.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 403 (Forbidden) Handler 3 | * 4 | * Usage: 5 | * return res.forbidden(); 6 | * return res.forbidden(err); 7 | * return res.forbidden(err, 'some/specific/forbidden/view'); 8 | * 9 | * e.g.: 10 | * ``` 11 | * return res.forbidden('Access denied.'); 12 | * ``` 13 | */ 14 | 15 | module.exports = function forbidden (data, options) { 16 | 17 | // Get access to `req`, `res`, & `sails` 18 | var req = this.req; 19 | var res = this.res; 20 | var sails = req._sails; 21 | 22 | // Set status code 23 | res.status(403); 24 | 25 | // Log error to console 26 | if (data !== undefined) { 27 | sails.log.verbose('Sending 403 ("Forbidden") response: \n',data); 28 | } 29 | else sails.log.verbose('Sending 403 ("Forbidden") response'); 30 | 31 | // Only include errors in response if application environment 32 | // is not set to 'production'. In production, we shouldn't 33 | // send back any identifying information about errors. 34 | if (sails.config.environment === 'production') { 35 | data = undefined; 36 | } 37 | 38 | // If the user-agent wants JSON, always respond with JSON 39 | if (req.wantsJSON) { 40 | return res.jsonx(data); 41 | } 42 | 43 | // If second argument is a string, we take that to mean it refers to a view. 44 | // If it was omitted, use an empty object (`{}`) 45 | options = (typeof options === 'string') ? { view: options } : options || {}; 46 | 47 | // If a view was provided in options, serve it. 48 | // Otherwise try to guess an appropriate view, or if that doesn't 49 | // work, just send JSON. 50 | if (options.view) { 51 | return res.view(options.view, { data: data }); 52 | } 53 | 54 | // If no second argument provided, try to serve the default view, 55 | // but fall back to sending JSON(P) if any errors occur. 56 | else return res.view('403', { data: data }, function (err, html) { 57 | 58 | // If a view error occured, fall back to JSON(P). 59 | if (err) { 60 | // 61 | // Additionally: 62 | // • If the view was missing, ignore the error but provide a verbose log. 63 | if (err.code === 'E_VIEW_FAILED') { 64 | sails.log.verbose('res.forbidden() :: Could not locate view for error page (sending JSON instead). Details: ',err); 65 | } 66 | // Otherwise, if this was a more serious error, log to the console with the details. 67 | else { 68 | sails.log.warn('res.forbidden() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); 69 | } 70 | return res.jsonx(data); 71 | } 72 | 73 | return res.send(html); 74 | }); 75 | 76 | }; 77 | 78 | -------------------------------------------------------------------------------- /api/responses/serverError.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 500 (Server Error) Response 3 | * 4 | * Usage: 5 | * return res.serverError(); 6 | * return res.serverError(err); 7 | * return res.serverError(err, 'some/specific/error/view'); 8 | * 9 | * NOTE: 10 | * If something throws in a policy or controller, or an internal 11 | * error is encountered, Sails will call `res.serverError()` 12 | * automatically. 13 | */ 14 | 15 | module.exports = function serverError (data, options) { 16 | 17 | // Get access to `req`, `res`, & `sails` 18 | var req = this.req; 19 | var res = this.res; 20 | var sails = req._sails; 21 | 22 | // Set status code 23 | res.status(500); 24 | 25 | // Log error to console 26 | if (data !== undefined) { 27 | sails.log.error('Sending 500 ("Server Error") response: \n',data); 28 | } 29 | else sails.log.error('Sending empty 500 ("Server Error") response'); 30 | 31 | // Only include errors in response if application environment 32 | // is not set to 'production'. In production, we shouldn't 33 | // send back any identifying information about errors. 34 | if (sails.config.environment === 'production') { 35 | data = undefined; 36 | } 37 | 38 | // If the user-agent wants JSON, always respond with JSON 39 | if (req.wantsJSON) { 40 | return res.jsonx(data); 41 | } 42 | 43 | // If second argument is a string, we take that to mean it refers to a view. 44 | // If it was omitted, use an empty object (`{}`) 45 | options = (typeof options === 'string') ? { view: options } : options || {}; 46 | 47 | // If a view was provided in options, serve it. 48 | // Otherwise try to guess an appropriate view, or if that doesn't 49 | // work, just send JSON. 50 | if (options.view) { 51 | return res.view(options.view, { data: data }); 52 | } 53 | 54 | // If no second argument provided, try to serve the default view, 55 | // but fall back to sending JSON(P) if any errors occur. 56 | else return res.view('500', { data: data }, function (err, html) { 57 | 58 | // If a view error occured, fall back to JSON(P). 59 | if (err) { 60 | // 61 | // Additionally: 62 | // • If the view was missing, ignore the error but provide a verbose log. 63 | if (err.code === 'E_VIEW_FAILED') { 64 | sails.log.verbose('res.serverError() :: Could not locate view for error page (sending JSON instead). Details: ',err); 65 | } 66 | // Otherwise, if this was a more serious error, log to the console with the details. 67 | else { 68 | sails.log.warn('res.serverError() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); 69 | } 70 | return res.jsonx(data); 71 | } 72 | 73 | return res.send(html); 74 | }); 75 | 76 | }; 77 | 78 | -------------------------------------------------------------------------------- /api/responses/notFound.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 404 (Not Found) Handler 3 | * 4 | * Usage: 5 | * return res.notFound(); 6 | * return res.notFound(err); 7 | * return res.notFound(err, 'some/specific/notfound/view'); 8 | * 9 | * e.g.: 10 | * ``` 11 | * return res.notFound(); 12 | * ``` 13 | * 14 | * NOTE: 15 | * If a request doesn't match any explicit routes (i.e. `config/routes.js`) 16 | * or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()` 17 | * automatically. 18 | */ 19 | 20 | module.exports = function notFound (data, options) { 21 | 22 | // Get access to `req`, `res`, & `sails` 23 | var req = this.req; 24 | var res = this.res; 25 | var sails = req._sails; 26 | 27 | // Set status code 28 | res.status(404); 29 | 30 | // Log error to console 31 | if (data !== undefined) { 32 | sails.log.verbose('Sending 404 ("Not Found") response: \n',data); 33 | } 34 | else sails.log.verbose('Sending 404 ("Not Found") response'); 35 | 36 | // Only include errors in response if application environment 37 | // is not set to 'production'. In production, we shouldn't 38 | // send back any identifying information about errors. 39 | if (sails.config.environment === 'production') { 40 | data = undefined; 41 | } 42 | 43 | // If the user-agent wants JSON, always respond with JSON 44 | if (req.wantsJSON) { 45 | return res.jsonx(data); 46 | } 47 | 48 | // If second argument is a string, we take that to mean it refers to a view. 49 | // If it was omitted, use an empty object (`{}`) 50 | options = (typeof options === 'string') ? { view: options } : options || {}; 51 | 52 | // If a view was provided in options, serve it. 53 | // Otherwise try to guess an appropriate view, or if that doesn't 54 | // work, just send JSON. 55 | if (options.view) { 56 | return res.view(options.view, { data: data }); 57 | } 58 | 59 | // If no second argument provided, try to serve the default view, 60 | // but fall back to sending JSON(P) if any errors occur. 61 | else return res.view('404', { data: data }, function (err, html) { 62 | 63 | // If a view error occured, fall back to JSON(P). 64 | if (err) { 65 | // 66 | // Additionally: 67 | // • If the view was missing, ignore the error but provide a verbose log. 68 | if (err.code === 'E_VIEW_FAILED') { 69 | sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead). Details: ',err); 70 | } 71 | // Otherwise, if this was a more serious error, log to the console with the details. 72 | else { 73 | sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); 74 | } 75 | return res.jsonx(data); 76 | } 77 | 78 | return res.send(html); 79 | }); 80 | 81 | }; 82 | 83 | -------------------------------------------------------------------------------- /config/i18n.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Internationalization / Localization Settings 3 | * (sails.config.i18n) 4 | * 5 | * If your app will touch people from all over the world, i18n (or internationalization) 6 | * may be an important part of your international strategy. 7 | * 8 | * 9 | * For more informationom i18n in Sails, check out: 10 | * http://sailsjs.org/#/documentation/concepts/Internationalization 11 | * 12 | * For a complete list of i18n options, see: 13 | * https://github.com/mashpie/i18n-node#list-of-configuration-options 14 | * 15 | * 16 | */ 17 | 18 | module.exports.i18n = { 19 | 20 | /*************************************************************************** 21 | * * 22 | * Which locales are supported? * 23 | * * 24 | ***************************************************************************/ 25 | 26 | // locales: ['en', 'es', 'fr', 'de'] 27 | 28 | /**************************************************************************** 29 | * * 30 | * What is the default locale for the site? Note that this setting will be * 31 | * overridden for any request that sends an "Accept-Language" header (i.e. * 32 | * most browsers), but it's still useful if you need to localize the * 33 | * response for requests made by non-browser clients (e.g. cURL). * 34 | * * 35 | ****************************************************************************/ 36 | 37 | // defaultLocale: 'en', 38 | 39 | /**************************************************************************** 40 | * * 41 | * Automatically add new keys to locale (translation) files when they are * 42 | * encountered during a request? * 43 | * * 44 | ****************************************************************************/ 45 | 46 | // updateFiles: false, 47 | 48 | /**************************************************************************** 49 | * * 50 | * Path (relative to app root) of directory to store locale (translation) * 51 | * files in. * 52 | * * 53 | ****************************************************************************/ 54 | 55 | // localesDirectory: '/config/locales' 56 | 57 | }; 58 | -------------------------------------------------------------------------------- /config/csrf.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Cross-Site Request Forgery Protection Settings 3 | * (sails.config.csrf) 4 | * 5 | * CSRF tokens are like a tracking chip. While a session tells the server that a user 6 | * "is who they say they are", a csrf token tells the server "you are where you say you are". 7 | * 8 | * When enabled, all non-GET requests to the Sails server must be accompanied by 9 | * a special token, identified as the '_csrf' parameter. 10 | * 11 | * This option protects your Sails app against cross-site request forgery (or CSRF) attacks. 12 | * A would-be attacker needs not only a user's session cookie, but also this timestamped, 13 | * secret CSRF token, which is refreshed/granted when the user visits a URL on your app's domain. 14 | * 15 | * This allows us to have certainty that our users' requests haven't been hijacked, 16 | * and that the requests they're making are intentional and legitimate. 17 | * 18 | * This token has a short-lived expiration timeline, and must be acquired by either: 19 | * 20 | * (a) For traditional view-driven web apps: 21 | * Fetching it from one of your views, where it may be accessed as 22 | * a local variable, e.g.: 23 | *
24 | * 25 | *
26 | * 27 | * or (b) For AJAX/Socket-heavy and/or single-page apps: 28 | * Sending a GET request to the `/csrfToken` route, where it will be returned 29 | * as JSON, e.g.: 30 | * { _csrf: 'ajg4JD(JGdajhLJALHDa' } 31 | * 32 | * 33 | * Enabling this option requires managing the token in your front-end app. 34 | * For traditional web apps, it's as easy as passing the data from a view into a form action. 35 | * In AJAX/Socket-heavy apps, just send a GET request to the /csrfToken route to get a valid token. 36 | * 37 | * For more information on CSRF, check out: 38 | * http://en.wikipedia.org/wiki/Cross-site_request_forgery 39 | * 40 | * For more information on this configuration file, including info on CSRF + CORS, see: 41 | * http://beta.sailsjs.org/#/documentation/reference/sails.config/sails.config.csrf.html 42 | * 43 | */ 44 | 45 | /**************************************************************************** 46 | * * 47 | * Enabled CSRF protection for your site? * 48 | * * 49 | ****************************************************************************/ 50 | 51 | // module.exports.csrf = false; 52 | 53 | /**************************************************************************** 54 | * * 55 | * You may also specify more fine-grained settings for CSRF, including the * 56 | * domains which are allowed to request the CSRF token via AJAX. These * 57 | * settings override the general CORS settings in your config/cors.js file. * 58 | * * 59 | ****************************************************************************/ 60 | 61 | // module.exports.csrf = { 62 | // grantTokenViaAjax: true, 63 | // origin: '' 64 | // } 65 | -------------------------------------------------------------------------------- /tasks/README.md: -------------------------------------------------------------------------------- 1 | # About the `tasks` folder 2 | 3 | The `tasks` directory is a suite of Grunt tasks and their configurations, bundled for your convenience. The Grunt integration is mainly useful for bundling front-end assets, (like stylesheets, scripts, & markup templates) but it can also be used to run all kinds of development tasks, from browserify compilation to database migrations. 4 | 5 | If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, read on! 6 | 7 | 8 | ### How does this work? 9 | 10 | The asset pipeline bundled in Sails is a set of Grunt tasks configured with conventional defaults designed to make your project more consistent and productive. 11 | 12 | The entire front-end asset workflow in Sails is completely customizable-- while it provides some suggestions out of the box, Sails makes no pretense that it can anticipate all of the needs you'll encounter building the browser-based/front-end portion of your application. Who's to say you're even building an app for a browser? 13 | 14 | 15 | 16 | ### What tasks does Sails run automatically? 17 | 18 | Sails runs some of these tasks (the ones in the `tasks/register` folder) automatically when you run certain commands. 19 | 20 | ###### `sails lift` 21 | 22 | Runs the `default` task (`tasks/register/default.js`). 23 | 24 | ###### `sails lift --prod` 25 | 26 | Runs the `prod` task (`tasks/register/prod.js`). 27 | 28 | ###### `sails www` 29 | 30 | Runs the `build` task (`tasks/register/build.js`). 31 | 32 | ###### `sails www --prod` (production) 33 | 34 | Runs the `buildProd` task (`tasks/register/buildProd.js`). 35 | 36 | 37 | ### Can I customize this for SASS, Angular, client-side Jade templates, etc? 38 | 39 | You can modify, omit, or replace any of these Grunt tasks to fit your requirements. You can also add your own Grunt tasks- just add a `someTask.js` file in the `grunt/config` directory to configure the new task, then register it with the appropriate parent task(s) (see files in `grunt/register/*.js`). 40 | 41 | 42 | ### Do I have to use Grunt? 43 | 44 | Nope! To disable Grunt integration in Sails, just delete your Gruntfile or disable the Grunt hook. 45 | 46 | 47 | ### What if I'm not building a web frontend? 48 | 49 | That's ok! A core tenant of Sails is client-agnosticism-- it's especially designed for building APIs used by all sorts of clients; native Android/iOS/Cordova, serverside SDKs, etc. 50 | 51 | You can completely disable Grunt by following the instructions above. 52 | 53 | If you still want to use Grunt for other purposes, but don't want any of the default web front-end stuff, just delete your project's `assets` folder and remove the front-end oriented tasks from the `grunt/register` and `grunt/config` folders. You can also run `sails new myCoolApi --no-frontend` to omit the `assets` folder and front-end-oriented Grunt tasks for future projects. You can also replace your `sails-generate-frontend` module with alternative community generators, or create your own. This allows `sails new` to create the boilerplate for native iOS apps, Android apps, Cordova apps, SteroidsJS apps, etc. 54 | 55 | -------------------------------------------------------------------------------- /config/globals.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Global Variable Configuration 3 | * (sails.config.globals) 4 | * 5 | * Configure which global variables which will be exposed 6 | * automatically by Sails. 7 | * 8 | * For more information on configuration, check out: 9 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.globals.html 10 | */ 11 | module.exports.globals = { 12 | 13 | /**************************************************************************** 14 | * * 15 | * Expose the lodash installed in Sails core as a global variable. If this * 16 | * is disabled, like any other node module you can always run npm install * 17 | * lodash --save, then var _ = require('lodash') at the top of any file. * 18 | * * 19 | ****************************************************************************/ 20 | 21 | // _: true, 22 | 23 | /**************************************************************************** 24 | * * 25 | * Expose the async installed in Sails core as a global variable. If this is * 26 | * disabled, like any other node module you can always run npm install async * 27 | * --save, then var async = require('async') at the top of any file. * 28 | * * 29 | ****************************************************************************/ 30 | 31 | // async: true, 32 | 33 | /**************************************************************************** 34 | * * 35 | * Expose the sails instance representing your app. If this is disabled, you * 36 | * can still get access via req._sails. * 37 | * * 38 | ****************************************************************************/ 39 | 40 | // sails: true, 41 | 42 | /**************************************************************************** 43 | * * 44 | * Expose each of your app's services as global variables (using their * 45 | * "globalId"). E.g. a service defined in api/models/NaturalLanguage.js * 46 | * would have a globalId of NaturalLanguage by default. If this is disabled, * 47 | * you can still access your services via sails.services.* * 48 | * * 49 | ****************************************************************************/ 50 | 51 | // services: true, 52 | 53 | /**************************************************************************** 54 | * * 55 | * Expose each of your app's models as global variables (using their * 56 | * "globalId"). E.g. a model defined in api/models/User.js would have a * 57 | * globalId of User by default. If this is disabled, you can still access * 58 | * your models via sails.models.*. * 59 | * * 60 | ****************************************************************************/ 61 | 62 | // models: true 63 | }; 64 | -------------------------------------------------------------------------------- /views/layout.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | New Sails App 5 | 6 | 7 | 8 | 9 | 10 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | <%- body %> 37 | 38 | 39 | 40 | 60 | 61 | 62 | 63 | 64 | 65 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /config/cors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Cross-Origin Resource Sharing (CORS) Settings 3 | * (sails.config.cors) 4 | * 5 | * CORS is like a more modern version of JSONP-- it allows your server/API 6 | * to successfully respond to requests from client-side JavaScript code 7 | * running on some other domain (e.g. google.com) 8 | * Unlike JSONP, it works with POST, PUT, and DELETE requests 9 | * 10 | * For more information on CORS, check out: 11 | * http://en.wikipedia.org/wiki/Cross-origin_resource_sharing 12 | * 13 | * Note that any of these settings (besides 'allRoutes') can be changed on a per-route basis 14 | * by adding a "cors" object to the route configuration: 15 | * 16 | * '/get foo': { 17 | * controller: 'foo', 18 | * action: 'bar', 19 | * cors: { 20 | * origin: 'http://foobar.com,https://owlhoot.com' 21 | * } 22 | * } 23 | * 24 | * For more information on this configuration file, see: 25 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.cors.html 26 | * 27 | */ 28 | 29 | module.exports.cors = { 30 | 31 | /*************************************************************************** 32 | * * 33 | * Allow CORS on all routes by default? If not, you must enable CORS on a * 34 | * per-route basis by either adding a "cors" configuration object to the * 35 | * route config, or setting "cors:true" in the route config to use the * 36 | * default settings below. * 37 | * * 38 | ***************************************************************************/ 39 | 40 | // allRoutes: false, 41 | 42 | /*************************************************************************** 43 | * * 44 | * Which domains which are allowed CORS access? This can be a * 45 | * comma-delimited list of hosts (beginning with http:// or https://) or * 46 | * "*" to allow all domains CORS access. * 47 | * * 48 | ***************************************************************************/ 49 | 50 | // origin: '*', 51 | 52 | /*************************************************************************** 53 | * * 54 | * Allow cookies to be shared for CORS requests? * 55 | * * 56 | ***************************************************************************/ 57 | 58 | // credentials: true, 59 | 60 | /*************************************************************************** 61 | * * 62 | * Which methods should be allowed for CORS requests? This is only used in * 63 | * response to preflight requests (see article linked above for more info) * 64 | * * 65 | ***************************************************************************/ 66 | 67 | // methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD', 68 | 69 | /*************************************************************************** 70 | * * 71 | * Which headers should be allowed for CORS requests? This is only used in * 72 | * response to preflight requests. * 73 | * * 74 | ***************************************************************************/ 75 | 76 | // headers: 'content-type' 77 | 78 | }; 79 | -------------------------------------------------------------------------------- /views/403.ejs: -------------------------------------------------------------------------------- 1 | 2 | 36 | 37 | 38 | Forbidden 39 | 40 | 44 | 45 | 46 | 47 |
48 |
49 | 50 |
51 | 52 |
53 |

54 | Forbidden 55 |

56 |

57 | <% if (typeof error !== 'undefined') { %> 58 | <%= error %> 59 | <% } else { %> 60 | You don't have permission to see the page you're trying to reach. 61 | <% } %> 62 |

63 |

64 | Why might this be happening? 65 |

66 |
67 | 68 | 73 |
74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /views/404.ejs: -------------------------------------------------------------------------------- 1 | 2 | 36 | 37 | 38 | Page Not Found 39 | 40 | 44 | 45 | 46 | 47 |
48 |
49 | 50 |
51 | 52 |
53 |

54 | Something's fishy here. 55 |

56 |

57 | <% if (typeof error!== 'undefined') { %> 58 | <%= error %> 59 | <% } else { %> 60 | The page you were trying to reach doesn't exist. 61 | <% } %> 62 |

63 |

64 | Why might this be happening? 65 |

66 |
67 | 68 | 73 |
74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /config/http.js: -------------------------------------------------------------------------------- 1 | /** 2 | * HTTP Server Settings 3 | * (sails.config.http) 4 | * 5 | * Configuration for the underlying HTTP server in Sails. 6 | * Only applies to HTTP requests (not WebSockets) 7 | * 8 | * For more information on configuration, check out: 9 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.http.html 10 | */ 11 | 12 | module.exports.http = { 13 | 14 | /**************************************************************************** 15 | * * 16 | * Express middleware to use for every Sails request. To add custom * 17 | * middleware to the mix, add a function to the middleware config object and * 18 | * add its key to the "order" array. The $custom key is reserved for * 19 | * backwards-compatibility with Sails v0.9.x apps that use the * 20 | * `customMiddleware` config option. * 21 | * * 22 | ****************************************************************************/ 23 | 24 | // middleware: { 25 | 26 | /*************************************************************************** 27 | * * 28 | * The order in which middleware should be run for HTTP request. (the Sails * 29 | * router is invoked by the "router" middleware below.) * 30 | * * 31 | ***************************************************************************/ 32 | 33 | // order: [ 34 | // 'startRequestTimer', 35 | // 'cookieParser', 36 | // 'session', 37 | // 'myRequestLogger', 38 | // 'bodyParser', 39 | // 'handleBodyParserError', 40 | // 'compress', 41 | // 'methodOverride', 42 | // 'poweredBy', 43 | // '$custom', 44 | // 'router', 45 | // 'www', 46 | // 'favicon', 47 | // '404', 48 | // '500' 49 | // ], 50 | 51 | /**************************************************************************** 52 | * * 53 | * Example custom middleware; logs each request to the console. * 54 | * * 55 | ****************************************************************************/ 56 | 57 | // myRequestLogger: function (req, res, next) { 58 | // console.log("Requested :: ", req.method, req.url); 59 | // return next(); 60 | // } 61 | 62 | 63 | /*************************************************************************** 64 | * * 65 | * The body parser that will handle incoming multipart HTTP requests. By * 66 | * default as of v0.10, Sails uses * 67 | * [skipper](http://github.com/balderdashy/skipper). See * 68 | * http://www.senchalabs.org/connect/multipart.html for other options. * 69 | * * 70 | ***************************************************************************/ 71 | 72 | // bodyParser: require('skipper') 73 | 74 | // }, 75 | 76 | /*************************************************************************** 77 | * * 78 | * The number of seconds to cache flat files on disk being served by * 79 | * Express static middleware (by default, these files are in `.tmp/public`) * 80 | * * 81 | * The HTTP static cache is only active in a 'production' environment, * 82 | * since that's the only time Express will cache flat-files. * 83 | * * 84 | ***************************************************************************/ 85 | 86 | // cache: 31557600000 87 | }; 88 | -------------------------------------------------------------------------------- /config/session.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Session Configuration 3 | * (sails.config.session) 4 | * 5 | * Sails session integration leans heavily on the great work already done by 6 | * Express, but also unifies Socket.io with the Connect session store. It uses 7 | * Connect's cookie parser to normalize configuration differences between Express 8 | * and Socket.io and hooks into Sails' middleware interpreter to allow you to access 9 | * and auto-save to `req.session` with Socket.io the same way you would with Express. 10 | * 11 | * For more information on configuring the session, check out: 12 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html 13 | */ 14 | 15 | module.exports.session = { 16 | 17 | /*************************************************************************** 18 | * * 19 | * Session secret is automatically generated when your new app is created * 20 | * Replace at your own risk in production-- you will invalidate the cookies * 21 | * of your users, forcing them to log in again. * 22 | * * 23 | ***************************************************************************/ 24 | secret: 'fa65439ffd0f4138299c90ea69c3b18e', 25 | 26 | 27 | /*************************************************************************** 28 | * * 29 | * Set the session cookie expire time The maxAge is set by milliseconds, * 30 | * the example below is for 24 hours * 31 | * * 32 | ***************************************************************************/ 33 | 34 | // cookie: { 35 | // maxAge: 24 * 60 * 60 * 1000 36 | // } 37 | 38 | /*************************************************************************** 39 | * * 40 | * In production, uncomment the following lines to set up a shared redis * 41 | * session store that can be shared across multiple Sails.js servers * 42 | ***************************************************************************/ 43 | 44 | // adapter: 'redis', 45 | 46 | /*************************************************************************** 47 | * * 48 | * The following values are optional, if no options are set a redis * 49 | * instance running on localhost is expected. Read more about options at: * 50 | * https://github.com/visionmedia/connect-redis * 51 | * * 52 | * * 53 | ***************************************************************************/ 54 | 55 | // host: 'localhost', 56 | // port: 6379, 57 | // ttl: , 58 | // db: 0, 59 | // pass: 60 | // prefix: 'sess:' 61 | 62 | 63 | /*************************************************************************** 64 | * * 65 | * Uncomment the following lines to use your Mongo adapter as a session * 66 | * store * 67 | * * 68 | ***************************************************************************/ 69 | 70 | // adapter: 'mongo', 71 | // host: 'localhost', 72 | // port: 27017, 73 | // db: 'sails', 74 | // collection: 'sessions', 75 | 76 | /*************************************************************************** 77 | * * 78 | * Optional Values: * 79 | * * 80 | * # Note: url will override other connection settings url: * 81 | * 'mongodb://user:pass@host:port/database/collection', * 82 | * * 83 | ***************************************************************************/ 84 | 85 | // username: '', 86 | // password: '', 87 | // auto_reconnect: false, 88 | // ssl: false, 89 | // stringify: true 90 | 91 | }; 92 | -------------------------------------------------------------------------------- /config/connections.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Connections 3 | * (sails.config.connections) 4 | * 5 | * `Connections` are like "saved settings" for your adapters. What's the difference between 6 | * a connection and an adapter, you might ask? An adapter (e.g. `sails-mysql`) is generic-- 7 | * it needs some additional information to work (e.g. your database host, password, user, etc.) 8 | * A `connection` is that additional information. 9 | * 10 | * Each model must have a `connection` property (a string) which is references the name of one 11 | * of these connections. If it doesn't, the default `connection` configured in `config/models.js` 12 | * will be applied. Of course, a connection can (and usually is) shared by multiple models. 13 | * . 14 | * Note: If you're using version control, you should put your passwords/api keys 15 | * in `config/local.js`, environment variables, or use another strategy. 16 | * (this is to prevent you inadvertently sensitive credentials up to your repository.) 17 | * 18 | * For more information on configuration, check out: 19 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.connections.html 20 | */ 21 | 22 | module.exports.connections = { 23 | 24 | /*************************************************************************** 25 | * * 26 | * Local disk storage for DEVELOPMENT ONLY * 27 | * * 28 | * Installed by default. * 29 | * * 30 | ***************************************************************************/ 31 | localDiskDb: { 32 | adapter: 'sails-disk' 33 | }, 34 | 35 | /*************************************************************************** 36 | * * 37 | * MySQL is the world's most popular relational database. * 38 | * http://en.wikipedia.org/wiki/MySQL * 39 | * * 40 | * Run: npm install sails-mysql * 41 | * * 42 | ***************************************************************************/ 43 | someMysqlServer: { 44 | adapter: 'sails-mysql', 45 | host: 'localhost', 46 | user: 'robot', 47 | port: 3306, 48 | password: 'Passw0rd123', 49 | database: 'prototypeDB' 50 | }, 51 | 52 | /*************************************************************************** 53 | * * 54 | * MongoDB is the leading NoSQL database. * 55 | * http://en.wikipedia.org/wiki/MongoDB * 56 | * * 57 | * Run: npm install sails-mongo * 58 | * * 59 | ***************************************************************************/ 60 | someMongodbServer: { 61 | adapter: 'sails-mongo', 62 | host: 'localhost', 63 | port: 27017, 64 | // user: 'username', 65 | // password: 'password', 66 | // database: 'your_mongo_db_name_here' 67 | }, 68 | 69 | /*************************************************************************** 70 | * * 71 | * PostgreSQL is another officially supported relational database. * 72 | * http://en.wikipedia.org/wiki/PostgreSQL * 73 | * * 74 | * Run: npm install sails-postgresql * 75 | * * 76 | * * 77 | ***************************************************************************/ 78 | somePostgresqlServer: { 79 | adapter: 'sails-postgresql', 80 | host: 'YOUR_POSTGRES_SERVER_HOSTNAME_OR_IP_ADDRESS', 81 | user: 'YOUR_POSTGRES_USER', 82 | password: 'YOUR_POSTGRES_PASSWORD', 83 | database: 'YOUR_POSTGRES_DB' 84 | } 85 | 86 | 87 | /*************************************************************************** 88 | * * 89 | * More adapters: https://github.com/balderdashy/sails * 90 | * * 91 | ***************************************************************************/ 92 | 93 | }; 94 | -------------------------------------------------------------------------------- /config/local.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Local environment settings 3 | * 4 | * Use this file to specify configuration settings for use while developing 5 | * the app on your personal system: for example, this would be a good place 6 | * to store database or email passwords that apply only to you, and shouldn't 7 | * be shared with others in your organization. 8 | * 9 | * These settings take precedence over all other config files, including those 10 | * in the env/ subfolder. 11 | * 12 | * PLEASE NOTE: 13 | * local.js is included in your .gitignore, so if you're using git 14 | * as a version control solution for your Sails app, keep in mind that 15 | * this file won't be committed to your repository! 16 | * 17 | * Good news is, that means you can specify configuration for your local 18 | * machine in this file without inadvertently committing personal information 19 | * (like database passwords) to the repo. Plus, this prevents other members 20 | * of your team from commiting their local configuration changes on top of yours. 21 | * 22 | * In a production environment, you probably want to leave this file out 23 | * entirely and leave all your settings in env/production.js 24 | * 25 | * 26 | * For more information, check out: 27 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.local.html 28 | */ 29 | 30 | module.exports = { 31 | 32 | /*************************************************************************** 33 | * Your SSL certificate and key, if you want to be able to serve HTTP * 34 | * responses over https:// and/or use websockets over the wss:// protocol * 35 | * (recommended for HTTP, strongly encouraged for WebSockets) * 36 | * * 37 | * In this example, we'll assume you created a folder in your project, * 38 | * `config/ssl` and dumped your certificate/key files there: * 39 | ***************************************************************************/ 40 | 41 | // ssl: { 42 | // ca: require('fs').readFileSync(__dirname + './ssl/my_apps_ssl_gd_bundle.crt'), 43 | // key: require('fs').readFileSync(__dirname + './ssl/my_apps_ssl.key'), 44 | // cert: require('fs').readFileSync(__dirname + './ssl/my_apps_ssl.crt') 45 | // }, 46 | 47 | /*************************************************************************** 48 | * The `port` setting determines which TCP port your app will be * 49 | * deployed on. * 50 | * * 51 | * Ports are a transport-layer concept designed to allow many different * 52 | * networking applications run at the same time on a single computer. * 53 | * More about ports: * 54 | * http://en.wikipedia.org/wiki/Port_(computer_networking) * 55 | * * 56 | * By default, if it's set, Sails uses the `PORT` environment variable. * 57 | * Otherwise it falls back to port 1337. * 58 | * * 59 | * In env/production.js, you'll probably want to change this setting * 60 | * to 80 (http://) or 443 (https://) if you have an SSL certificate * 61 | ***************************************************************************/ 62 | 63 | // port: process.env.PORT || 1337, 64 | 65 | /*************************************************************************** 66 | * The runtime "environment" of your Sails app is either typically * 67 | * 'development' or 'production'. * 68 | * * 69 | * In development, your Sails app will go out of its way to help you * 70 | * (for instance you will receive more descriptive error and * 71 | * debugging output) * 72 | * * 73 | * In production, Sails configures itself (and its dependencies) to * 74 | * optimize performance. You should always put your app in production mode * 75 | * before you deploy it to a server. This helps ensure that your Sails * 76 | * app remains stable, performant, and scalable. * 77 | * * 78 | * By default, Sails sets its environment using the `NODE_ENV` environment * 79 | * variable. If NODE_ENV is not set, Sails will run in the * 80 | * 'development' environment. * 81 | ***************************************************************************/ 82 | 83 | // environment: process.env.NODE_ENV || 'development' 84 | 85 | }; 86 | -------------------------------------------------------------------------------- /config/views.js: -------------------------------------------------------------------------------- 1 | /** 2 | * View Engine Configuration 3 | * (sails.config.views) 4 | * 5 | * Server-sent views are a classic and effective way to get your app up 6 | * and running. Views are normally served from controllers. Below, you can 7 | * configure your templating language/framework of choice and configure 8 | * Sails' layout support. 9 | * 10 | * For more information on views and layouts, check out: 11 | * http://sailsjs.org/#/documentation/concepts/Views 12 | */ 13 | 14 | module.exports.views = { 15 | 16 | /**************************************************************************** 17 | * * 18 | * View engine (aka template language) to use for your app's *server-side* * 19 | * views * 20 | * * 21 | * Sails+Express supports all view engines which implement TJ Holowaychuk's * 22 | * `consolidate.js`, including, but not limited to: * 23 | * * 24 | * ejs, jade, handlebars, mustache underscore, hogan, haml, haml-coffee, * 25 | * dust atpl, eco, ect, jazz, jqtpl, JUST, liquor, QEJS, swig, templayed, * 26 | * toffee, walrus, & whiskers * 27 | * * 28 | * For more options, check out the docs: * 29 | * https://github.com/balderdashy/sails-wiki/blob/0.9/config.views.md#engine * 30 | * * 31 | ****************************************************************************/ 32 | 33 | engine: 'ejs', 34 | 35 | 36 | /**************************************************************************** 37 | * * 38 | * Layouts are simply top-level HTML templates you can use as wrappers for * 39 | * your server-side views. If you're using ejs or jade, you can take * 40 | * advantage of Sails' built-in `layout` support. * 41 | * * 42 | * When using a layout, when one of your views is served, it is injected * 43 | * into the `body` partial defined in the layout. This lets you reuse header * 44 | * and footer logic between views. * 45 | * * 46 | * NOTE: Layout support is only implemented for the `ejs` view engine! * 47 | * For most other engines, it is not necessary, since they implement * 48 | * partials/layouts themselves. In those cases, this config will be * 49 | * silently ignored. * 50 | * * 51 | * The `layout` setting may be set to one of the following: * 52 | * * 53 | * If `false`, layouts will be disabled. Otherwise, if a string is * 54 | * specified, it will be interpreted as the relative path to your layout * 55 | * file from `views/` folder. (the file extension, ".ejs", should be * 56 | * omitted) * 57 | * * 58 | ****************************************************************************/ 59 | 60 | layout: 'layout' 61 | 62 | /**************************************************************************** 63 | * * 64 | * Using Multiple Layouts with EJS * 65 | * * 66 | * If you're using the default engine, `ejs`, Sails supports the use of * 67 | * multiple `layout` files. To take advantage of this, before rendering a * 68 | * view, override the `layout` local in your controller by setting * 69 | * `res.locals.layout`. (this is handy if you parts of your app's UI look * 70 | * completely different from each other) * 71 | * * 72 | * e.g. your default might be * 73 | * layout: 'layouts/public' * 74 | * * 75 | * But you might override that in some of your controllers with: * 76 | * layout: 'layouts/internal' * 77 | * * 78 | ****************************************************************************/ 79 | 80 | 81 | }; 82 | -------------------------------------------------------------------------------- /views/homepage.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 12 | 13 |
14 |
15 |

<%= __('A brand new app.') %>

16 |

You're looking at: <%= view.pathFromApp + '.' +view.ext %>

17 |
18 |
19 | 21 |
    22 |
  • 23 |
    24 |
    25 |

    Generate a REST API.

    26 |

    27 | Run sails generate api user. This will create two files: a model api/models/User.js and a controllerapi/controllers/UserController.js. 28 |

    29 |
    30 |
  • 31 |
  • 32 |
    33 |
    34 |

    35 | Lift your app. 36 |

    37 |

    38 | Run sails lift to start up your app server. If you visit http://localhost:1337/user in your browser, you'll see a WebSocket-compatible user API. 39 |

    40 |
    41 |
  • 42 |
  • 43 |
    44 |
    45 |

    46 | Dive in. 47 |

    48 |

    Blueprints are just the beginning. You'll probably also want to learn how to customize your app's routes, set up security policies, configure your data sources, and build custom controller actions. For more help getting started, check out the links on this page.

    49 | 50 |
    51 |
  • 52 |
53 | 73 |
74 |
75 | -------------------------------------------------------------------------------- /tasks/config/sails-linker.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Autoinsert script tags (or other filebased tags) in an html file. 3 | * 4 | * --------------------------------------------------------------- 5 | * 6 | * Automatically inject ', 22 | appRoot: '.tmp/public' 23 | }, 24 | files: { 25 | '.tmp/public/**/*.html': require('../pipeline').jsFilesToInject, 26 | 'views/**/*.html': require('../pipeline').jsFilesToInject, 27 | 'views/**/*.ejs': require('../pipeline').jsFilesToInject 28 | } 29 | }, 30 | 31 | devJsRelative: { 32 | options: { 33 | startTag: '', 34 | endTag: '', 35 | fileTmpl: '', 36 | appRoot: '.tmp/public', 37 | relative: true 38 | }, 39 | files: { 40 | '.tmp/public/**/*.html': require('../pipeline').jsFilesToInject, 41 | 'views/**/*.html': require('../pipeline').jsFilesToInject, 42 | 'views/**/*.ejs': require('../pipeline').jsFilesToInject 43 | } 44 | }, 45 | 46 | prodJs: { 47 | options: { 48 | startTag: '', 49 | endTag: '', 50 | fileTmpl: '', 51 | appRoot: '.tmp/public' 52 | }, 53 | files: { 54 | '.tmp/public/**/*.html': ['.tmp/public/min/production.min.js'], 55 | 'views/**/*.html': ['.tmp/public/min/production.min.js'], 56 | 'views/**/*.ejs': ['.tmp/public/min/production.min.js'] 57 | } 58 | }, 59 | 60 | prodJsRelative: { 61 | options: { 62 | startTag: '', 63 | endTag: '', 64 | fileTmpl: '', 65 | appRoot: '.tmp/public', 66 | relative: true 67 | }, 68 | files: { 69 | '.tmp/public/**/*.html': ['.tmp/public/min/production.min.js'], 70 | 'views/**/*.html': ['.tmp/public/min/production.min.js'], 71 | 'views/**/*.ejs': ['.tmp/public/min/production.min.js'] 72 | } 73 | }, 74 | 75 | devStyles: { 76 | options: { 77 | startTag: '', 78 | endTag: '', 79 | fileTmpl: '', 80 | appRoot: '.tmp/public' 81 | }, 82 | 83 | files: { 84 | '.tmp/public/**/*.html': require('../pipeline').cssFilesToInject, 85 | 'views/**/*.html': require('../pipeline').cssFilesToInject, 86 | 'views/**/*.ejs': require('../pipeline').cssFilesToInject 87 | } 88 | }, 89 | 90 | devStylesRelative: { 91 | options: { 92 | startTag: '', 93 | endTag: '', 94 | fileTmpl: '', 95 | appRoot: '.tmp/public', 96 | relative: true 97 | }, 98 | 99 | files: { 100 | '.tmp/public/**/*.html': require('../pipeline').cssFilesToInject, 101 | 'views/**/*.html': require('../pipeline').cssFilesToInject, 102 | 'views/**/*.ejs': require('../pipeline').cssFilesToInject 103 | } 104 | }, 105 | 106 | prodStyles: { 107 | options: { 108 | startTag: '', 109 | endTag: '', 110 | fileTmpl: '', 111 | appRoot: '.tmp/public' 112 | }, 113 | files: { 114 | '.tmp/public/index.html': ['.tmp/public/min/production.min.css'], 115 | 'views/**/*.html': ['.tmp/public/min/production.min.css'], 116 | 'views/**/*.ejs': ['.tmp/public/min/production.min.css'] 117 | } 118 | }, 119 | 120 | prodStylesRelative: { 121 | options: { 122 | startTag: '', 123 | endTag: '', 124 | fileTmpl: '', 125 | appRoot: '.tmp/public', 126 | relative: true 127 | }, 128 | files: { 129 | '.tmp/public/index.html': ['.tmp/public/min/production.min.css'], 130 | 'views/**/*.html': ['.tmp/public/min/production.min.css'], 131 | 'views/**/*.ejs': ['.tmp/public/min/production.min.css'] 132 | } 133 | }, 134 | 135 | // Bring in JST template object 136 | devTpl: { 137 | options: { 138 | startTag: '', 139 | endTag: '', 140 | fileTmpl: '', 141 | appRoot: '.tmp/public' 142 | }, 143 | files: { 144 | '.tmp/public/index.html': ['.tmp/public/jst.js'], 145 | 'views/**/*.html': ['.tmp/public/jst.js'], 146 | 'views/**/*.ejs': ['.tmp/public/jst.js'] 147 | } 148 | }, 149 | 150 | devJsJade: { 151 | options: { 152 | startTag: '// SCRIPTS', 153 | endTag: '// SCRIPTS END', 154 | fileTmpl: 'script(src="%s")', 155 | appRoot: '.tmp/public' 156 | }, 157 | files: { 158 | 'views/**/*.jade': require('../pipeline').jsFilesToInject 159 | } 160 | }, 161 | 162 | devJsRelativeJade: { 163 | options: { 164 | startTag: '// SCRIPTS', 165 | endTag: '// SCRIPTS END', 166 | fileTmpl: 'script(src="%s")', 167 | appRoot: '.tmp/public', 168 | relative: true 169 | }, 170 | files: { 171 | 'views/**/*.jade': require('../pipeline').jsFilesToInject 172 | } 173 | }, 174 | 175 | prodJsJade: { 176 | options: { 177 | startTag: '// SCRIPTS', 178 | endTag: '// SCRIPTS END', 179 | fileTmpl: 'script(src="%s")', 180 | appRoot: '.tmp/public' 181 | }, 182 | files: { 183 | 'views/**/*.jade': ['.tmp/public/min/production.min.js'] 184 | } 185 | }, 186 | 187 | prodJsRelativeJade: { 188 | options: { 189 | startTag: '// SCRIPTS', 190 | endTag: '// SCRIPTS END', 191 | fileTmpl: 'script(src="%s")', 192 | appRoot: '.tmp/public', 193 | relative: true 194 | }, 195 | files: { 196 | 'views/**/*.jade': ['.tmp/public/min/production.min.js'] 197 | } 198 | }, 199 | 200 | devStylesJade: { 201 | options: { 202 | startTag: '// STYLES', 203 | endTag: '// STYLES END', 204 | fileTmpl: 'link(rel="stylesheet", href="%s")', 205 | appRoot: '.tmp/public' 206 | }, 207 | 208 | files: { 209 | 'views/**/*.jade': require('../pipeline').cssFilesToInject 210 | } 211 | }, 212 | 213 | devStylesRelativeJade: { 214 | options: { 215 | startTag: '// STYLES', 216 | endTag: '// STYLES END', 217 | fileTmpl: 'link(rel="stylesheet", href="%s")', 218 | appRoot: '.tmp/public', 219 | relative: true 220 | }, 221 | 222 | files: { 223 | 'views/**/*.jade': require('../pipeline').cssFilesToInject 224 | } 225 | }, 226 | 227 | prodStylesJade: { 228 | options: { 229 | startTag: '// STYLES', 230 | endTag: '// STYLES END', 231 | fileTmpl: 'link(rel="stylesheet", href="%s")', 232 | appRoot: '.tmp/public' 233 | }, 234 | files: { 235 | 'views/**/*.jade': ['.tmp/public/min/production.min.css'] 236 | } 237 | }, 238 | 239 | prodStylesRelativeJade: { 240 | options: { 241 | startTag: '// STYLES', 242 | endTag: '// STYLES END', 243 | fileTmpl: 'link(rel="stylesheet", href="%s")', 244 | appRoot: '.tmp/public', 245 | relative: true 246 | }, 247 | files: { 248 | 'views/**/*.jade': ['.tmp/public/min/production.min.css'] 249 | } 250 | }, 251 | 252 | // Bring in JST template object 253 | devTplJade: { 254 | options: { 255 | startTag: '// TEMPLATES', 256 | endTag: '// TEMPLATES END', 257 | fileTmpl: 'script(type="text/javascript", src="%s")', 258 | appRoot: '.tmp/public' 259 | }, 260 | files: { 261 | 'views/**/*.jade': ['.tmp/public/jst.js'] 262 | } 263 | } 264 | }); 265 | 266 | grunt.loadNpmTasks('grunt-sails-linker'); 267 | }; 268 | -------------------------------------------------------------------------------- /config/blueprints.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Blueprint API Configuration 3 | * (sails.config.blueprints) 4 | * 5 | * These settings are for the global configuration of blueprint routes and 6 | * request options (which impact the behavior of blueprint actions). 7 | * 8 | * You may also override any of these settings on a per-controller basis 9 | * by defining a '_config' key in your controller defintion, and assigning it 10 | * a configuration object with overrides for the settings in this file. 11 | * A lot of the configuration options below affect so-called "CRUD methods", 12 | * or your controllers' `find`, `create`, `update`, and `destroy` actions. 13 | * 14 | * It's important to realize that, even if you haven't defined these yourself, as long as 15 | * a model exists with the same name as the controller, Sails will respond with built-in CRUD 16 | * logic in the form of a JSON API, including support for sort, pagination, and filtering. 17 | * 18 | * For more information on the blueprint API, check out: 19 | * http://sailsjs.org/#/documentation/reference/blueprint-api 20 | * 21 | * For more information on the settings in this file, see: 22 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html 23 | * 24 | */ 25 | 26 | module.exports.blueprints = { 27 | 28 | /*************************************************************************** 29 | * * 30 | * Action routes speed up the backend development workflow by * 31 | * eliminating the need to manually bind routes. When enabled, GET, POST, * 32 | * PUT, and DELETE routes will be generated for every one of a controller's * 33 | * actions. * 34 | * * 35 | * If an `index` action exists, additional naked routes will be created for * 36 | * it. Finally, all `actions` blueprints support an optional path * 37 | * parameter, `id`, for convenience. * 38 | * * 39 | * `actions` are enabled by default, and can be OK for production-- * 40 | * however, if you'd like to continue to use controller/action autorouting * 41 | * in a production deployment, you must take great care not to * 42 | * inadvertently expose unsafe/unintentional controller logic to GET * 43 | * requests. * 44 | * * 45 | ***************************************************************************/ 46 | 47 | // actions: true, 48 | 49 | /*************************************************************************** 50 | * * 51 | * RESTful routes (`sails.config.blueprints.rest`) * 52 | * * 53 | * REST blueprints are the automatically generated routes Sails uses to * 54 | * expose a conventional REST API on top of a controller's `find`, * 55 | * `create`, `update`, and `destroy` actions. * 56 | * * 57 | * For example, a BoatController with `rest` enabled generates the * 58 | * following routes: * 59 | * ::::::::::::::::::::::::::::::::::::::::::::::::::::::: * 60 | * GET /boat/:id? -> BoatController.find * 61 | * POST /boat -> BoatController.create * 62 | * PUT /boat/:id -> BoatController.update * 63 | * DELETE /boat/:id -> BoatController.destroy * 64 | * * 65 | * `rest` blueprint routes are enabled by default, and are suitable for use * 66 | * in a production scenario, as long you take standard security precautions * 67 | * (combine w/ policies, etc.) * 68 | * * 69 | ***************************************************************************/ 70 | 71 | // rest: true, 72 | 73 | /*************************************************************************** 74 | * * 75 | * Shortcut routes are simple helpers to provide access to a * 76 | * controller's CRUD methods from your browser's URL bar. When enabled, * 77 | * GET, POST, PUT, and DELETE routes will be generated for the * 78 | * controller's`find`, `create`, `update`, and `destroy` actions. * 79 | * * 80 | * `shortcuts` are enabled by default, but should be disabled in * 81 | * production. * 82 | * * 83 | ***************************************************************************/ 84 | 85 | // shortcuts: true, 86 | 87 | /*************************************************************************** 88 | * * 89 | * An optional mount path for all blueprint routes on a controller, * 90 | * including `rest`, `actions`, and `shortcuts`. This allows you to take * 91 | * advantage of blueprint routing, even if you need to namespace your API * 92 | * methods. * 93 | * * 94 | * (NOTE: This only applies to blueprint autoroutes, not manual routes from * 95 | * `sails.config.routes`) * 96 | * * 97 | ***************************************************************************/ 98 | 99 | // prefix: '', 100 | 101 | /*************************************************************************** 102 | * * 103 | * Whether to pluralize controller names in blueprint routes. * 104 | * * 105 | * (NOTE: This only applies to blueprint autoroutes, not manual routes from * 106 | * `sails.config.routes`) * 107 | * * 108 | * For example, REST blueprints for `FooController` with `pluralize` * 109 | * enabled: * 110 | * GET /foos/:id? * 111 | * POST /foos * 112 | * PUT /foos/:id? * 113 | * DELETE /foos/:id? * 114 | * * 115 | ***************************************************************************/ 116 | 117 | // pluralize: false, 118 | 119 | /*************************************************************************** 120 | * * 121 | * Whether the blueprint controllers should populate model fetches with * 122 | * data from other models which are linked by associations * 123 | * * 124 | * If you have a lot of data in one-to-many associations, leaving this on * 125 | * may result in very heavy api calls * 126 | * * 127 | ***************************************************************************/ 128 | 129 | // populate: true, 130 | 131 | /**************************************************************************** 132 | * * 133 | * Whether to run Model.watch() in the find and findOne blueprint actions. * 134 | * Can be overridden on a per-model basis. * 135 | * * 136 | ****************************************************************************/ 137 | 138 | // autoWatch: true, 139 | 140 | /**************************************************************************** 141 | * * 142 | * The default number of records to show in the response from a "find" * 143 | * action. Doubles as the default size of populated arrays if populate is * 144 | * true. * 145 | * * 146 | ****************************************************************************/ 147 | 148 | // defaultLimit: 30 149 | 150 | }; 151 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sails JS and Waterline Association 2 | 3 | For a few weeks now I have been tinkering node.js and in which I am highly considering using on our next project. I reckon node will be the future of web development. Hunting for a MVC framework in node, I stumble upon sails.js. It looks promising and I’ve been following its development ever since. 4 | Sails.js is still on its early stage and with the release of version 0.10.x recently, I got excited on one of its feature, “Associations”! 5 | In this article, I wanted to share to you a short guide on how to get going with node + sails js and lastly a briefly guide on Associations. 6 | 7 | ## Node + Sails 8 | 9 | To start, you’ll need node.js in your machine. Download and install node from http://nodejs.org/ if haven’t already. Then to start using sails you need to grab the package. To do this, go to your node js console and run 10 | 11 | ```javascript 12 | > npm install –g sails 13 | ``` 14 | 15 | The –g argument installs the package globally. Now to create a new project, run the command: 16 | 17 | ```javascript 18 | > sails new MySailsProject 19 | ``` 20 | 21 | This command will create the project folder together with the files. Go to the directory: 22 | 23 | ```javascript 24 | > cd MySailsProject 25 | ``` 26 | 27 | Then type the command: 28 | ```javascript 29 | > sails lift 30 | ``` 31 | Easy as that, you now have a sails.js project running! By default, the project will run on port 1337. You can change the port in *config\local.js*, add the snippet below under module.export: 32 | 33 | ```javascript 34 | port: 35 | ``` 36 | 37 | ## Controller 38 | Sails comes with generator for creating controller and model. Looking at their trello road map https://trello.com/b/cGzNVE0b/sails-roadmap looks like they’re working on including mocha test in the generator which should be handy. To create a controller: 39 | 40 | ```javascript 41 | > sails generate controller Store 42 | ``` 43 | 44 | This will create a *StoreController.js* under *api/controllers*. So, to add an action, simply add a function, e.g.: 45 | 46 | ```javascript 47 | module.exports = { 48 | HelloWorld: function (req, res){ 49 | return res.json({Hello: 'Hello World!'}); 50 | } 51 | } 52 | ``` 53 | 54 | The code will be accessible through the url */Store/HelloWorld*. 55 | 56 | ##MySQL Adapter 57 | 58 | Sails comes with Waterline ORM. To interact with the database, we’ll need an adapter, for this instance will add a mysql adpater. 59 | 60 | ```javascript 61 | > npm install sails-mysql 62 | ``` 63 | 64 | Configure the database connection in *config/connections.js* 65 | ```javascript 66 | someMysqlServer: { 67 | adapter: 'sails-mysql', 68 | host: 'localhost', 69 | user: 'robot', 70 | port: 3306, 71 | password: 'Passw0rd123', 72 | database: 'prototypeDB' 73 | }, 74 | ``` 75 | 76 | ## Model 77 | 78 | Creating the model is easy, simply use the generator: 79 | 80 | ```javascript 81 | > sails generate model Driver 82 | ``` 83 | 84 | This will create a file *Driver.js* under *api/Models*. Add the fields under the attribute object: 85 | 86 | ```javascript 87 | module.exports = { 88 | 89 | attributes: { 90 | 91 | Name: 'string' 92 | 93 | } 94 | }; 95 | ``` 96 | 97 | You can checkout the list of data type on their documentation http://sailsjs.org/#/documentation/concepts/ORM/Attributes.html 98 | 99 | ##Association 100 | 101 | Association is a feature in Waterline wherein you can associate a model with another model across multiple data stores. To me, this is the most 102 | important feature, as this is where you would design the structure of your data. 103 | 104 | To specify which data store of the model, simply specify the connection: 105 | 106 | ```javascript 107 | module.exports = { 108 | 109 | connection: 'someMysqlServer', 110 | 111 | attributes: { 112 | 113 | Name: { 114 | type: 'string', 115 | }, 116 | 117 | } 118 | }; 119 | ``` 120 | 121 | ##One to One Association 122 | 123 | Take for example we wanted to create a Car that can only be linked one driver and that driver can only be link to a single Car. We’ll generate the Car model: 124 | 125 | ```javascript 126 | > sails generate model Car 127 | ``` 128 | 129 | Add the fields: 130 | 131 | ```javascript 132 | module.exports = { 133 | connection: 'someMysqlServer', 134 | attributes: { 135 | Name: { 136 | type: 'string', 137 | }, 138 | Brand: { 139 | type: 'string' 140 | }, 141 | Model: { 142 | type: 'string' 143 | }, 144 | driver: { 145 | model: 'Driver', 146 | required: false 147 | } 148 | } 149 | }; 150 | ``` 151 | 152 | Notice the last attribute driver, we associated the model to the Driver model. We need modify the Driver model to add the association to the car model. 153 | 154 | ```javascript 155 | module.exports = { 156 | connection: 'someMysqlServer', 157 | attributes: { 158 | Name: { 159 | type: 'string', 160 | }, 161 | car: { 162 | model: 'Car', 163 | required: false 164 | } 165 | } 166 | }; 167 | ``` 168 | 169 | Now we’ll add a Car controller: 170 | 171 | ```javascript 172 | > sails generate controller Car 173 | ``` 174 | Insert the code in CarController.js 175 | 176 | ```javascript 177 | add: function(req, res){ 178 | var driver = {Name: 'Juan'}; 179 | Driver.create(driver).exec(function(err, result){ 180 | Car.create({ 181 | Name: 'My Car', 182 | Brand: 'Honda', 183 | Model: 'Civic', 184 | driver: result.id 185 | }).exec(function (e, r){ 186 | Driver.update({id: result.id}, {car: r.id}).exec(function(e1, r1){ 187 | return res.json({result: r, error: e}); 188 | }); 189 | }); 190 | }); 191 | } 192 | ``` 193 | 194 | We now have a bit of chained callbacks. What the code does is it: 195 | 196 | 1. Create Driver 197 | 2. Create the car then associate the driver 198 | driver: result.id 199 | 3. Update the Driver to associate with the Car. 200 | Now retrieving the Car model, you can use the populate function to get the associated model: 201 | 202 | ```javascript 203 | viewCar: function(req, res){ 204 | Car.find().populate('driver').exec(function(e, r){ 205 | return res.json({Car: r}); 206 | }); 207 | }, 208 | ``` 209 | 210 | This will spits out: 211 | ```javascript 212 | { 213 | "Car": [ 214 | { 215 | "driver": { 216 | "Name": "Juan", 217 | "id": 1, 218 | "createdAt": "2014-09-01T00:00:59.000Z", 219 | "updatedAt": "2014-09-01T00:00:59.000Z", 220 | "car": 1 221 | }, 222 | "Name": "My Car", 223 | "Brand": "Honda", 224 | "Model": "Civic", 225 | "id": 1, 226 | "createdAt": "2014-09-01T00:00:59.000Z", 227 | "updatedAt": "2014-09-01T00:00:59.000Z" 228 | } 229 | ] 230 | } 231 | ``` 232 | 233 | Or you can retrieve the other way around, retrieving the Driver and populate the car: 234 | ```javascript 235 | viewDriver: function(req, res){ 236 | Driver.find().populate('car').exec(function(e, r){ 237 | return res.json({Car: r}); 238 | }); 239 | } 240 | ``` 241 | Which will spits out: 242 | 243 | ```javascript 244 | { 245 | "Car": [ 246 | { 247 | "car": { 248 | "Name": "My Car", 249 | "Brand": "Honda", 250 | "Model": "Civic", 251 | "id": 1, 252 | "createdAt": "2014-09-01T00:00:59.000Z", 253 | "updatedAt": "2014-09-01T00:00:59.000Z", 254 | "driver": 1 255 | }, 256 | "Name": "Juan", 257 | "id": 1, 258 | "createdAt": "2014-09-01T00:00:59.000Z", 259 | "updatedAt": "2014-09-01T00:00:59.000Z" 260 | } 261 | ] 262 | } 263 | ``` 264 | 265 | ## One to may associations 266 | 267 | You can also associate one model with many other models. To do this, take for example, a scenario where you have a store which can have several customers: 268 | 269 | **Store.js** 270 | 271 | ```javascript 272 | module.exports = { 273 | 274 | connection: 'someMysqlServer', 275 | 276 | attributes: { 277 | Name: { 278 | type: 'string' 279 | }, 280 | 281 | customers: { 282 | collection: 'Customer', 283 | via: 'store' 284 | } 285 | } 286 | }; 287 | ``` 288 | 289 | **Customer.js** 290 | 291 | ```javascript 292 | module.exports = { 293 | 294 | connection: 'someMysqlServer', 295 | 296 | attributes: { 297 | 298 | Name: { 299 | type: 'string', 300 | }, 301 | 302 | store: { 303 | model: 'Store' 304 | } 305 | 306 | } 307 | }; 308 | ``` 309 | 310 | Then you can add the customers using the store id 311 | 312 | ```javascript 313 | addStoreCustomer: function(req, res){ 314 | Store.create({Name: 'Sari Sari Store'}).exec(function(e,r){ 315 | Customer.create({Name: 'Pedro', store: r.id}).exec(function(err, result){ 316 | Customer.create({Name: 'Juan', store: r.id}).exec(function(err1, res1){ 317 | return res.json({ok: 'success'}); 318 | }); 319 | }); 320 | }); 321 | }, 322 | ``` 323 | 324 | Then retrieve the same way by using populate function: 325 | 326 | ```javascript 327 | viewStore: function(req, res){ 328 | Store.find().populate('customers').exec(function (err, result){ 329 | res.json({Result: result}); 330 | }); 331 | } 332 | ``` 333 | 334 | Spits out 335 | 336 | ```javascript 337 | { 338 | "Result": [ 339 | { 340 | "customers": [ 341 | { 342 | "Name": "Pedro", 343 | "store": 1, 344 | "id": 1, 345 | "createdAt": "2014-09-01T00:30:58.000Z", 346 | "updatedAt": "2014-09-01T00:30:58.000Z" 347 | }, 348 | { 349 | "Name": "Juan", 350 | "store": 1, 351 | "id": 2, 352 | "createdAt": "2014-09-01T00:30:58.000Z", 353 | "updatedAt": "2014-09-01T00:30:58.000Z" 354 | } 355 | ], 356 | "Name": 'Sari Sari Store', 357 | "id": 1, 358 | "createdAt": "2014-09-01T00:30:58.000Z", 359 | "updatedAt": "2014-09-01T00:30:58.000Z" 360 | } 361 | ] 362 | } 363 | 364 | ``` 365 | -------------------------------------------------------------------------------- /config/sockets.js: -------------------------------------------------------------------------------- 1 | /** 2 | * WebSocket Server Settings 3 | * (sails.config.sockets) 4 | * 5 | * These settings provide transparent access to the options for Sails' 6 | * encapsulated WebSocket server, as well as some additional Sails-specific 7 | * configuration layered on top. 8 | * 9 | * For more information on sockets configuration, including advanced config options, see: 10 | * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.sockets.html 11 | */ 12 | 13 | module.exports.sockets = { 14 | 15 | /*************************************************************************** 16 | * * 17 | * This custom onConnect function will be run each time AFTER a new socket * 18 | * connects (To control whether a socket is allowed to connect, check out * 19 | * `authorization` config.) Keep in mind that Sails' RESTful simulation for * 20 | * sockets mixes in socket.io events for your routes and blueprints * 21 | * automatically. * 22 | * * 23 | ***************************************************************************/ 24 | onConnect: function(session, socket) { 25 | 26 | // By default, do nothing. 27 | 28 | }, 29 | 30 | 31 | /*************************************************************************** 32 | * * 33 | * This custom onDisconnect function will be run each time a socket * 34 | * disconnects * 35 | * * 36 | ***************************************************************************/ 37 | onDisconnect: function(session, socket) { 38 | 39 | // By default: do nothing. 40 | }, 41 | 42 | 43 | /*************************************************************************** 44 | * * 45 | * `transports` * 46 | * * 47 | * A array of allowed transport methods which the clients will try to use. * 48 | * The flashsocket transport is disabled by default You can enable * 49 | * flashsockets by adding 'flashsocket' to this list: * 50 | * * 51 | ***************************************************************************/ 52 | // transports: [ 53 | // 'websocket', 54 | // 'htmlfile', 55 | // 'xhr-polling', 56 | // 'jsonp-polling' 57 | // ], 58 | 59 | /*************************************************************************** 60 | * * 61 | * Use this option to set the datastore socket.io will use to manage * 62 | * rooms/sockets/subscriptions: default: memory * 63 | * * 64 | ***************************************************************************/ 65 | 66 | // adapter: 'memory', 67 | 68 | /*************************************************************************** 69 | * * 70 | * Node.js (and consequently Sails.js) apps scale horizontally. It's a * 71 | * powerful, efficient approach, but it involves a tiny bit of planning. At * 72 | * scale, you'll want to be able to copy your app onto multiple Sails.js * 73 | * servers and throw them behind a load balancer. * 74 | * * 75 | * One of the big challenges of scaling an application is that these sorts * 76 | * of clustered deployments cannot share memory, since they are on * 77 | * physically different machines. On top of that, there is no guarantee * 78 | * that a user will "stick" with the same server between requests (whether * 79 | * HTTP or sockets), since the load balancer will route each request to the * 80 | * Sails server with the most available resources. However that means that * 81 | * all room/pubsub/socket processing and shared memory has to be offloaded * 82 | * to a shared, remote messaging queue (usually Redis) * 83 | * * 84 | * Luckily, Socket.io (and consequently Sails.js) apps support Redis for * 85 | * sockets by default. To enable a remote redis pubsub server, uncomment * 86 | * the config below. * 87 | * * 88 | * Worth mentioning is that, if `adapter` config is `redis`, but host/port * 89 | * is left unset, Sails will try to connect to redis running on localhost * 90 | * via port 6379 * 91 | * * 92 | ***************************************************************************/ 93 | 94 | // adapter: 'redis', 95 | // host: '127.0.0.1', 96 | // port: 6379, 97 | // db: 'sails', 98 | // pass: '' 99 | 100 | 101 | /*************************************************************************** 102 | * * 103 | * `authorization` * 104 | * * 105 | * Global authorization for Socket.IO access, this is called when the * 106 | * initial handshake is performed with the server. * 107 | * * 108 | * By default (`authorization: false`), when a socket tries to connect, * 109 | * Sails allows it, every time. If no valid cookie was sent, a temporary * 110 | * session will be created for the connecting socket. * 111 | * * 112 | * If `authorization: true`, before allowing a connection, Sails verifies * 113 | * that a valid cookie was sent with the upgrade request. If the cookie * 114 | * doesn't match any known user session, a new user session is created for * 115 | * it. (In most cases, the user would already have a cookie since they * 116 | * loaded the socket.io client and the initial HTML page.) * 117 | * * 118 | * However, in the case of cross-domain requests, it is possible to receive * 119 | * a connection upgrade request WITHOUT A COOKIE (for certain transports) * 120 | * In this case, there is no way to keep track of the requesting user * 121 | * between requests, since there is no identifying information to link * 122 | * him/her with a session. The sails.io.js client solves this by connecting * 123 | * to a CORS endpoint first to get a 3rd party cookie (fortunately this * 124 | * works, even in Safari), then opening the connection. * 125 | * * 126 | * You can also pass along a ?cookie query parameter to the upgrade url, * 127 | * which Sails will use in the absense of a proper cookie e.g. (when * 128 | * connection from the client): * 129 | * io.connect('http://localhost:1337?cookie=smokeybear') * 130 | * * 131 | * (Un)fortunately, the user's cookie is (should!) not accessible in * 132 | * client-side js. Using HTTP-only cookies is crucial for your app's * 133 | * security. Primarily because of this situation, as well as a handful of * 134 | * other advanced use cases, Sails allows you to override the authorization * 135 | * behavior with your own custom logic by specifying a function, e.g: * 136 | * * 137 | * authorization: function authSocketConnectionAttempt(reqObj, cb) { * 138 | * * 139 | * // Any data saved in `handshake` is available in subsequent * 140 | * requests from this as `req.socket.handshake.*` * 141 | * * 142 | * // to allow the connection, call `cb(null, true)` * 143 | * // to prevent the connection, call `cb(null, false)` * 144 | * // to report an error, call `cb(err)` * 145 | * } * 146 | * * 147 | ***************************************************************************/ 148 | 149 | // authorization: false, 150 | 151 | /*************************************************************************** 152 | * * 153 | * Whether to run code which supports legacy usage for connected sockets * 154 | * running the v0.9 version of the socket client SDK (i.e. sails.io.js). * 155 | * Disabled in newly generated projects, but enabled as an implicit default * 156 | * (i.e. legacy usage/v0.9 clients be supported if this property is set to * 157 | * true, but also if it is removed from this configuration file or set to * 158 | * `undefined`) * 159 | * * 160 | ***************************************************************************/ 161 | 162 | // 'backwardsCompatibilityFor0.9SocketClients': false, 163 | 164 | /*************************************************************************** 165 | * * 166 | * Whether to expose a 'get /__getcookie' route with CORS support that sets * 167 | * a cookie (this is used by the sails.io.js socket client to get access to * 168 | * a 3rd party cookie and to enable sessions). * 169 | * * 170 | * Warning: Currently in this scenario, CORS settings apply to interpreted * 171 | * requests sent via a socket.io connection that used this cookie to * 172 | * connect, even for non-browser clients! (e.g. iOS apps, toasters, node.js * 173 | * unit tests) * 174 | * * 175 | ***************************************************************************/ 176 | 177 | // grant3rdPartyCookie: true, 178 | 179 | /*************************************************************************** 180 | * * 181 | * Match string representing the origins that are allowed to connect to the * 182 | * Socket.IO server * 183 | * * 184 | ***************************************************************************/ 185 | 186 | // origins: '*:*', 187 | 188 | }; 189 | -------------------------------------------------------------------------------- /views/500.ejs: -------------------------------------------------------------------------------- 1 | 2 | 36 | 37 | 38 | Server Error 39 | 40 | 47 | 48 | 49 |
50 |
51 |
52 | 53 | 54 |
55 |
56 |
57 |

58 | Internal Server Error 59 |

60 |

61 | Something isn't right here. 62 |

63 | <% if (typeof error !== 'undefined') { %> 64 |

65 |         	<%- error %>
66 |         
67 | <% } else { %> 68 |

69 | A team of highly trained sea bass is working on this as we speak.
70 | If the problem persists, please contact the system administrator and inform them of the time that the error occured, and anything you might have done that may have caused the error. 71 |

72 | <% } %> 73 | 74 |
75 | 76 | 79 |
80 | 81 | 82 | --------------------------------------------------------------------------------