Giter VIP home page Giter VIP logo

synth-api's Introduction

SYNTH-API

Scans through the specified directory and builts endpoints that are then added to an Express app.

Each API endpoint is crafted by merely by giving it the name of the HTTP method it handles.

Synth-api is one of the major features provided by the Synth framework but is made available here for people who just want a stripped down module, and not the rest of the Synth framework (which includes support for asset compilation and more fun things).

Within your request handlers, you can either return data that will be JSONified and sent back to the client (useful for stubbing during development), a promise that will then return such data, or call the methods on the Express response object directly. See the examples below.

Build Status Code Climate Test Coverage

Example Usage

app.js:

var express = require('express');
var synthApi = require('synth-api');

var app = express();
synthApi.generateHandlers({
  resourceDir: __dirname + '/resources', // This is the default, not required
  prefix: '/api', // This is the default, not required
  app: app,
  timeout: 300
});

app.listen(80);

resources/tweets/tweets.js

// Return data directly, useful for stubbing during development
exports.getIndex = function (req, res) {
  return {
    tweets: [
      {
        message: "Fake tweet!",
        createdAt: new Date()
      }
    ]
  };
};

// Return a promise!
exports.get = function (req, res) {
  var id = req.params.id;
  return req.db.collection('tweets').findOne({
    id: id
  }).then(function (data) {
    return {
      tweet: data
    };
  });
};

// Or talk directly to Express response object
exports.post = function (req, res) {
  req.db.collection('tweets').insert({
    message: req.body.message,
    createdAt: new Date()
  }, function (err, data) {
    if (err) {
      res.status(500).send("Something went wrong: " + err.message);
    } else {
      res.send(data);
    }
  });
};

The above will create request handlers for the following routes:

  • GET /api/tweets
  • GET /api/tweets/:id
  • POST /api/tweets

You can also create nested resources, handlers for PUT and DELETE, as well as custom actions. Learn more at (synthjs.com)[http://www.synthjs.com/docs/#creating-api-endpoints]

generateHandlers(options)

Options

An object with the following keys (all are optional).

option Type Default What it does
prefix String '/api' Specifies what should precede the resource name for the generated routes.
resourceDir String process.cwd() + '/resources' The directory to look into for generating the API endpoints.
app ExpressApp null If given an Express app, it will have the API and view endpoints automatically attached.
timeout Number 5000 Time (in milliseconds) before an error response is returned to the client instead of the expected result.
catchAll Function null An optional Express style request handler to handle any requests to the api path that are not handled (regardless of HTTP method). Can be used to return a custom 404 error. Note: This function should not return data or a promise. It should use the Express response object directly.

Returns

generateHandlers() returns an object with a 'handers' key, which is an array of all the API handlers generated.

Each handler object contains the following keys:

  • file - String - Path to the js file that the API handler was found in.
  • method - String - The HTTP method that this handler respnds to. e.g. 'get', 'post', 'put', or 'delete'.
  • path - String - The URL path that the endpoint responds to. e.g. '/api/tweets'
  • isCustom - Boolean - Whether this handler is a custom method. This is good to know so that you register it before the non-custom methods. For example, you want '/api/tweets/favorites' to be registered with your Express apps before '/api/tweets/:id'.
  • funcName - String - The name of function. e.g. 'getIndex'
  • resources - Array[String] - The list of resources that this handler is a child of. e.g. the handler at '/api/tweets/1234/comments' would have a resources array of ['tweets', 'comments'].

Defining API endpoints

For this, just check out the existing Synth Documentation.

License

MIT

Credit

synth-api's People

Contributors

jonabrams avatar monthypython avatar

Watchers

Mikael Møller avatar James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.