Mock Server Lite
Get a full REST API with zero coding in less than 30 seconds (seriously)
Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.
This is the lite version of MocK Server.
Note: This lite version doesn't support db add, update, clone route in homepage, fetch
related routeConfigs and helper middlewares like _IterateResponse
, _IterateRoutes
etc...
Table of contents
Getting started
Install Mock Server
npm install -g @r35007/mock-server
Create a db.json
file with some data.
{
"posts": [{ "id": 1, "title": "mock-server", "author": "r35007" }],
"comments": [{ "id": 1, "body": "some comment", "postId": 1 }],
"profile": { "name": "r35007" }
}
Start Mock Server
mock-server --watch ./db.json
Now if you go to http://localhost:3000/posts/1, you'll get
{ "id": 1, "title": "mock-server", "author": "r35007" }
Using JS Module
First install nodemon for watching changes
npm install -g nodemon
Create server.js
File
const { MockServer } = require("@r35007/mock-server");
const mockServer = new MockServer("./config.json");
mockServer.launchServer(
"./db.json",
"./injectors.json",
"./middleware.js",
"./rewriters.json",
"./store.json"
);
const app = mockServer.app;
const rewriter = mockServer.rewriter("./rewriters.json");
app.use(rewriter);
const defaults = mockServer.defaults({ noGzip: true });
app.use(defaults);
const resources = mockServer.resources(
"./db.json",
"./injectors.json",
"./middleware.js",
"./store.json"
);
app.use(resources);
const defaultRoutes = mockServer.defaultRoutes();
app.use(defaultRoutes);
app.use(mockServer.pageNotFound);
app.use(mockServer.errorHandler);
mockServer.startServer(3000, "localhost");
Now go to terminal and type the following command to start the Mock Server.
nodemon server.js
Route Config
Create a db.json file. Pay attention to start every route with /.
For Example:
db.json
{
"/route/1, /route/2": {
// /route/1 and /route/2 shares the same config and mock data
"_config": true, // Make sure to set this to true to use this object as a route configuration.
"id": "id-unique", // sets a base64 encoded route
"description": "", // Description about this Route.
"delay": 2000, // in milliseconds
"statusCode": 200, // in number between 100 to 600
"middlewares": ["CustomLog"], // list of middleware names to be called
"mock": [{ "name": "foo" }, { "name": "bar" }],
"store": {} // helps to store any values for later use
},
"/routeName3": {
"name": "foo",
"age": "bar",
"description": "Note: Since _config attribute is not set to true this whole object will be sent as a response"
}
}
Set Delay Response
delay
helps you to set a custom delay to your routes.
Note : The delay yo set must be in milliseconds and of type number
{
"/customDelay": {
"_config": true,
"delay": 2000,
"description": "Note: give delay in milliseconds",
"mock": "This is response is received with a delay of 2000 milliseconds"
}
}
Now if you go to http://localhost:3000/customDelay, you'll get the response in a delay of 2 seconds.
Set Custom StatusCode
statusCode
helps you set a custom statusCode to your routes.
It must be of type number and between 100 to 600.
{
"/customStatusCode": {
"_config": true,
"statusCode": 500,
"mock": "This is response is received with a statusCode of 500"
}
}
Now if you go to http://localhost:3000/customStatusCode, you'll get the response with a 500
statusCode
Add Middleware
You can add n number of middleware to a route which helps you to manipulate or log the data.
middleware.js
exports.DataWrapper = (req, res, next) => {
res.locals.data = {
status: "Success",
message: "Retrieved Successfully",
result: res.locals.data,
};
next();
};
db.json
{
"/users/customMiddleware": {
"_config": true,
"description": "Note: This middleware must be available in the 'middleware.js' by the below given names. This 'DataWrapper' will be called on every hit of this route.",
"mock": { "name": "foo" },
"middlewares": ["DataWrapper"]
}
}
Note: A middleware must be available at the name of the middlewares given in db.json
http://localhost:3000/users/customMiddleware.
Injectors
Injectors helps to inject a Route Configs explicitly.
This also helps to provide a common route configs.
Injector uses path-to-regexp
pattern recognition to set config for multiple routes.
Inject Route Configs
Here we are explicitly injecting delay
, middlewares
, statusCode
to the /posts
route.
You can any route configs to a specific or to a group of routes using Injectors.
- Injectors use
path-to-regexp
package for route pattern recognition. - Click path-to-regexp for more details.
example : injectors.json
[
{
"routes": ["/injectors/:id"],
"description": "This description is injected using the injectors by matching the pattern '/injectors/:id'."
}
]
Override Existing Route Configs
Setting override
flag to true helps to override the existing config of that route.
For example :
injectors.json
[
{
"routes": ["/injectors/2"],
"override": true,
"mock": "This data is injected using the injectors by matching the pattern '/injectors/2'."
},
{
"routes": ["/injectors/:id"],
"override": true,
"exact": true,
"statusCode": 200,
"mock": "This data is injected using the injectors by exactly matching the route '/injectors/:id'."
},
{
"routes": ["/(.*)"],
"override": true,
"middlewares": ["...", "CustomLog"]
}
]
Note: Use ["..."]
If you want to add the existing middlewares.
Common Route Configs
Using wildcards you can set a common route configs to all the routes.
/(.*)
- matches all the routes.
For example :
injectors.json
[
{
"routes": ["/(.*)"],
"description": "This Description is injected using the injectors. Set 'Override' flag to true to override the existing config values."
},
{
"routes": ["/(.*)"],
"override": true,
"middlewares": ["...", "CustomLog"]
}
]
Make sure you give /(.*)
at the end of the injectors.json
object to set route configs to all the routes.
Store Data
Store used to store any values which can be used later for any purpose like response manipulation or logging etc..
Route Store
Route store helps to store any values which can be accessed on by that particular route.
This stores values cannot be able to accessed by the other routes.
Route Store can be accessed using res.locals.routeConfig.store
inside the middleware.
Local Store
Local Store helps to store and share data between routes.
This can be accessed using res.locals.getStore()
inside the middleware.
Route Rewriters
Create a rewriters.json
file. Pay attention to start every route with /
.
- Rewriters use
express-urlrewrite
package to rewrite the urls. - Click here for more information about url rewrite.
{
"/api/*": "/$1",
"/:resource/:id/show": "/:resource/:id",
"/posts/:category": "/posts?category=:category",
"/articles?id=:id": "/posts/:id"
}
server.js
const mockServer = MockServer.Create();
mockServer.launchServer(
"./db.json",
"./injectors.json",
"./middleware.js",
"./rewriters.json"
);
Now you can access resources using additional routes.
/api/posts
/api/posts/1
/posts/1/show
/posts/javascript
/articles?id=1
Locals
res.locals
helps to access the current route config, store
etc..
Here are the available options in res.locals
interface Locals {
routePath: string;
routeConfig: {
_config?: boolean;
id?: string;
description?: string;
mock?: any;
store?: object;
statusCode?: number;
delay?: number;
middlewares?: string[] | Array<express.RequestHandler>;
};
data: any;
config: Config;
getStore: () => object;
getDb: () => object;
}
Config
you can provide your own config by passing the config object in the MockServer
constructor. For Example :
server.js
:
const config = {
port: 3000,
host: "localhost",
root: process.cwd(),
base: "/",
staticDir: "public",
reverse: false,
bodyParser: true,
id: "id",
logger: true,
noCors: false,
noGzip: false,
readOnly: false,
};
new MockServer(config).launchServer("./db.json");
Default Routes
CLI Usage
$ mock-server --help
Options:
-c, --config Path to config file [string]
-P, --port Set port [default: 3000]
-H, --host Set host [default: "localhost"]
-m, --middleware Paths to middleware file [string]
-i, --injectors Path to Injectors file [string]
-s, --store Path to Store file [string]
-r, --rewriters Path to Rewriter file [string]
--staticDir, --sd Set static files directory [string]
-b, --base Set base route path [string]
--readOnly, --ro Allow only GET requests [boolean]
--noCors, --nc Disable Cross-Origin Resource Sharing [boolean]
--noGzip, --ng Disable GZIP Content-Encoding [boolean]
-l, --logger Enable logger [boolean] [default: true]
--sample, --ex Create Sample [boolean] [default: false]
-w, --watch Watch file(s) [boolean] [default: false]
-S, --snapshots Set snapshots directory [default: "."]
-h, --help Show help [boolean]
-v, --version Show version number [boolean]
Examples:
index.js db.json
index.js --watch db.json
index.js --sample --watch
index.js http://jsonplaceholder.typicode.com/db
https://r35007.github.io/Mock-Server/
API
MockServer
returns the instance of the mockServer.
const { MockServer } = require("@r35007/mock-server");
const mockServer = new MockServer("./config.json");
Params
Name | Type | Required | Description |
---|
config | string / object | No | This object sets the port, host etc.. |
Create
returns the single instance of the mockServer.
const { MockServer } = require("@r35007/mock-server");
const mockServer = MockServer.Create("./config.json");
Params
Name | Type | Required | Description |
---|
config | string / object | No | This object sets the port, host etc.. |
Destroy
stops the server and clears the instance of the mockServer.
returns promise
const { MockServer } = require("@r35007/mock-server");
const mockServer = MockServer.Create();
await MockServer.Destroy();
await MockServer.Destroy(mockServer);
launchServer
It validates all the params in the MockServer, loads the resources and starts the server.
mockServer.launchServer(
"./db.json",
"./injectors.json",
"./middleware.js",
"./rewriters.json",
"./store.json"
);
Params
Name | Type | Required | Description |
---|
db | string / object | No | This object generates the local rest api. |
injectors | string / object | No | Helps to inject a route configs for the existing routes |
middleware | string / object | No | Here you initialize the needed custom middleware |
rewriters | string / object | No | Helps to set route rewriters |
store | string / object | No | Helps to store values and share between routes |
rewriter
Sets the route rewrites and return the router of the rewriters;
const rewriters = mockServer.rewriter("./rewriters.json");
app.use(rewriters);
Params
Name | Type | Required | Description |
---|
rewriters | string / object | No | Give the Rewrites |
defaults
returns the list of default middlewares.
Also helps to host a static directory.
const defaults = mockServer.defaults({ staticDir: "./public", readOnly: true });
app.use(defaults);
- options
staticDir
path to static fileslogger
enable logger middleware (default: true)bodyParser
enable body-parser middleware (default: true)noGzip
disable Compression (default: false)noCors
disable CORS (default: false)readOnly
accept only GET requests (default: false)
resources
Sets the routes and returns the resources router.
const resources = mockServer.resources(
"./db.json",
"./injectors.json",
"./middleware.js",
"./store.json"
);
app.use(resources);
Params
Name | Type | Required | Description |
---|
db | string / object | No | This object generates the local rest api. |
injectors | string / object | No | Helps to inject a route configs for the existing routes |
middleware | string / object | No | Here you initialize the needed custom middleware |
store | string / object | No | Helps to store values and share between routes |
defaultRoutes
Returns router with some default routes.
const defaultsRoutes = mockServer.defaultRoutes();
app.use(defaultsRoutes);
addDbData
adds a new data to the existing db.
mockServer.addDbData(db);
Params
Name | Type | Required | Description |
---|
db | object | No | Give the new data to add to existing Db |
startServer
Returns a Promise of Server
. - helps to start the app server externally
const server = await mockServer.startServer(3000, "localhost");
Params
Name | Type | Required | Description |
---|
port | number | No | Set custom Port |
host | string | No | Set custom Host |
stopServer
Returns a Promise of Boolean. - helps to stop the app server externally
const isStopped = await mockServer.stopServer();
resetServer
Clears out all values and resets the server for a fresh start.
By default this method will be called on mockServer.stopServer()
method.
mockServer.resetServer();
pageNotFound
It is a middleware to handle a page not found error.
Please use it at the end of all routes.
app.use(mockServer.pageNotFound);
errorHandler
It is a middleware to handle a any error occur in server.
Please use it at the end of all routes.
app.use(mockServer.errorHandler);
Setters
set the db, middleware, injectors, rewriters, config, store
mockServer.setData(db, middleware, injectors, rewriters, store, config);
mockServer.setConfig(config);
mockServer.setMiddlewares(middlewares);
mockServer.setInjectors(injectors);
mockServer.setRewriters(rewriters);
mockServer.setStore(store);
mockServer.setDb(Db, { reverse });
Params
The same as the MockServer
Variables
Other useful variables.
const app = mockServer.app;
const server = mockServer.server;
const router = mockServer.router;
const data = mockServer.data;
const db = mockServer.db;
const middleware = mockServer.middleware;
const injectors = mockServer.injectors;
const rewriters = mockServer.rewriters;
const config = mockServer.config;
const store = mockServer.store;
const initialDb = mockServer.initialDb;
const initialStore = mockServer.initialStore;
Validators
These helps to return a valid data from provided file path or object.
const {
getValidDb,
getValidMiddlewares,
getValidInjectors,
getValidRewriters,
getValidConfig,
getValidStore,
getValidRouteConfig,
} = require("@r35007/mock-server/dist/server/utils/validators");
const options = {
reverse: true,
};
const rootPath = "./";
const db = getValidDb(
"db.json",
[],
rootPath,
options
);
const middleware = getValidMiddlewares(middlewares, rootPath);
const injectors = getValidInjectors(injectors, rootPath);
const rewriters = getValidRewriters(rewriters, rootPath);
const config = getValidConfig(config, rootPath);
const store = getValidStore(store, rootPath);
const routeConfig = getValidRouteConfig(route, routeConfig);
const injectorConfig = getValidInjectorConfig(route, routeConfig);
const route = getValidRoute(route);
Author
Sivaraman - sendmsg2siva.siva@gmail.com
License
MIT