3.12.0 • Published 2 years ago

the-fake-backend v3.12.0

Weekly downloads
235
License
ISC
Repository
github
Last release
2 years ago

the-fake-backend

build Coverage Status NPM Version NPM Downloads Publish Size

Build a fake backend by providing the content of files or JavaScript objects through configurable routes. This service allows the developer to work on a new feature or an existing one using fake data while the real service is in development.

Installing

Start by adding the service as a development dependency.

yarn add --dev the-fake-backend

or

npm i --save-dev the-fake-backend

Getting Started

After installing, create a new file that will be responsible for configuring and starting the service.

const { createServer } = require('the-fake-backend');

const server = createServer();

server.routes([
  {
    path: '/example',
    methods: [
      {
        type: 'get', // or MethodType.GET with Typescript
        data: 'your-response-data-here',
        // data: (req) => 'your-response-data-here-based-in-request'
      },
    ],
  },
]);

server.listen(8080);

This will create the http://localhost:8080/example endpoint.

Files

You can also use files content as response instead of using the data property.

const { createServer } = require('the-fake-backend');

const server = createServer();

server.routes([
  {
    path: '/cats',
    methods: [
      {
        type: 'get', // or MethodType.GET with Typescript
      },
    ],
  },
  {
    path: '/dogs',
    methods: [
      {
        type: 'get', // or MethodType.GET with Typescript
        file: 'data/my/custom/path/to/dogs.txt',
        // file: req => `data/my/custom/path/to/dogs-${req.query.type}.txt`
      },
    ],
  },
]);

server.listen(8080);

The script above generates the following two endpoints.

MethodPathResponse
GEThttp://localhost:8080/catsThe data/cats.json file content
GEThttp://localhost:8080/dogsThe data/my/custom/path/to/dogs.txt file content

Properties

Server

PropertyRequiredDescription
basePathnoAn API context prefix (e.g. /v1)
middlewaresnoAn array of express's middlewares
proxiesnoThe server proxies
throttlingsnoThe server throttlings
paginationnoThe server pagination setup
docsRoutenoThe route that will print all the routes as HTML
definitionsnoThe GraphQL definitions.

Proxies

This property allows to proxy requests.

