npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

the-mock

v0.1.0

Published

Create & Delete RESTful API End-Points dynamically from a deployed the-mock server

Downloads

6

Readme

The-Mock 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:

  • http://localhost:3000, if the-mock server is run locally.
  • http://your-domain, if the-mock server is deployed online.

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 Call | The-Mock Stored Data | Response | Reason | ---- | ---- | ---- | ---- | | path: /api/v1.0/posts method: GET headers: {} | path: /api/v1.0/posts method: GET headers: {} | success | EXACTLY 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" } | error | request 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" } | success | EXACTLY 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" } | error | request 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: {} | error | request path query should be department=EDU&year=1992 |

License

Code licensed under MIT.