Giter Club home page Giter Club logo

connect-api-mocker's Introduction

connect-api-mocker

connect-api-mocker is a connect.js middleware that fakes REST API server with filesystem. It will be helpful when you try to test your application without the actual REST API server.

Installation

npm install connect-api-mocker --save-dev

Usage

You can use it with Grunt. After you install grunt-contrib-connect add api-mocker middleware to your grunt config. The mocks/api folder will be served as REST API at /api.

module.exports = function(grunt) {
  var apiMocker = require('connect-api-mocker');

  grunt.loadNpmTasks('grunt-contrib-connect');  // Connect - Development server

  // Project configuration.
  grunt.initConfig({

    // Development server
    connect: {
      server: {
        options: {
          base: './build',
          port: 9001,
          middleware: function(connect, options) {

            var middlewares = [];

            // mock/rest directory will be mapped to your fake REST API
            middlewares.push(apiMocker(
                '/api',
                'mocks/api'
            ));

            // Static files
            middlewares.push(connect.static(options.base));
            middlewares.push(connect.static(__dirname));

            return middlewares;
          }
        }
      }
    }
  });
}

After you can run your server with grunt connect command. You will see /api will be mapped to mocks/api.

Directory Structure

You need to use service names as directory name and http method as filename. Files must be JSON. Middleware will match url to directory structure and respond with the corresponding http method file.

Example REST service: GET /api/messages

Directory Structure:

_ api
  \_ messages
     \_ GET.json

Example REST service: GET /api/messages/1

Directory Structure:

_ api
  \_ messages
     \_ 1
        \_ GET.json

Example REST service: POST /api/messages/1

Directory Structure:

_ api
  \_ messages
     \_ 1
        \_ POST.json

Example REST service: DELETE /api/messages/1

Directory Structure:

_ api
  \_ messages
     \_ 1
        \_ DELETE.json

Custom responses

If you want define custom responses you can use js files with a middleware function that handles requests.

Example REST service: POST /api/messages

Directory Structure:

_ api
  \_ messages
     \_ POST.js

POST.js file:

module.exports = function (request, response) {
  if (!request.get('X-Auth-Key')) {
    response.status(403).send({});
  } else {
    response.sendFile('POST.json', {root: __dirname});
  }
}

Another Example: Respond different json files based on a query parameter:

  • Request to /users?type=active will be responded by mocks/users/GET_active.json
  • Request to /users will be responded by mocks/users/GET.json

GET.js file:

module.exports = function (request, response) {
  var targetFileName = 'GET.json';
  
  // Check is a type parameter exist
  if (request.get('type')) {
    // Generate a new targetfilename with that type parameter
    targetFileName = 'GET_' + request.get('type') + '.json';
    
    // If file does not exist then respond with 404 header
    if (!fs.accessSync(targetFileName)) {
      return response.status(404);
    }
  }
  
  // Respond with targetFileName
  response.sendFile(targetFileName, {root: __dirname}
}

Bandwidth simulation

3rd parameter of api-mocker is for bandwidth limit. Metric is kilobit/sec and default value is 0(unlimited). You can use this to test your application in low bandwidth.

Example grunt configuration:

...
          middleware: function(connect, options) {

            var middlewares = [];

            // mock/rest directory will be mapped to your fake REST API
            middlewares.push(apiMocker(
                '/api',
                'mocks/api',
                50          // limit bandwidth to 50 kilobit/second
            ));
...

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.