npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sails-rest-adapter

v0.1.7

Published

rest adapter for Sails / Waterline

Downloads

2

Readme

image_squidhome@2x.png

waterline-rest Build Status

Provides easy access to RESTful APIs from Sails.js & Waterline.

This module is a Waterline/Sails adapter, an early implementation of a rapidly-developing, tool-agnostic data standard. Its goal is to provide a set of declarative interfaces, conventions, and best-practices for integrating with all sorts of data sources. Not just databases-- external APIs, proprietary web services, or even hardware.

Strict adherence to an adapter specification enables the (re)use of built-in generic test suites, standardized documentation, reasonable expectations around the API for your users, and overall, a more pleasant development experience for everyone.

Compatibility

sails-rest version 0.1.x is not backwards compatible with 0.0.x . In fact, version 0.1.x is a complete rewrite of the adapter and is compatible with Waterline 0.10.x and above.

Installation

To install this adapter, run:

$ npm install sails-rest

Configuration

Add the following config to the config/connections.js file:

module.exports.connections = {

  rest: {
    adapter: 'sails-rest',
    host:     'localhost:8080',  // api host
    protocol: 'http',            // api HTTP protocol
    pathname: '',                // api endpoint path name
    headers:  {},                // Optional HTTP headers
    hooks: {
      merge:    true,            // flag that indicates whether or not to merge build-in hooks with user-provided hooks
      before:   [],              // array of hook functions that run before a request
      after:    []               // array of hook functions that run after a request
    }
  }

};

Hooks

sails-rest supports defining before and after hooks that are executed before and after issuing an HTTP request respectively. Hooks are simply functions that conform to a specific signature and are run in sequence, allowing you to transform various parts of the request and response components.

Since REST APIs have various and individual implementations, hooks are sails-rest's way of letting the developer add custom logic to API calls without polluting the adapter's code.

before hooks

Before hooks will run in sequence before issuing an HTTP request and are defined in the hooks.before array on the configuration object.

Each hook must conform to the following signature:


/**
 * @param {Request} req - SuperAgent HTTP Request object
 * @param {String}  method - HTTP request method
 * @param {Object}  config - configuration object used to hold request-specific configuration. this is used to avoid polluting the connection's own configuration object.
 * @param {Object}  conn - connection configuration object:
 *    - {Object} connection - Waterline connection configuration object
 *    - {String} collection - collection name.
 *    - {Object} options - query options object. contains Waterline query conditions (where), sort, limit etc. as per Waterline's API.
 *    - {Array<Object>} values - values of records to create.
 * @param {Function} cb - function that is called when this hook finishes
 */
function someBeforeHook(req, method, config, conn, cb){
  // add custom logic here
}

Important!

If you choose not to merge the built-in hooks with your own hooks, you must provide a hook that creates an endpoint field on the config object. This field is used to resolve the HTTP request end-point.

after hooks

Before hooks will run in sequence after the HTTP request ends and are defined in the hooks.after array on the configuration object.

Each hook must conform to the following signature:

/**
 * Process HTTP response. Converts response objects date fields from Strings to Dates.
 * @param {Error} err - HTTP response error
 * @param {Response} res - SuperAgent HTTP Response object
 * @param {Function} cb - function that is called when this hook finishes
 */
function someAfterHook(err, res, cb){
  // add custom logic here
}

Build-in hooks

sails-rest comes in with two built-in before hooks and one build-in after hook.

before hook - HTTP end-point builder

This hook build the final HTTP endpoint from your host, protocol and pathname configurations, along with the collection name on which the adapter is configured, and optionally the record ID.

Given the default adapter host, scheme and pathname configuration, and a model named user, this hook will create the following HTTP endpoints:

  • find() - http://localhost:8080/user
  • find(id) - http://localhost:8080/user/:id
  • create() - http://localhost:8080/user
  • update() - http://localhost:8080/user
  • update(id) - http://localhost:8080/user/:id
  • delete() - http://localhost:8080/user
  • delete(id) - http://localhost:8080/user/:id
before hook - Query options cleaner

This hook removes the where object added by Waterline from request query options, and adds that object fields to the main options object.

Given the query options object {where: {first_name: "Tedd"}, sort: {first_name: 1}}, this hook will modify the query options object to: {first_name: "Tedd", sort: {first_name: 1}}.

This behaviour is useful and probably desired since most APIs are not likely to "understand" Waterline's query jargon.

after hook - response Date fields formatting

This hook iterates over HTTP response objects and looks for ISO formatted date strings on response object fields. If found, this fields will be converted into Javascript Date objects.

merging hooks

The adapter's configuration allows you to specify whether you wish to merge your own hooks with the above built-in hooks or not, by setting the hooks.merge flag to either true or false.

If you choose not to use the above built-in hooks, please make sure that the first before hook you supply creates an endpoint field on the config object, which points to the HTTP endpoint you wish to issue requests against.

If you're unsure, please take a look at the createEndpoint function inside lib/hooks.js

Interfaces

This adapter implements the semantic interface and exposes the following methods:

find()

Find one or more records. Translated to an HTTP GET request.

create()

Create one or more records. Translated to an HTTP POST request.

update()

Update one or more records. Translated to an HTTP PUT request.

destroy()

Destroy one or more records. Translated to an HTTP DELETE request.

Examples

See the examples folder for an example of simple model and CRUD operations in a Sails.js controller.

Arbitrary HTTP Requests

If your backend REST api does not conform to sails-rest / Waterline conventions of URL structure or HTTP verbs, you can always create your own HTTP queries and add them as static methods in your model.

See User.query in the User.js model example.

Sails.js Resources

License

MIT

© 2015 Zohar Arad

© 2014 balderdashy & contributors

Mike McNeil, Balderdash & contributors

Sails is free and open-source under the MIT License.