Updated example, shortened readme and links to wiki. Removed dependency.

This commit is contained in:
Dan Hough
2014-08-09 15:39:59 +01:00
parent 635209e11a
commit 5014d9c2e4
4 changed files with 16 additions and 170 deletions

View File

@@ -23,7 +23,7 @@ var deleteRequest = postRequest.creates.delete('/items/1').status(204);
// But when the put request is hit we need to edit both
putRequest.extends.get('/items').body({ items: {
0 : { id: 1, name: 'Item One' }
0 : { name: 'Item One' }
}});
// And also create an endpoint for our new item

View File

@@ -3,9 +3,6 @@
var program = require('commander');
var Interfake = require('./lib/server');
var packageInfo = require('./package.json');
var fs = require('fs');
var PEG = require('pegjs');
var grammar, parser, endpoints;
program
.version(packageInfo.version)
.option('-f, --file [file]', 'Load an API from a JSON file [file]')
@@ -29,23 +26,4 @@ if (program.file) {
interfake.loadFile(program.file);
}
function addFluentEndpoint(endpoint) {
var e = interfake[endpoint.method](endpoint.path).status(endpoint.status);
if (endpoint.creates) {
endpoint.creates.forEach(function (c) {
e.creates[c.method](c.path).status(c.status);
});
}
}
if (['get', 'put', 'post', 'del'].indexOf(program.args[0]) !== -1) {
// Fluent command line mode
// console.log('Fluent command line mode!');
// This should be refined using http://pegjs.majda.cz/online
grammar = fs.readFileSync('./lib/grammar.pegjs') + '';
parser = PEG.buildParser(grammar);
endpoints = parser.parse(program.args.join(' '));
endpoints.forEach(addFluentEndpoint);
}
interfake.listen(program.port);

View File

@@ -52,7 +52,6 @@
"merge": "^1.1.2",
"connect-json": "0.0.0",
"body-parser": "~1.0.2",
"pegjs": "^0.8.0",
"deepmerge": "git://github.com/basicallydan/deepmerge.git#126cc82a695cc804120cbfd1545003582e1728ed"
},
"license": "MIT",

161
readme.md
View File

