Code Monkey home page Code Monkey logo

http-fake-backend's Introduction

GitHub version Build Status Coverage Status Dependency Status devDependency Status Unicorn

http-fake-backend

Build a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.

It actually can serve the content of other file types as well as sending the files itself as response.

Comes as a Node.js server. Useful for mocking, testing and developing independent of the »real« backend.

Sorry, this project is unmaintained 😢

Thanks to all contributors for your work!

We’ve just pushed a last release which fixes some bugs, make this thing run with Node 18.

Example

Let’s say you need an endpoint like http://localhost:8081/api/example which should return:

{
  "response": "Yeah"
}

It’s a matter of seconds to create this endpoint with help of this little hapi server.

It might take a few seconds longer as setting up the well-made JSON Server but it’s way more flexible.

Requirements

  • Node.js (18.12.0 or greater)

Install

git clone https://github.com/micromata/http-fake-backend.git
npm install

Or with help of Yeoman

npm install -g yo
npm install -g generator-http-fake-backend

This comes in handy, because the Yeoman generator has a sub-generator to setup endpoints of your fake backend very convenient. See https://github.com/micromata/generator-http-fake-backend.

Default Address

The server runs at http://localhost:8081/ providing a page with links to all existing API endpoints.

Start the server

There are the following two options.

During development

npm run start:dev

This way the server uses nodemon to restart itself on changes.

Later (eg. for tests in CI)

npm start

Just starts the server via node.

Configure endpoints

Each endpoint needs a configuration file in /server/api/ to define routes, http method and the response.

Example configurations

Simple Example

/server/api/simpleExample.js:

module.exports = SetupEndpoint({
    name: 'simpleExample',
    urls: [{
        requests: [
            { response: '/response-files/simpleExample.json' }
        ]
    }]
});

Advanced Example

/server/api/anotherExample.js:

module.exports = SetupEndpoint({
    name: 'anotherExample',
    urls: [{
        params: '/read',
        requests: [{
            method: 'GET',
            response: '/response-files/anotherExample.json'
        }]
    }, {
        params: '/update/{id}',
        requests: [{
            method: ['PUT', 'PATCH'],
            response: {
                success: true
            }
        }, {
            method: 'DELETE',
            response: {
                deleted: true
            }
        }]
    }, ]
});

Serving different content types

/server/api/fileTypes.js:

module.exports = SetupEndpoint({
    name: 'fileTypes',
    urls: [{
        params: '/json',
        requests: [{
            response: '/response-files/simpleExample.json'
        }]
    }, {
        params: '/text',
        requests: [{
            response: '/response-files/example.txt',
            mimeType: 'text/plain'
        }]
    }, {
        params: '/html',
        requests: [{
            response: '/response-files/example.html',
            mimeType: 'text/html'
        }]
    }, {
        params: '/pdf',
        requests: [{
            response: '/response-files/example.pdf',
            sendFile: true
        }]
    }]
});

Faking HTTP errors and status code

/server/api/fakingStatusCodes.js:

module.exports = SetupEndpoint({
    name: 'statusCodes',
    urls: [
        {
            params: '/boomError',
            requests: [{
                // Returns a 402 status code + error message provided by boom:
                // {
                //   "error" : "Payment Required",
                //   "message" : "Payment Required",
                //   "statusCode" : 402
                // }
                statusCode: 402
            }]
        },
        {
            params: '/customError',
            requests: [{
                // Returns a HTTP status code 406 and a self defined response:
                response: { error: true },
                statusCode: 406
            }]
        },
        {
            params: '/regularResponse',
            requests: [{
                // Returns a 401 error provided by boom
                // as defined on endpoint level
                response: '/response-files/anotherExample.json'
            }]
        }
    ],
    statusCode: 401
});

The configuration object in Detail:

  • name
    • Is used to set the endpoint.
  • urls
    • You need to add at least one url object.
  • urls.params
    • Optional
    • URL path parameters with fixed and/or variable path segments.
    • Example:
      • params: '/update/{id}'
    • See hapi docs. For example regarding optional path parameters.
  • urls.requests
    • You need to add at least one request object.
    • Multiple request objects are needed in case you like to serve different responses via different HTTP methods with the same URL.
  • urls.requests.method
    • optional. Uses GET when not defined.
    • string, or array of strings.
    • is used to define the http method(s) to which the endpoint will listen.
  • urls.requests.response
    • Could be a string pointing to a file:
      • response: '/response-files/articles.json'
    • Or just a JavaScript object:
      • response: { success: true }
  • urls.requests.mimeType
    • Optional (string). Defaults to application/json.
    • Is used to set the content-type response header.
  • urls.requests.sendFile
    • Optional (boolean). Defaults to false.
    • Sends the file as response instead of returning the file content.
  • urls.requests.statusCode
    • Optional (boolean). Defaults to 200
    • The HTTP status code of the response.
    • Will return:
      • a status code with a self defined response if you provide a response property
      • a status code with a predefined error object provided by boom if you dont provide a response property for that request.
  • statusCode
    • Optional
    • Every subroute of this endpoint will return a HTTP error with the given status code provided by boom.

