Chapter 5. Custom backend code

 

This chapter covers

  • Setting up the initial state of your application
  • Introduction to custom asynchronous code in Sails
  • Counting the number of records in your database
  • Creating a new record in your database
  • Accessing a third-party API

Almost every commercial web application requires some way to run custom code “on lift,” before it begins listening for requests. This usually involves creating seed data, like admin user accounts. As we introduce custom backend code in this chapter, we’ll show how to use the config/bootstrap.js file to set up the data your application needs at startup.

Next, we’ll provide an introduction to communicating with third-party APIs. Specifically, we’ll show how to install open source packages from npm, and then take advantage of that preexisting code in your app (without having to write it yourself by hand!). In this chapter, we’ll demonstrate how to use Node machines—reusable helper functions with standardized arguments, errors, and return values—but the concepts you learn here apply for any open source package on npm.

Finally, in the process, we’ll explore some of the patterns (and anti-patterns) to look out for when writing custom logic for your Sails application, particularly as they relate to marshaling data and handling errors in synchronous versus asynchronous code.

5.1. Chad has a new investor

5.2. Running code on lift

5.3. A deeper understanding of model methods

5.4. Introducing machinepacks

5.5. Creating multiple records

5.6. Summary