@@ -4,7 +4,7 @@ Interfake is a tool which allows developers of client-side applications of *any*
## Get started
If you don't want to use the JavaScript method to create your Interfake API, go read up on [all the methods](#three-ways-to-use-interfake). Otherwise, read on.
If you don't want to use the JavaScript method to create your Interfake API, go read up on [all the methods](https://github.com/basicallydan/interfake/wiki). Otherwise, read on.
Install Interfake in your project.
@@ -156,49 +156,11 @@ There's more options, though, including delays, custom response headers, and han
---
## Three ways to use Interfake
## API
Interfake can handle complex API structures, mutable endpoints and has three interfaces: the [JavaScript API](#method-1-javascript) (useful for NodeJS-based tests), the [command line](#method-2-command-line) (useful for non-NodeJS tests), or on-the-fly using Interfake's [HTTP meta-API](#method-2-command-line) (also useful for non-NodeJS tests). Based on [express](https://github.com/visionmedia/express).
The majority of Interfake users will probably be interested in the JavaScript API, which is covered below. However, there are in fact [three ways to use Interfake: JavaScript, on the Command Line (using static JSON files), or using an HTTP meta-API](https://github.com/basicallydan/interfake/wiki). These are covered in detail in [the Wiki](https://github.com/basicallydan/interfake/wiki).
## Method 1: JavaScript
Make sure you've installed Interfake as a local module using `npm install interfake --save`. If you `var Interfake = require('interfake')` in your JavaScript file, you can use the following API to spin up the Interfake server.
### Example ([more examples](/examples-javascript))
```javascript
var Interfake = require('interfake');
var interfake = new Interfake();
// Create endpoints using the fluent interface
interfake.post('/items').status(201).body({ created: true }).creates.get('/next-items').status(200).body([ { id: 1, name: 'the thing' } ]);
// Or using the more verbose JSON syntax (more on this below under 'command line')
interfake.createRoute({
request: {
url: '/whats-next',
method: 'get',
query: { // Optional querystring parameters
page: 2
}
},
response: {
code: 200, // HTTP Status Code
delay: 50, // Delay in milliseconds
body: { // JSON Body Response
next:'more stuff'
},
headers: { // Optional headers
'X-Powered-By': 'Interfake'
}
}
});
interfake.listen(3000); // The server will listen on port 3000
```
### API
### JavaScript
* `new Interfake(options)`: creates an Interfake object. Options are:
* `debug`: If `true`, outputs lots of annoying but helpful log messages. Default is `false`.
@@ -223,106 +185,6 @@ interfake.listen(3000); // The server will listen on port 3000
* `#creates#get|post|put|delete(url)`: Specify an endpoint to create *after* the first execution of this one. API is the same as above.
* `#extends#get|post|put|delete(url)`: Specify an endpoint to modify *after* the first execution of this one. API is the same as above. The endpoints you extend are matched based on `url` and `query`. The `status`, `body`, `delay` and `responseHeaders` are the extendable bits. Keep in mind that keys will be replaced, and arrays will be added to.
## Method 2: Command line
Interfake must be install globally for the command line interface to work:
```
npm install interfake -g
```
A JSON array of request/response pairs ("endpoints") you can write APIs and run them multiple times using the global `interfake` executable, and the JSON syntax.
### Example ([more examples](/examples-command-line))
Create a file called `adventuretime.json`:
```JSON
[
{
"request": {
"url": "/whattimeisit",
"method": "get"
},
"response": {
"code": 200,
"delay": 100,
"body": {
"theTime": "Adventure Time!",
"starring": [
"Finn",
"Jake"
],
"location": "ooo"
}
}
}
]
```
Then run Interfake against it:
```
interfake --file ./adventuretime.json
```
Now go to http://localhost:3000/whattimeisit in your web browser.
The above example will create a endpoint at `http://localhost:3000/whattimeisit` which returns a `200` and the body specified in the `response` object.
The top-level array should contain a list of endpoints (represented by request/response objects). The `request` object contains a URL and HTTP Method (GET/POST/PUT/DELETE/etc) to match against, and the `response` object contains an [HTTP Status Code](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes) (`code`) and `body` object, which is in itself a JSON object, and optional. This `body` is what will be returned in the body of the response for the request you're creating.
You can create as many HTTP request/response pairs as you like. I've put some simple examples below for your copy & paste pleasure, or you can look in `/examples-command-line` for some more complex examples.
Run `interfake --help` for a full list of command-line options.
### Conditional endpoints
When the API needs to mutate responses, such as after a POST, PUT or DELETE request, there is an `afterResponse` property available for any existing endpoint, which specifies endpoints to create after the parent has been hit for the first time.
```JSON
[
{
"request": {
"url": "/items",
"method": "post"
},
"response": {
"code": 201,
"body": {}
},
"afterResponse": {
"endpoints": [
{
"request": {
"url": "/items",
"method": "get"
},
"response": {
"code": 200,
"body": { "items" : [] }
}
}
]
}
}
]
```
The `afterResponse` property can be used as deep as you like in the endpoint hierarchy. For a complex example of the use of post-response endpoints, see the `/examples-command-line/crud.json` file in this repository.
## Method 3: HTTP
While the server is running, you can create new endpoints on-the-fly. You can make a POST request to `/_requests` with the same JSON structure that the command line interface accepts.
### Example
While Interfake is running, make this request using `curl`.
```
$ curl -X POST -d '{ "request":{"url":"/whattimeisit", "method":"get"}, "response":{"code":200,"body":{ "theTime" : "Adventure Time!" } } }' http://localhost:3000/_requests --header "Content-Type:application/json"
```
## JSONP
Interfake supports [JSONP](http://en.wikipedia.org/wiki/JSONP). Just put `?callback` on the end of the URLs being called.
@@ -333,6 +195,10 @@ $ curl http://localhost:3000/whattimeisit?callback=handleSomeJson
## Use Cases
### Backend/API Prototype for a Single-Page Application (SPA)
By using Interfake's `.serveStatic()` method, you can serve some front-end HTML, JavaScript and CSS which uses the API you've created as the backend. Not only does this massively speed up development time by not having to have a real API, it serves as a great prototype for the real API, and avoids having to mock requests. This is my most common use for Interfake.
### Backend for a Mobile Application
If you'd like to develop an API-driven mobile application you might not yet have a finished API available. This is a perfect example of where Interfake is useful. You can quickly mock up some dummy APIs and work on the mobile application. In parallel, perhaps another developer will be creating the real API, or you could create it later.
@@ -356,7 +222,7 @@ I tested this on my Mac. If you have trouble on Windows or any other platform, [
## Version History
* 1.9.0: Created the `.extends` methods to extend existing endpoints
* 1.8.2: Bug fix for Windows
* 1.8.2: Bug fix for Windows - paths were screwed up
* 1.8.1: Bug fix for responseheaders
* 1.8.0: Querystring parameter values can now be regular expressions
* 1.7.2: Fixed a bug where `.delay()` was not allowing chaining
@@ -376,9 +242,7 @@ I tested this on my Mac. If you have trouble on Windows or any other platform, [
## Contribute
Interfake is a labour of love, created for front-end and mobile developers to increase their prototyping and development speeds. If you can contribute by getting through some issues, I would be very grateful.
If you make any pull requests, please do try to write tests, or at the very least ensure they're still passing by running `npm test` before you do so.
Interfake is a labour of love, created for front-end and mobile developers to increase their prototyping and development speeds. If you can contribute by getting through some issues, I would be very grateful. Please read more about how to contribute in the [CONTRIBUTING.md](https://github.com/basicallydan/interfake/blob/master/CONTRIBUTING.md) document.
<3 Open Source!
@@ -387,7 +251,12 @@ If you make any pull requests, please do try to write tests, or at the very leas
## Dependencies
* [express](https://github.com/visionmedia/express)
* [express body-parser](https://github.com/expressjs/body-parser)
* [connect-json](https://github.com/dtinth/connect-json)
* [commander](https://github.com/visionmedia/commander.js/)
* [core-util-is](https://github.com/isaacs/core-util-is)
* [merge](https://github.com/yeikos/js.merge)
* [basicallydan/deepmerge](https://github.com/basicallydan/deepmerge) forked from [nrf110/deepmerge](https://github.com/nrf110/deepmerge)
## Works well with