Configure server

The main config is handled via a file named .env with the following content:

# NODE_ENV
# Could be either `development` or `production`
NODE_ENV=development

# Port of the Server
SERVER_PORT=8081

# Port for running the tests
TEST_PORT=9090

# URL Prefix for the endpoints
# eg. http://localhost:8081/api/foo
API_PREFIX=/api

# Custom response header
#CUSTOM_HEADER_NAME=Authorization
#CUSTOM_HEADER_VALUE=Bearer eyJhbGciOiJIUzUxMiJ9

Related

  • Yeoman Generator – Easily generate your fake backend and use sub-generators to setup endpoints like ⚡

License

Please be aware of the licenses of the components we use in this project. Everything else that has been developed by the contributions to this project is under MIT License.

http-fake-backend's People

Contributors

mischah avatar mppperez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

http-fake-backend's Issues

Cannot serve files (png)

'use strict';

const SetupEndpoint = require('./setup/setup.js');

module.exports = SetupEndpoint({
    name: 'attachment',
    urls: [{
                   params: '/{file}',
                   requests: [{
                       sendFile: true,
                       mimeType: 'application/pdf',
                       //response: '/attachments/1.png',

                       response: '/attachments/test.pdf'
                   }]
               }
               ]
});

I get the error message:

2018-02-06/16:40:42.573, [response] http://localhost:8081: get /api/app/v6/attachment/test.pdf {} 500 (51ms)
2018-02-06/16:40:44.721, [log,connection,client,error] message: Parse Error, stack: Error: Parse Error
    at Error (native)
2018-02-06/16:40:44.728, [log,info] data: Received payload:null
Debug: internal, implementation, error 
    /project/attachments/test.pdf:1
(function (exports, require, module, __filename, __dirname) { %PDF-1.3
                                                              ^

SyntaxError: Unexpected token %
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at handler (/project/server/api/setup/setup.js:40:44)
2018-02-06/16:40:44.724, [response] http://localhost:8081: get /api/app/v6/attachment/test.pdf {} 500 (25ms)

Feat: Add support for plain text response as alternative to JSON

Hey @mischah,
Very promising work! I landed here once the json-server has some limitations.

What I would like to know is how can I return a simple text in some cases.

E.g When I make a PUT request to /api/simpleExample/update/1 to get the text DONE

module.exports = SetupEndpoint({
    name: 'simpleExample',
    urls: [{
        requests: [...]
    },
    {
        params: '/update/{id}',
        requests: [{
            method: ['PUT', 'PATCH'],
            response: 'DONE'
        }, {
            method: 'DELETE',
            response: 'DELETED'
        }]
    }]
});

Thank you

Only getting response for GET Method

I am not able to get a response for a PUT method.I get the below
{"statusCode":405,"error":"Method Not Allowed","message":"Method Not Allowed"}
I get this for the default put example provided too.Could you please help me out with this.I might be missing something.

Does this support POST?

Hello,
does this support POST?

module.exports = SetupEndpoint({
name: 'anotherExample',
urls: [{
params: '/write',
requests: [{
method: 'POST',
response: '/response-files/anotherExample.json',
requestData: ??
}]
}]
});

feature: Support for query parameters

Hi.
Thows error when url like this

module.exports = SetupEndpoint({
    name: 'v1',
    urls: [{
        params: '/read?cmd=on-enter&pid=1414-414-567-3636',
        requests: [{
            method: 'GET',
            response: '/json-templates/anotherExample.json'
        }]
    }]
    }]
});

Respond with HTML

I would love to have the possibility to get a HTML from the fake-backend.
@krnlde told me he implemented this feature 'inofficial' already.

Error: New route X conflicts with existing Y

{
        {
            params: '/{id}/note/{noteId}',
            method: 'PUT'
        },
        {
            params: '/{id}/note/{noteId}',
            method: 'PATCH'
        }
}

This should work since there are different methods to the same endpoint, but it fails with the following message: Error: New route /api/salesItem/{id}/note/{noteId} conflicts with existing /api/salesItem/{id}/note/{noteId}

POST not working with node 16 / npm 8

Sending POST requests to the server is not working while using Node v16.14.0 and npm 8.3.2 but it works using node v14.19.0 npm v6.14.16.

Executing POST requests via our app or curl resulted in waiting for the response until it timed out. The server logs already printed that the response were written but it actually never were received. Restarting the server with node v14 and npm v6 made it working again.

Solution: updating all hapi libraries and making the appropriate changes. PR incoming.

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.