PropertyRequiredDefaultDescription
proxies[].nameyesThe proxy name
proxies[].hostyesThe proxy host (e.g.: http://api.dev.com/api)
proxies[].appendBasePathNofalseWhether basePath should be appended in target
proxies[].onProxyReqNoA proxy request handler to forward to http-proxy-middleware
proxies[].onProxyResNoA proxy response handler to forward to http-proxy-middleware

Throttlings

This property allows responses to be throttled.

PropertyRequiredDescription
throttlings[].nameyesCustom throttling name
throttlings[].valuesyesCustom throttling range (array of numbers, in ms)

Pagination

This property allows routes to be paginated. Response attributes may be printed in response payload (wrapping the given fixture) or headers. Request parameters are read from URL query string.

PropertyRequiredDefaultTypeDescription
countno'count'Response attributeCurrent page items count
datano'data'Response attributeCurrent page data
emptyno'empty'Response attributeWhether if current page is empty
firstno'first'Response attributeWhether if current page is the first one
headersnofalseConfigurationWhether response attributes will be present in headers
lastno'last'Response attributeWhether if current page is the last one
nextno'next'Response attributeWhether if there is a next page
offsetParameterno'offset'Request parameterRequested offset
pageno'page'Response attributeCurrent page
pageParameterno'page'Request parameterRequested page
pagesno'pages'Response attributePages count
sizeParameterno'size'Request parameterRequested page size
totalno'total'Response attributeTotal items count

Routes

PropertyRequiredDescription
routes[].pathyesThe endpoint address (URI).
routes[].methodsyesThe route methods, check the method's properties table below.

Methods

PropertyTypeRequiredDefaultDescription
methods[].typestringyesHTTP request type
methods[].codenumberno200HTTP response status code
methods[].dataany | (req) => anynoHTTP response data. May also be a function with request
methods[].filestring | (req) => stringno/data/${req.path}HTTP response data fixture file (when data is not given). May also be a function with request
methods[].headersobject | (req) => objectnoHTTP response headers. May also be a function with request
methods[].delaynumbernoHTTP response delay/timeout, in milliseconds
methods[].searchobjectnoSearch parameters
methods[].paginationboolean | objectnofalseWhether data is paginated or not. May also be a pagination object
methods[].overridesobject[]noCustom response scenarios (switchable in CLI)
methods[].overrideContent(req, content) => anynoA function to override response content before send

Search

This property allows routes to be searchable.

PropertyTypeRequiredDefaultDescription
parameterstringyes'search'Query string parameter name
propertiesstring[]yesAn array of properties to apply the search

Overrides

This property allows you to create an array of options that will override the current method option.

PropertyTypeRequiredDefaultDescription
overrides[].namestringyesScenario name
overrides[].codenumberno200Described above
overrides[].dataany | (req) => anynoDescribed above
overrides[].filestring | (req) => stringnoDescribed above
overrides[].headersobject | (req) => objectnoDescribed above
overrides[].delaynumbernoDescribed above
overrides[].searchobjectnoDescribed above
overrides[].paginationboolean | objectnofalseDescribed above
overrides[].overrideContent(req, content) => anynoDescribed above
overrides[].selectedbooleannofalseDescribed above

GraphQL

We're using apollo-server-express to integrate the GraphQL Server to the the-fake-backend. When you have the definitions property, the server will enable the GraphQL's related endpoints.

MethodPathResponse
GEThttp://localhost:8080/graphqlThe graphical interactive in-browser GraphQL IDE
POSThttp://localhost:8080/graphqlThe queries and mutations response

Queries

The service searches for a JSON file inside the graphl/queries/ folder using the query name, for example, the query below tries to respond with the graphl/queries/getPerson.json file's content.

const { createServer } = require('the-fake-backend');

const serverOptions = {
  definitions: `
    type Person {
      id: String
      name: String
      age: Int
    }

    type Query {
      getPerson(id: String): Person
    }
  `,
};

const server = createServer(serverOptions);

server.listen(8080);

Mutations

The same happens to the mutations, for example, the mutation below tries to respond with the graphl/mutations/createPerson.json file's content.

const { createServer } = require('the-fake-backend');

const serverOptions = {
  definitions: `
    type Person {
      id: String
      name: String
      age: Int
    }

    input PersonInput {
      name: String
      age: Int
    }

    type Mutation {
      createPerson(person: PersonInput): Person
    }
  `,
};

const server = createServer(serverOptions);

server.listen(8080);

The GraphQL's endpoints does not have support for throttlings, proxies, pagination, overridings and search at the moment, we are still working on these features.

Guides

Overriding responses

When a request is made the server will check if the method object contains the overrides property and if there is one override selected through the property selected. If there is an override selected it will be merged with the method object.

Example

const server = createServer({ ... })

server.routes([
  {
    path: '/user',
    methods: [
      {
        type: 'get', // or MethodType.GET with Typescript
        file: 'data/my/custom/path/to/client-user.json',
        overrides: [
          {
            name: 'Staff',
            file: 'data/my/custom/path/to/staff-user.json'
          },
          {
            name: 'Super Admin',
            file: 'data/my/custom/path/to/super-admin-user.json'
          },
          {
            name: 'Error 500',
            code: 500
          }
        ]
      }
    ]
  }
]);

// curl -XGET http://localhost:8080/user
// Returns `data/my/custom/path/to/client-user.json` file content.

Press 'o' on terminal and change the URL '/user' with method 'get' with override 'Super Admin'

// curl -XGET http://localhost:8080/user
// Returns `data/my/custom/path/to/super-admin-user.json` file content.

Overriding response content

You can override the response content after all the processing (file/data content, pagination, search, etc.).

Example

// /data/dogs.json
[
  { "id": 1, "name": "Doogo" },
  { "id": 2, "name": "Dogger" },
  { "id": 3, "name": "Dog" },
  { "id": 4, "name": "Doggernaut" },
  { "id": 5, "name": "Dogging" }
]
const { createServer } = require('the-fake-backend');

const server = createServer();

server.routes([
  {
    path: '/dogs',
    methods: [
      {
        type: 'get', // or MethodType.GET with Typescript
        overrideContent: (req, content) => ({
          ...content,
          { id: 6, name: 'Bulldog' }
        })
      },
    ],
  },
]);

server.listen(8080);

Searching

You can make an endpoint searchable by declaring the search property in a route.

Example

// /data/dogs.json
[
  { "id": 1, "name": "Doogo" },
  { "id": 2, "name": "Dogger" },
  { "id": 3, "name": "Dog" },
  { "id": 4, "name": "Doggernaut" },
  { "id": 5, "name": "Dogging" }
]
const { createServer } = require('the-fake-backend');

const server = createServer();

server.routes([
  {
    path: '/dogs',
    methods: [
      {
        type: 'get', // or MethodType.GET with Typescript
        search: {
          parameter: 'search',
          properties: ['name'],
        },
      },
    ],
  },
]);

server.listen(8080);

You can now make requests to the http://localhost:8080/dogs?search=dogg endpoint. The response will be the data/dogs.json file content filtered.

[
  { "id": 2, "name": "Dogger" },
  { "id": 4, "name": "Doggernaut" },
  { "id": 5, "name": "Dogging" }
]

Paginating

You can make an endpoint paginated by declaring the pagination options in the server (just in case of overriding default values), adding pagination parameter in a route and visiting it with pagination query string parameters.

Route pagination parameter may be a boolean (true) to use global pagination options, or pagination object parts to override global ones.

Note: The pagination is zero-based, so 0 is the first page.

Example

// /data/dogs.json
[
  { "id": 1, "name": "Doogo" },
  { "id": 2, "name": "Dogger" },
  { "id": 3, "name": "Dog" },
  { "id": 4, "name": "Doggernaut" },
  { "id": 5, "name": "Dogging" }
];
const { createServer } = require('the-fake-backend');

const server = createServer(); // if pagination isn't given, default values will be applied

server.routes([
  {
    path: '/dogs',
    methods: [
      {
        type: 'get', // or MethodType.GET with Typescript
        pagination: true,
        // pagination: { headers: true } // only this request will have pagination parameters in response headers
      },
    ],
  },
]);

server.listen(8080);

Then, given a http://localhost:8080/dogs?page=1&size=2 request, the following payload will be returned:

{
  "count": 2,
  "empty": false,
  "first": true,
  "last": false,
  "next": true,
  "page": 1,
  "pages": 3,
  "total": 5,
  "data": [
    { "id": 3, "name": "Dog" },
    { "id": 4, "name": "Doggernaut" }
  ]
}

Note: given http://localhost:8080/dogs?offset=2&size=2 the payload would be the same. Offset attribute has precedence over page.

If headers attribute was set to true in server options (or route pagination options):

const server = createServer({
  pagination: {
    headers: true,
  },
});

Then the metadata attributes would be printed in response headers and the response payload would be the following:

[
  { "id": 3, "name": "Dog" },
  { "id": 4, "name": "Doggernaut" }
]

Dynamic params requests

Just like in Express, route requests may have dynamic params:

const { createServer } = require('the-fake-backend');

const server = createServer();

server.routes([
  {
    path: '/dogs/:id/details',
    methods: [
      {
        type: 'get', // or MethodType.GET with Typescript
      },
    ],
  },
]);

Given a matching HTTP request, e.g. http://localhost:8080/dogs/3/details, the server will search the following fixtures, sorted by precedence:

  1. data/dogs/3/details.json
  2. data/dogs/:id/details.json

If the request has multiple dynamic params, the precedence is the same, searching the fullly specific fixture, and the fully generic one otherwise.

Contributing

Setup library

  1. Clone this repository
  2. Run npm install to install dependencies
  3. Run npm start to start rollup in watch mode
  4. Have fun!

Example application

This repository already have an example application that already install last built version from the-fake-backend before run.

To start this application:

  1. Go to example folder
  2. Run npm install to install dependencies
  3. Run npm start to start example application
3.10.0

2 years ago

3.12.0

2 years ago

3.11.0

2 years ago

3.9.2

2 years ago

3.9.1

2 years ago

3.9.0

2 years ago

3.8.1

2 years ago

3.8.0

3 years ago

3.7.0

3 years ago

3.6.0

3 years ago

3.5.3

3 years ago

3.4.0

3 years ago

3.3.0

3 years ago

3.5.2

3 years ago

3.5.1

3 years ago

3.5.0

3 years ago

3.2.1

3 years ago

3.2.0

3 years ago

3.1.0

3 years ago

3.0.3

4 years ago

3.0.2

4 years ago

3.0.1

4 years ago

3.0.0

4 years ago

2.3.0

4 years ago

2.4.0

4 years ago

2.2.0

4 years ago

2.1.0

4 years ago

2.0.0

4 years ago

1.6.0

4 years ago

1.5.0

4 years ago

1.4.0

4 years ago

1.3.0

4 years ago

1.2.0

4 years ago

1.1.0

4 years ago

1.0.13

4 years ago

1.0.12

4 years ago

1.0.11

4 years ago

1.0.10

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.0.0

4 years ago