Variant Handlers
Preface
As described in the variants chapter:
Depending on the variant type, variants can be defined in many ways, from plain objects to plain text or even Express middlewares, and they act in different ways also, from sending a response to proxy the request to another host..
This is possible because the route variant itself does not contain the logic at charge of sending the response. Each route variant can be of a different type, and its type defines which Variant Handler is at charge of receiving the variant options and act in consequence.
This allows to add new Variant Handlers to provide more features to Mocks Server easily. For example, next variant handlers are included by default in the main distribution of Mocks Server:
json
: Defines the JSON body and the status code to be sent when the route is requested.text
: Defines the text body and the status code to be sent when the route is requested.status
: Defines a status code to be sent without body when the route is requested.middleware
: Defines an Express middleware to be executed when the request is received. It is completely on your hand to send a response, or to pass the request to the next route, etc.static
: Defines a folder from which to serve static assets.file
: Defines a file to transfer when the route is requested.proxy
: Defines a host to proxy the request when it is received. You can modify the request and/or the response also.
But, adding your own Variant Handlers, you would be able to create new types of variants allowing to:
- Read files in the
mocks
folder and create routes from your own format - Send an API response with a predefined body format
- etc...
Example
In the next example you can see how route variants define the handler to be used.
module.exports = [
{
id: "get-users",
url: "/api/users",
method: "GET",
variants: [
{
id: "success",
delay: 1000,
type: "json", // variant type. Corresponds to the Variant Handler id
options: { // options for the Variant Handler
status: 200,
body: [{ id: 1, name: "John Doe" }]
},
},
{
id: "all-users",
type: "file", // variant type. Corresponds to the Variant Handler id
options: { // options for the Variant Handler
status: 200,
path: "../fixtures/all-users.json",
},
},
{
id: "error",
type: "text", // variant type. Corresponds to the Variant Handler id
options: { // options for the Variant Handler
status: 403,
body: "An error ocurred"
},
}
]
}
];
Read the variants chapter for further info about defining route variants.