### Example: Creating Sails Project in Existing Empty Directory Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailsnew.md This example demonstrates creating a Sails project in an existing, empty directory. The output confirms the project creation after dependency installation. ```text $ cd myProject $ sails new . info: Installing dependencies... Press CTRL+C to skip. (but if you do that, you'll need to cd in and run `npm install`) info: Created a new Sails app `my-project`! ``` -------------------------------- ### Sails Lift Example Output Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailslift.md This is an example of the output when running `sails lift`. It shows the app starting, the Sails version, and server details like the environment and port. ```text $ sails lift info: Starting app... info: info: info: Sails <| info: v1.0.0 |\ info: /|.\ info: / || \ info: ,' |' \ info: .-'.-==|/_--' info: `--'-------' info: __---___--___---___--___---___--___ info: ____---___--___---___--___---___--___-__ info: info: Server lifted in `/Users/mikermcneil/code/sandbox/second` info: To see your app, visit http://localhost:1337 info: To shut down Sails, press + C at any time. debug: -------------------------------------------------------- debug: :: Sat Apr 05 2014 17:03:39 GMT-0500 (CDT) debug: Environment : development debug: Port : 1337 debug: -------------------------------------------------------- ``` -------------------------------- ### Example: Creating a New Sails Project Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailsnew.md This example shows the output when creating a new Sails project named 'test-project'. It includes information about dependency installation and project creation confirmation. ```text $ sails new code/testProject info: Installing dependencies... Press CTRL+C to skip. (but if you do that, you'll need to cd in and run `npm install`) info: Created a new Sails app `test-project`! ``` -------------------------------- ### Install Winston Logger Source: https://github.com/balderdashy/sails/blob/master/docs/reference/sails.config/sails.config.log.md Install the Winston logging library as a project dependency. ```bash npm install winston ``` -------------------------------- ### Install Consolidate.js Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/Views/ViewEngines.md Install the Consolidate.js library using npm. This is a prerequisite for easily integrating various view engines. ```bash npm install consolidate --save ``` -------------------------------- ### Example Sails Console Output Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailsconsole.md This is an example of the output you will see when starting the `sails console`. It indicates the app is starting in interactive mode and provides instructions for exiting. ```text $ sails console info: Starting app in interactive mode... info: Welcome to the Sails console. info: ( to exit, type + ) sails> ``` -------------------------------- ### Install Skipper-S3 Adapter Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/File Uploads/uploading-to-amazon-s3.md Install the skipper-s3 adapter using npm. This is the first step to enable S3 uploads. ```sh npm install skipper-s3 --save ``` -------------------------------- ### Install skipper-gridfs Adapter Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/File Uploads/uploading-to-mongo-gridfs.md Install the skipper-gridfs npm package to enable GridFS uploads. This is a prerequisite for using the adapter. ```sh npm install skipper-gridfs --save ``` -------------------------------- ### Install sails-mysql Adapter Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/extending-sails/Adapters/adapterList.md Use this command to install the sails-mysql adapter. It is recommended to save it as a dependency. ```bash npm install sails-mysql --save ``` -------------------------------- ### Example Socket POST Request Source: https://github.com/balderdashy/sails/blob/master/docs/reference/websockets/sails.io.js/socket.post.md An example demonstrating how to use `io.socket.post()` to send user data and handle the server's response. ```javascript io.socket.post('/users', { name: 'Timmy Mendez' }, function (resData, jwRes) { jwRes.statusCode; // => 200 }); ``` -------------------------------- ### Example: Find Newest Purchases Source: https://github.com/balderdashy/sails/blob/master/docs/reference/blueprint-api/Find.md This example demonstrates how to find up to 30 of the newest purchases by sorting on 'createdAt' in descending order and limiting the results. ```text GET /purchase?sort=createdAt DESC&limit=30 ``` -------------------------------- ### Install Beta Version of Sails.js Source: https://github.com/balderdashy/sails/blob/master/docs/faq/faq.md To install a pre-release version of Sails.js for testing upcoming features, use the 'beta' tag. This command installs the version corresponding to the 'beta' branch in the Sails repository. ```bash npm install sails@beta ``` -------------------------------- ### Install Supertest for Development Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/Testing/Testing.md Install Supertest as a development dependency using npm. ```bash npm install supertest --save-dev ``` -------------------------------- ### Example Output of sails --version Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailsversion.md This is an example of the output you can expect when running the `sails --version` command. ```text 1.0.0 ``` -------------------------------- ### Install Mocha for Development Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/Testing/Testing.md Install Mocha as a development dependency using npm. ```bash npm install mocha --save-dev ``` -------------------------------- ### Install and Configure node-p3p Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/Security/P3P.md Install the 'p3p' module using npm and configure it in `config/http.js` using the recommended compact privacy policy. ```sh # In your sails app npm install p3p --save ``` ```javascript // ... // node-p3p provides a recommended compact privacy policy out of the box p3p: require('p3p')(require('p3p').recommended) // ... ``` -------------------------------- ### Example Request - Add Purchase to Employee Involvement Source: https://github.com/balderdashy/sails/blob/master/docs/reference/blueprint-api/Add.md This example demonstrates adding purchase #47 to the list of purchases employee #7 is involved in. ```bash PUT /employee/7/involvedInPurchases/47 ``` -------------------------------- ### Install lusca Middleware Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/Security/Clickjacking.md Install the lusca middleware package using npm. This is the first step to enable X-FRAME-OPTIONS. ```sh # In your sails app npm install lusca --save ``` -------------------------------- ### Example io.socket.get() Usage Source: https://github.com/balderdashy/sails/blob/master/docs/reference/websockets/sails.io.js/socket.get.md This example demonstrates how to fetch user data by ID using `io.socket.get()`. The callback function processes the received user data. ```javascript io.socket.get('/users/9', function (resData) { // resData => {id:9, name: 'Timmy Mendez'} }); ``` -------------------------------- ### Install Sails from Git Repository (Edge) Source: https://github.com/balderdashy/sails/blob/master/docs/contributing/code-submission-guidelines/best-practices.md Install the latest development version of Sails directly from its GitHub repository. ```sh npm install sails@git://github.com/balderdashy/sails.git ``` -------------------------------- ### Example: Broadcasting user login event Source: https://github.com/balderdashy/sails/blob/master/docs/reference/websockets/sails.sockets/sails.sockets.blast.md An example of broadcasting a 'user_logged_in' event with user details to all sockets, omitting the requesting socket if it's a socket request. ```javascript sails.sockets.blast('user_logged_in', { msg: 'User #' + user.id + ' just logged in.', user: { id: user.id, username: user.username } }, req); ``` -------------------------------- ### Example: Ensure User Exists Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/models/findOrCreate.md This example demonstrates how to use .findOrCreate() with a callback to ensure a user record exists, logging whether it was created or found. ```javascript User.findOrCreate({ name: 'Finn' }, { name: 'Finn' }) .exec(async(err, user, wasCreated)=> { if (err) { return res.serverError(err); } if(wasCreated) { sails.log('Created a new user: ' + user.name); } else { sails.log('Found existing user: ' + user.name); } }); ``` -------------------------------- ### Example: Replace User's Pets Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/models/replaceCollection.md Example demonstrating how to replace all pets associated with User ID 3 with pets 99 and 98. ```javascript await User.replaceCollection(3, 'pets') .members([99,98]); ``` -------------------------------- ### Example PATCH Request with Callback Source: https://github.com/balderdashy/sails/blob/master/docs/reference/websockets/sails.io.js/socket.patch.md This example demonstrates sending a PATCH request to update a user's occupation and logging the response status code. ```javascript io.socket.patch('/users/9', { occupation: 'psychic' }, function (resData, jwr) { resData.statusCode; // => 200 }); ``` -------------------------------- ### Install MySQL Adapter for Sails Source: https://github.com/balderdashy/sails/blob/master/docs/reference/sails.config/sails.config.connections.md Install the sails-mysql adapter using npm. Use --save --save-exact to ensure exact versioning. ```bash npm install sails-mysql --save --save-exact ``` -------------------------------- ### Example Request for Find One Source: https://github.com/balderdashy/sails/blob/master/docs/reference/blueprint-api/FindOne.md This example shows how to request a specific purchase record with ID 1. ```text GET /purchase/1 ``` -------------------------------- ### Install Mocha Testing Framework Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/ORM/standalone-usage.md Installs the Mocha testing framework globally using npm. This is a prerequisite for running the provided integration tests. ```bash $ npm install -g mocha ``` -------------------------------- ### Server-side .unsubscribe() Example Source: https://github.com/balderdashy/sails/blob/master/docs/reference/websockets/resourceful-pubsub/unsubscribe.md This example demonstrates unsubscribing from `User` records named 'Lenny'. It first finds the users, extracts their IDs, and then calls `.unsubscribe()`. ```javascript unsubscribeFromUsersNamedLenny: function (req, res) { if (!req.isSocket) { return res.badRequest(); } User.find({name: 'Lenny'}).exec(function(err, lennies) { if (err) { return res.serverError(err); } var lennyIds = _.pluck(lennies, 'id'); User.unsubscribe(req, lennyIds); return res.ok(); }); }, ``` -------------------------------- ### Accessing Request Start Time Source: https://github.com/balderdashy/sails/blob/master/docs/reference/req/req._startTime.md Use this property to get the timestamp when Sails started processing the request. Note that this property is not added in production mode. ```javascript req._startTime; ``` -------------------------------- ### Create and fetch a user record Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/models/create.md Example demonstrating how to create a user and fetch the created record to log its ID. Note the use of .fetch(). ```javascript var createdUser = await User.create({name:'Finn'}).fetch(); sails.log('Finn\'s id is:', createdUser.id); ``` -------------------------------- ### Example: Realtime Cafeteria Order System Source: https://github.com/balderdashy/sails/blob/master/docs/reference/websockets/sails.io.js/io.socket.on.md A comprehensive example demonstrating how to use `io.socket.on()` to handle 'order' events for a realtime cafeteria system, including creating and destroying orders. ```APIDOC ## Example: Realtime Cafeteria Order System ### Description This example illustrates a frontend implementation for a realtime ordering system. It listens for 'order' socket events and updates the UI to reflect newly created or destroyed orders. ### Method GET (Implicit, for initial data load) POST /io/socket/on (for event subscription) ### Endpoint Client-side JavaScript ### Parameters #### Query Parameters - **eventName** (string) - 'order' - The specific event to listen for. #### Request Body (Not directly applicable for the `on` call itself, but the handler receives a `msg` object) ### Request Example ```javascript // In your frontend code... var ORDER_IN_LIST = _.template('
  • <%- order.summary %>

  • '); $(function whenDomIsReady(){ // Every time we receive a relevant socket event... io.socket.on('order', function onServerSentEvent (msg) { // Let's see what the server has to say... switch(msg.verb) { case 'created': (function(){ // Render the new order in the DOM. var newOrderHtml = ORDER_IN_LIST(msg.data); $('#orders').append(newOrderHtml); })(); return; case 'destroyed': (function(){ // Find any existing orders w/ this id in the DOM. var $deletedOrders = $('#orders').find('[data-id="'+msg.id+'"]'); // Then, if there are any, remove them from the DOM. $deletedOrders.remove(); })(); return; // Ignore any unrecognized messages default: return; }//< / switch > });//< / io.socket.on() > });//< / when DOM is ready > ``` ### Response #### Success Response (200) (No direct response for `on`, but subsequent event messages are received) #### Response Example (Example of a 'created' message) ```json { "verb": "created", "data": { "id": 123, "summary": "Order for Pizza" } } ``` (Example of a 'destroyed' message) ```json { "verb": "destroyed", "id": 123 } ``` ### Notes - This example assumes the backend uses methods like `.publish()` or `.broadcast()` to send messages. - The frontend relies on the server broadcasting messages related to record changes or custom events. ``` -------------------------------- ### Create and Fetch Users Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/models/createEach.md Example of creating two user records and fetching them back. Logs the number of created users. ```javascript var createdUsers = User.createEach([{name:'Finn'}, {name: 'Jake'}]).fetch(); sails.log(`Created ${createdUsers.length} user${createdUsers.length===1?'':'s'}.`); ``` -------------------------------- ### Example of .fetch() with .create() Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/queries/fetch.md Demonstrates how to use `.fetch()` with a `.create()` query to retrieve the newly created user record. The fetched record includes its assigned ID. ```javascript var newUser = await User.create({ fullName: 'Alice McBailey' }).fetch(); sails.log(`Hi, ${newUser.fullName}! Your id is ${newUser.id}.`); ``` -------------------------------- ### Launch node-inspector Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailsdebug.md After installing node-inspector, launch it from your terminal. This will start the inspector, making it ready to connect to your Sails app. ```bash node-inspector ``` -------------------------------- ### Making a Virtual GET Request with Custom Headers and Data Source: https://github.com/balderdashy/sails/blob/master/docs/reference/websockets/sails.io.js/socket.request.md An example of using `io.socket.request()` to perform a virtual GET request to '/user/3/friends'. It includes custom data and headers, and handles potential errors by checking `jwres.error` and logging the status code. ```javascript io.socket.request({ method: 'get', url: '/user/3/friends', data: { limit: 15 }, headers: { 'x-csrf-token': 'ji4brixbiub3' } }, function (resData, jwres) { if (jwres.error) { console.log(jwres.statusCode); // => e.g. 403 return; } console.log(jwres.statusCode); // => e.g. 200 }); ``` -------------------------------- ### Create and Fetch User with .meta() Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/queries/meta.md Use `.meta({fetch: true})` to create a new record and return the newly created instance. This is useful when you need to immediately work with the created record. ```javascript var newUser = await User.create({name: 'alice'}).meta({fetch: true}); return res.json(newUser); ``` -------------------------------- ### Example: Accessing a query parameter Source: https://github.com/balderdashy/sails/blob/master/docs/reference/req/req.query.md If the request URL is GET /search?q=mudslide, this code will return the value "mudslide". ```javascript req.query.q // -> "mudslide" ``` -------------------------------- ### Basic Sails Action Example Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/ActionsAndControllers/ActionsAndControllers.md A simple asynchronous action that sends a text response. This is bound to a route like GET /hello. ```javascript async function (req, res) { return res.send('Hi there!'); } ``` -------------------------------- ### Run Sails App Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailslift.md Use this command to start your Sails application in the current directory. If `node_modules/sails` exists, it will be used instead of the globally installed Sails. ```bash sails lift ``` -------------------------------- ### Access Request Subdomains Source: https://github.com/balderdashy/sails/blob/master/docs/reference/req/req.subdomains.md Use `req.subdomains` to get an array of subdomains from the request URL. For example, if the URL is 'https://ww3.staging.ibm.com', this property will return ['ww3', 'staging']. ```javascript req.subdomains; ``` ```javascript req.subdomains; // -> ['ww3', 'staging'] ``` -------------------------------- ### Get Local Sails Version in Project Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailsversion.md To check the version of Sails installed specifically within a project's `node_modules/` folder, use this npm command. ```bash npm ls sails ``` -------------------------------- ### Using .meta() for Fetching Records Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/queries/meta.md This example demonstrates how to use the `.meta({fetch: true})` option to fetch the newly created user record. The `.fetch()` method is a shorthand for this. ```APIDOC ## POST /user ### Description Creates a new user and fetches the created record. ### Method POST ### Endpoint /user ### Parameters #### Request Body - **name** (string) - Required - The name of the user. ### Request Example ```json { "name": "alice" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the created user. - **name** (string) - The name of the created user. #### Response Example ```json { "id": 1, "name": "alice" } ``` ``` -------------------------------- ### Get Global Sails CLI Version Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailsversion.md Run this command to display the version of the Sails CLI installed globally on your system. For local project versions, use `npm ls sails`. ```bash sails --version ``` -------------------------------- ### Dynamic Connection Management with Driver Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/datastores/driver.md Demonstrates how to use the datastore driver to dynamically create a connection manager, acquire a connection, perform operations, and then tear down the manager. Ensure to handle potential errors and clean up resources. ```javascript // Get the generic, stateless driver for our database (e.g. MySQL). var Driver = sails.getDatastore().driver; // Create our own dynamic connection manager (e.g. connection pool) var manager = ( await Driver.createManager({ connectionString: req.param('connectionUrl') }) ).manager; var db; try { db = ( await Driver.getConnection({ manager: managerReport.manager }) ).connection; } catch (err) { await Driver.destroyManager({ manager: managerReport.manager }); throw err; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Do some stuff here... // e.g. // await Driver.sendNativeQuery({ // connection: db, // nativeQuery: '...' // }); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Finally, before we continue, tear down the dynamic connection manager. // (this also takes care of releasing the active connection we acquired above) await Driver.destroyManager({ manager: managerReport.manager }); return res.ok(); ``` -------------------------------- ### Classic Sails Action Example Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/ActionsAndControllers/ActionsAndControllers.md This action looks up a user by ID, then displays a welcome view or redirects to signup if the user is not found. It uses `req.param()` to get input and `res.view()` or `res.redirect()` for responses. ```javascript module.exports = async function welcomeUser (req, res) { // Get the `userId` parameter from the request. // This could have been set on the querystring, in // the request body, or as part of the URL used to // make the request. var userId = req.param('userId'); // If no `userId` was specified, or it wasn't a number, return an error. if (!_.isNumeric(userId)) { return res.badRequest(new Error('No user ID specified!')); } // Look up the user whose ID was specified in the request. var user = await User.findOne({ id: userId }); // If no user was found, redirect to signup. if (!user) { return res.redirect('/signup' ); } // Display the welcome view, setting the view variable // named "name" to the value of the user's name. return res.view('welcome', {name: user.name}); } ``` -------------------------------- ### Sails.js Model Generation Commands Source: https://github.com/balderdashy/sails/blob/master/docs/reference/blueprint-api/Add.md These shell commands demonstrate how to generate the 'purchase' and 'employee' models required for the socket notification examples. This setup is necessary for associations involving collections and foreign keys. ```shell $ sails new foo $ cd foo $ sails generate model purchase $ sails generate model employee ``` -------------------------------- ### Create and Query MySQL Connection Natively Source: https://github.com/balderdashy/sails/blob/master/docs/tutorials/low-level-mysql-access.md Create a new MySQL connection using the `mysql` module obtained from the datastore and execute queries. This example demonstrates creating a connection with credentials and then using a stream for query results. ```javascript // Get the named datastore var rdi = sails.getDatastore('default'); // Grab the MySQL module from the datastore instance var mysql = rdi.driver.mysql; // Create a new connection var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'password', database: 'example_database' }); // Make a query and pipe the results connection.query('SELECT * FROM posts') .stream({highWaterMark: 5}) .pipe(...); ``` -------------------------------- ### Install Sails.js Globally Source: https://github.com/balderdashy/sails/wiki/Home Installs the Sails.js framework globally on your system using npm. Ensure Node.js is installed first. ```sh sudo npm install -g sails ``` -------------------------------- ### Install Sails.js Globally Source: https://github.com/balderdashy/sails/blob/master/README.md Installs the latest stable release of Sails.js globally using npm. Requires Node.js and npm to be installed. ```sh # Get the latest stable release of Sails $ npm install sails -g ``` -------------------------------- ### Create and Associate User and Pet Models Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/ORM/standalone-usage.md Demonstrates creating a user and a pet, associating them via an owner reference, and saving the changes. Use `save` on model instances returned by queries, not on collection objects. ```javascript const user = await User.create({ firstName: 'Neil', lastName: 'Armstrong' }).fetch(); const pet = await Pet.create({ name: 'Astro', breed: 'beagle', type: 'dog', owner: user.id }).fetch(); await User.addToCollection(user.id, 'pets', pet.id); const foundUser = await User.findOne(user.id).populate('pets'); console.log(JSON.stringify(foundUser, null, 2)); ``` -------------------------------- ### Install and Configure Published Generator Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/extending-sails/Generators/customGenerators.md Install a generator published on NPM using 'npm install'. Then, update the .sailsrc file to reference the NPM package name instead of a local path. ```bash npm install @my-npm-name/sails-generate-awesome ``` -------------------------------- ### Create Users Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/models/createEach.md Example of creating two user records in the database. ```javascript await User.createEach([{name:'Finn'}, {name: 'Jake'}]); ``` -------------------------------- ### Bootstrap Waterline Objects Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/ORM/standalone-usage.md Initializes the Waterline factory, an adapter instance, and the main Waterline instance. This is the first step in setting up Waterline. ```javascript var Waterline = require('waterline'); var sailsDiskAdapter = require('sails-disk'); var waterline = new Waterline(); ``` -------------------------------- ### Configure Waterline Adapters and Datastores Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/ORM/standalone-usage.md Sets up the 'disk' adapter and defines a 'default' datastore that uses this adapter. This configuration tells Waterline how and where to store data. ```javascript var config = { adapters: { 'disk': sailsDiskAdapter }, datastores: { default: { adapter: 'disk' } } }; ``` -------------------------------- ### Initialize Waterline and Perform Operations Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/ORM/standalone-usage.md Initializes the Waterline instance with the provided configuration, then creates a user and a pet, associating the pet with the user. Finally, it finds all users and populates their pets. ```javascript waterline.initialize(config, (err, ontology)=>{ if (err) { console.error(err); return; } // Tease out fully initialized models. var User = ontology.collections.user; var Pet = ontology.collections.pet; // Since we're using `await`, we'll scope our selves an async IIFE: (async ()=>{ // First we create a user var user = await User.create({ firstName: 'Neil', lastName: 'Armstrong' }); // Then we create the pet var pet = await Pet.create({ breed: 'beagle', type: 'dog', name: 'Astro', owner: user.id }); // Then we grab all users and their pets var users = await User.find().populate('pets'); console.log(users); })() .then(()=>{ // All done. }) .catch((err)=>{ ``` -------------------------------- ### Install Latest Sails Version Source: https://github.com/balderdashy/sails/blob/master/docs/contributing/code-submission-guidelines/best-practices.md Install the latest stable version of Sails from npm. ```sh npm install sails ``` -------------------------------- ### Install lusca for CSP Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/Security/ContentSecurityPolicy.md Install the lusca package as a development dependency in your Sails.js application. ```sh npm install lusca --save --save-exact ``` -------------------------------- ### Example Base URL Output Source: https://github.com/balderdashy/sails/blob/master/docs/reference/application/advanced-usage/sails.getBaseUrl.md This is an example of the string returned by sails.getBaseUrl() when using HTTP. ```javascript http://localhost:1337 ``` -------------------------------- ### Update User Record Example Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/models/updateOne.md This example shows how to update a user's first name from 'Pen' to 'Finn' using .updateOne(). It includes logging to indicate whether the update was successful or if no user named 'Pen' was found. ```javascript var updatedUser = await User.updateOne({ firstName:'Pen' }) .set({ firstName:'Finn' }); if (updatedUser) { sails.log('Updated the user named "Pen" so that their new name is "Finn".'); } else { sails.log('The database does not contain a user named "Pen".'); } ``` -------------------------------- ### Install node-inspector globally Source: https://github.com/balderdashy/sails/blob/master/docs/reference/cli/sailsdebug.md Before using Node Inspector to debug your Sails app, install it globally using npm. ```bash npm install -g node-inspector ``` -------------------------------- ### With .populate() Example Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/models/stream.md A snippet of a command-line script that searches for creepy comments from someone named "Bailey Bitterbumps" and reports them to the authorities. ```javascript // e.g. in a shell script var numReported = 0; await Comment.stream({ author: 'Bailey Bitterbumps' }) .limit(1000) .skip(40) .sort('title ASC') .populate('attachedFiles', { limit: 3, sort: 'updatedAt' }) .populate('fromBlogPost') .eachRecord(async (comment)=>{ var isCreepyEnoughToWorryAbout = comment.rawMessage.match(/creepy/) && comment.attachedFiles.length > 1; if (!isCreepyEnoughToWorryAbout) { return; } await sails.helpers.sendTemplateEmail.with({ template: 'email-creepy-comment-notification', templateData: { url: `https://blog.example.com/${comment.fromBlogPost.slug}/comments/${comment.slug}.` }, to: 'authorities@cannedmeat.gov', subject: 'Creepy comment alert' }); numReported++; }); sails.log(`Successfully reported ${numReported} creepy comments.`); ``` -------------------------------- ### Example Request Body for Creating a User Source: https://github.com/balderdashy/sails/blob/master/docs/reference/blueprint-api/Create.md Send body parameters with the same names as the model attributes to set values on the new record. This example creates a user with a name, hobby, and associated purchases. ```json { "name": "Applejack", "hobby": "pickin", "involvedInPurchases": [13,25] } ``` -------------------------------- ### Initialize Project for Standalone Waterline Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/ORM/standalone-usage.md Set up a new directory for your standalone Waterline project. This involves creating a directory, navigating into it, and initializing a Node.js project using npm init. ```sh mkdir my-tool cd my-tool npm init ``` -------------------------------- ### Install sails-postgresql Adapter Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/extending-sails/Adapters/adapterList.md Install the sails-postgresql adapter using npm. This is the first step to connect Sails.js to a PostgreSQL database. ```bash npm install sails-postgresql --save ``` -------------------------------- ### Realtime Cafeteria Order System Example Source: https://github.com/balderdashy/sails/blob/master/docs/reference/websockets/sails.io.js/io.socket.on.md This example demonstrates handling 'order' socket events on the frontend to update a list of orders in real-time. It uses jQuery and Lodash to append new orders and remove deleted ones based on server messages. ```javascript var ORDER_IN_LIST = _.template('
  • <%- order.summary %>

  • '); $(function whenDomIsReady(){ // Every time we receive a relevant socket event... io.socket.on('order', function (msg) { // Let's see what the server has to say... switch(msg.verb) { case 'created': (function(){ // Render the new order in the DOM. var newOrderHtml = ORDER_IN_LIST(msg.data); $('#orders').append(newOrderHtml); })(); return; case 'destroyed': (function(){ // Find any existing orders w/ this id in the DOM. // // > Remember: To prevent XSS attacks and bugs, never build DOM selectors // > using untrusted provided by users. (In this case, we know that "id" // > did not come from a user, so we can trust it.) var $deletedOrders = $('#orders').find('[data-id="'+msg.id+'"]'); // Then, if there are any, remove them from the DOM. $deletedOrders.remove(); })(); return; // Ignore any unrecognized messages default: return; }//< / switch > });//< / io.socket.on() > });//< / when DOM is ready > ``` -------------------------------- ### Basic package.json for an Installable Hook Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/extending-sails/Hooks/installablehooks.md This is the minimum required `package.json` configuration for a Sails installable hook. Ensure `sails.isHook` is set to `true`. ```json { "name": "sails-hook-your-hook-name", "version": "0.0.0", "description": "a brief description of your hook", "main": "index.js", "sails": { "isHook": true } } ``` -------------------------------- ### Install sails-mongo Adapter Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/extending-sails/Adapters/adapterList.md Install the sails-mongo adapter using npm. This command is used to add MongoDB support to your Sails.js application. ```bash npm install sails-mongo --save ``` -------------------------------- ### Install Redis Session Packages Source: https://github.com/balderdashy/sails/blob/master/docs/concepts/Sessions/sessions.md If working with an upgraded Sails app, install the necessary Redis packages for session and socket.io adapters. ```bash npm install @sailshq/connect-redis npm install @sailshq/socket.io-redis ``` -------------------------------- ### Basic Usage Example Source: https://github.com/balderdashy/sails/blob/master/docs/reference/waterline/models/stream.md An action that iterates over users named Finn in the database, one at a time. ```javascript await User.stream({name:'Finn'}) .eachRecord(async (user)=>{ if (Math.random() > 0.5) { throw new Error('Oops! This is a simulated error.'); } sails.log(`Found a user ${user.id} named Finn.`); }); ```