0.1.0 • Published 4 years ago

the-mock v0.1.0

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

The-Mock npm.io GitHub license

  • Create & Delete REST API End-Points dynamically from a deployed the-mock server.
  • First mock server where mock data are stored in NoSQL "MongoDB" Database and not locally, thus these mock data are created once and can be shared across all Front-End development team.
  • It is useful for companies which both Back-End & Front-End teams work parallelly.
  • Created for both Front-End developers and testers who needs a quick RESTful API back-end solution, in case there is none.
  • No coding involved, it has a nice UI and with few clicks a mock end-point can be created.
  • It can be deployed to an online server.

Table of contents

Installation

The choice is yours:

  • npm i the-mock
  • yarn add the-mock

Getting Started

To run The-Mock Server successfully, 3 steps need to be handled.

Create a MongoDB database

If you already have a MongoDB, skip to the second step. If not:

  • Visit MongoDB Atlas and create a DB as a service, it's FREE FOREVER when you choose: "M0 - Standard RAM & 512MB storage".
  • OR Install MongoDB locally on your machine.

Important Notes:

  • the-mock server will use both MongoDB models 'p' & 'r' to store mock data. 'p': stands for Paths, while 'r': for path Resources.
  • It's recommeneded to use MongoDB Atlas, so the mock data can be shared across Front-End development team. Here is the Atlas Documentation explaining how to create one.

Create a config.json file

Inside the root project folder create config.json file to link the-mock server with MongoDB and to handle CORS issue by passing response headers.

config.json file contains:

  • "db":
    • "url": here you need to add your MongoDB URL that you just created in Step 1, whether it's from Atlas or local DB.
    • "options": an object which will be passed on to your MongoDB driver, it can be blank object though.
  • "headers":
    • "all": response headers for ALL REST Api calls.
    • "options": response headers for only OPTIONS method REST Api calls.

Note: you can copy this config.json, then only change db.url to link to your db.

{
    "db": {
        "url": "mongodb://localhost:27017/the-mock",
        "options": {
            "useNewUrlParser": true,
            "useUnifiedTopology": true
        }
    },
    "headers": {
        "all": {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "*",
            "Access-Control-Allow-Credentials": true
        },
        "options": {
            "Access-Control-Allow-Methods": "GET,HEAD,PUT,PATCH,POST,DELETE"
        }
    }
}

Create a server.js file

The-Mock Server is created using Express JS, thus it needs a starting point to run. Inside the root project folder create server.js file:

// server.js
const http = require('http');
const theMock = require('the-mock');

const port = process.env.PORT || 3000;
theMock.setConfig('config.json');
const server = http.createServer(theMock);

server.listen(port, () => {
    console.log(`The-Mock server is running on Port ${port}`);
    console.log(`open your browser on http://localhost:${port}`);
});

then run the-mock server by this commad node server.js.

The-Mock server GUI

The-Mock server has a friendly GUI which can easily lead you to create mock end-points. just navigate to:

Mock Rest Api Creation

To create a Mock Rest Api successfully, 2 steps need to be handled.

Create a path

The path is all your URL except your domain, paths must be unique. exmaples:

  • List: /api/v1.0/users
  • Singular: /api/v1.0/users/12
  • Query: /api/v1.0/users?department=EDU&year=1992.

Important Notes:

  • For a Singular Path, avoid this format: /api/v1.0/users/{id}, as the-mock server reads the end-point exactly as it is. There is no changing in path's variables.
  • Both /p/* & /r/* are reserved paths and cannot be mock.
  • To call your end-point: http://your-domain/your-path. e.g: http://localhost:3000/api/v1.0/users/12
  • Before Calling your mock end-point, at least one resource must be created.

Create a resource

Basically each path has many resources e.g: GET, POST, PUT, DELETE ..etc, and to create one click on a specific path. It will navigate you to Resources page. How to create a resource ? when you click on + sign a box will show up that contains:

  • "method": type "" sting only. It's required field and must be unique.
  • "headers": type {} object only. It can be an empty {} object or removed, if you don't need headers.
  • "reqBody": type {} object or [] Array. It can be Removed, if you don't need a request body.
  • "success": it's the successful response, which consists of:
    • "statusCode": type "" sting or integer, it's HTTP response status code. "200" is the default value.
    • "resBody": type any, it's response body data.
  • "error": it's the failed response, which consists of:
    • "statusCode": type "" sting or integer, it's HTTP response status code. "500" is the default value.
    • "resBody": type any, it's response body data.

Important Notes:

  • Only "method" is required to fill in, and it must be unique. Other fileds can be Removed.
  • Create resource form must be a valid JSON format.
  • All form field keys are case-sensitive. Meaning "method" is not equal to "METHOD". In order for the-mock server to work successfully, avoid changeing/adding any key names.
  • After creating a resource, try calling the end-point using Browser, Postman ..etc.

How to achieve a Success/Error response

The-Mock server compares request Api call data with the data stored in the-mock database. If they are EXACTLY EQUAL "===". The-Mock returns a seccessful response, otherwise it returns a failed response. In other words:

  • Successful Response: reqData === dbData.
  • Error Response: reqData !== dbData.

Success/Error Examples

Request Api CallThe-Mock Stored DataResponseReason
path: /api/v1.0/posts method: GET headers: {}path: /api/v1.0/posts method: GET headers: {}successEXACTLY EQUAL "==="
path: /api/v1.0/posts/2 method: GET headers: { "authorization": "Bearer blahBlah" }path: /api/v1.0/posts/1 method: GET headers: { "authorization": "Bearer fake-jwt" }errorrequest path should be /posts/1 request headers should be { "authorization": "Bearer fake-jwt" }
path: /api/v1.0/posts/2 method: GET headers: { "authorization": "Bearer fake-jwt" }path: /api/v1.0/posts/2 method: GET headers: { "authorization": "Bearer fake-jwt" }successEXACTLY EQUAL "==="
path: /api/v1.0/posts method: PUT headers: { "authorization": "Bearer fake-jwt" } body: { "title": "the Mock 1", "content": "the easiest way to mock end-points" }path: /api/v1.0/posts method: POST headers: { "authorization": "Bearer fake-jwt" } reqBody: { "title": "The Mock", "content": "the easiest way to mock end-points" }errorrequest method should be "POST" request body.title should be "The Mock", it's also case-sensitive: t should be T
path: /api/v1.0/posts?department=GOV&year=1990 method: GET headers: {}path: /api/v1.0/posts?department=EDU&year=1992 method: GET headers: {}errorrequest path query should be department=EDU&year=1992

License

Code licensed under MIT.