thin2-mocker
v1.0.14
Published
CLI tool that generates a mock ExpressJS backend from an input Swagger 2.0 specification file.
Downloads
7
Readme
Thin2-mocker
Project that parses a given Swagger 2.0 spec file and generates a working ExpressJS API which validates input parameters and generates a mocked response object according to the given spec.
From version 1.0.2 on, the mocker also supports websocket definition.
As an important note, given that Swagger doesn't support socket
definition, all the socket definition is a custom implementation
documented here.
IMPORTANT: The current implementation only supports
Socket.io as the socket engine, other engines
can be added on request as long as there's NodeJS support for said engine.
As of version 1.0.4, custom response functions are supported. You can read more about what they are and how to use them here.
Version 1.0.14 improves file mock responses, allowing developers to configure responses for specific path parameter values. Further versions may also allow developers to define specific responses depending on query parameters.
At this point, it only supports YAML as input format, but JSON format may be implemented in the near future.
Install it!
You can easily install it using npm with the following command:
npm install -g thin2-mocker
Use it!
Thin2-mocker is very easy to use. All you have to do is download a local copy of the spec you want to mock and invoke the command line tool provided by the mocker component with the spec file path.
thin2-mocker C:\Development\api-swagger.yml
You can output the JSON file generated by the component after parsing
the Swagger spec file by using the output option. The generated file
will be named output.json.
For example:
thin2-mocker C:\Development\api-swagger.yml -o C:\Development
You can also use your own yml file to define custom responses for your
endpoints. This file can be allocated anywhere you want and is provided
to the CLI with the mock option.
For example:
thin2-mocker C:\Development\api-swagger.yml -m C:\Development\MockResponseFile.yml
Custom responses
IMPORTANT: As of 1.0.4, request parameter, headers and body validation is disabled, since all of the inner endpoint logic is forwarded to your function. Validation support has been added to the todo list.
Javascript function mock response
If you want to create custom responses from a JavaScript
file, you must create a js folder at the CLI execution
path, placing the Javascript mock functions inside it.
An example of the required folder structure is as follows:
- folder
|-- api-swagger.yml
|-- customResponseFunction.js
cd folder
thin2-mocker api-swagger.yml
The function has access to both ExpressJS' request and
response objects so you can perform any kind of parameter
extraction, validation or parsing and any kind of response
generation.
An example of a response function would be like this:
(request, response) => {
// Your custom logic goes here.
// As you can see, you've got access to both the request and response.
const resp = [];
response.json(resp);
};
Last but not least, in order to attach the function to a method inside an endpoint, you must use the x-th2-mocker-pre-fn attribute within the method; this attribute will let you specify the script file path.
Absolute paths are recommended to avoid running into issues when the mocker attempts to locate the function's source code; anyhow, you can still use relative paths, which will attempt to locate the scripts under the path the mocker was ran at.
You'll find an example of function definition below.
IMPORTANT: at this point int time, library usage within the custom response functions is not supported. We're not sure as of yet whether we want to implement something like that for a simple mock generator.
/historicLastData:
x-th2mocker-socket: false
get:
x-th2-mocker-pre-fn: historicLastData.js
operationId: historicLastData
summary: Endpoint that retrieves the historic for sockets.
description: |
Generates a *JSON* object which contains file system content data for the
input parameters query.
parameters:
- $ref: '#/parameters/ProductParameter'
- name: fileName
in: query
description: Filename to filter by.
required: false
type: string
- name: sortBy
in: query
description: Parameter to sort by.
required: false
type: string
tags:
- Search
responses:
200:
$ref: '#/responses/FilesDataResponse'
File mock responses
As of 1.0.6, you can now use a yml file to define custom
JSON responses for your service endpoints. In order to provide
the CLI tool with the mock file, you have to provide the option
mock with the mock responses file path.
You can find an example of the mock responses file below:
endpoints:
# Example returning an object
- data:
name: google
seo: high
method: get
uri: /firstSearchEngine
# Example returning an array
- data:
- name: google
seo: high
- name: bing
seo: medium
method: get
uri: /searchEngine
# Example returning void
- data: []
method: post
uri: /newSearchEngine
# Example returning a string
- data: Example string
method: get
uri: /exampleEndpoint
As you can see, you can either return JSON objects, arrays or primitive types.
These mock responses override the base responses provided by the defined endpoints. If an endpoint is not defined within the file, the base response or the Javascript function response will be used in it's place meaning you can combine all three ways of mocking on your API (default, file or Javascript function).
The following example shows how to use path parameters in the mock file configuration.
endpoints:
- data:
- code: 1
name: Luxury hotel
description: Luxurious hotel
location: Madrid, Spain
rating: 4
reviews: 894
- code: 2
name: Average hotel
description: Average hotel
location: Madrid, Spain
rating: 2
reviews: 1432
- code: 3
name: Modest hotel
description: Average hotel
location: Madrid, Spain
rating: 1
reviews: 2712
method: get
uri: /hotels
- data:
- code: 1
description: A great 4-bed room with a huge balcony and a private jacuzzi
cancellation: PROMOTION! No cancellation fee.
beds: 4
bathrooms: 2
visitors: 4
price: 88
hotelId: 1
- code: 2
description: A great 2-bed room with a private jacuzzi
cancellation: PROMOTION! No cancellation fee.
beds: 2
bathrooms: 1
visitors: 2
price: 78
hotelId: 1
method: get
uri: /hotels/{hotelId}/rooms
path:
- param: hotelId
value: 1
- data:
- code: 3
description: A 4-bed room featuring amazing sights of the city center
cancellation: PROMOTION! No cancellation fee.
beds: 4
bathrooms: 1
visitors: 4
price: 58
hotelId: 2
- code: 4
description: A 2-bed room featuring amazing sights of the city center
cancellation: PROMOTION! No cancellation fee.
beds: 2
bathrooms: 1
visitors: 2
price: 48
hotelId: 2
method: get
uri: /hotels/{hotelId}/rooms
path:
- param: hotelId
value: 2
- data:
- code: 5
description: A modest 2-bed room
cancellation: PROMOTION! No cancellation fee.
beds: 2
bathrooms: 1
visitors: 2
price: 28
hotelId: 3
method: get
uri: /hotels/{hotelId}/rooms
path:
- param: hotelId
value: 3
- data:
- code: 5
description: A modest 2-bed room
cancellation: PROMOTION! No cancellation fee.
beds: 2
bathrooms: 1
visitors: 2
price: 28
hotelId: 3
method: get
uri: /hotels/{hotelId}/rooms/{roomId}
path:
- param: hotelId
value: 3
- param: roomId
value: 5
Socket definition
As it's been stated on the introduction, given that Swagger spec files do not provide a socket definition format, a custom DSL has been defined within the Swagger spec.
The following parameters are available:
- x-th2mocker-socket: Labels the path it's attached to as a socket for the mocker's parser.
- x-th2mocker-socket-response-event: Defines the event to publish to the clients.
- x-th2mocker-socket-response-format: Defines the object format to be sent to socket clients. The format has to be a valid Swagger definition.
- x-th2mocker-socket-publish-interval: Defines the interval of time the socket will wait between publications.
- x-th2mocker-socket-transport: Defines the transport to be used. It currently supports either polling or websocket. Defaults to websocket.
- x-th2mocker-socket-ping: Defines the ping interval used on the polling transport. Defaults to 5 seconds.
The socket configuration is embedded within a Swagger spec path. In order for the spec file to still be a valid Swagger spec file, you still have to add a get method and it's response.
An example configuration would be like this:
/socketFx:
x-th2mocker-socket: true
get:
x-th2mocker-socket-response-event: 'fxData'
x-th2mocker-socket-response-format: '#/definitions/FxFormatDTO'
x-th2mocker-socket-transport: 'polling'
x-th2mocker-socket-ping: 3000
x-th2mocker-socket-publish-interval: 1000
operationId: socketFx
summary: Socket endpoint that provides realtime *FX* data.
description: Socket endpoint which publishes *FX* data every second.
tags:
- Socket
responses:
200:
description: "Socket dummy response"
Future features
- [ ] RAML spec files support.
- [ ] JSON Swagger spec files as input support via an option on the CLI.
- [ ] Allow users to define responses via the example tag.
- [ ] Parameter validation on custom response functions.
- [ ] Mock configuration using query parameters.
- [ ] Data store support.
- [ ] Cloud function deployment.
License
Thin2 mocker is 100% free and open-source, under the MIT license. Use it however you want.