Skip to content

Commit

Permalink
feat: Helper functions for custom responses
Browse files Browse the repository at this point in the history
Helper functions for custom responses
  • Loading branch information
muratcorlu authored Apr 16, 2019
2 parents 20291c2 + 154224e commit ba5831f
Show file tree
Hide file tree
Showing 19 changed files with 138 additions and 85 deletions.
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Editor configuration, see http://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false
56 changes: 42 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,23 +226,23 @@ module.exports = function (request, response) {
`POST.js` file for non ExpressJS server:

```js
var fs = require('fs');
var path = require('path');
const fs = require('fs');
const path = require('path');

module.exports = function (request, response) {
module.exports = (request, response) => {
if (!request.get('X-Auth-Key')) {
response.statusCode = 403;
response.end();
} else {
var filePath = path.join(__dirname, 'POST.json');
var stat = fs.statSync(filePath);
const filePath = path.join(__dirname, 'POST.json');
const stat = fs.statSync(filePath);

response.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': stat.size
});

var readStream = fs.createReadStream(filePath);
const readStream = fs.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
}
Expand All @@ -260,7 +260,7 @@ const fs = require('fs');
const path = require('path');

module.exports = function (request, response) {
var targetFileName = 'GET.json';
let targetFileName = 'GET.json';

// Check is a type parameter exist
if (request.query.type) {
Expand All @@ -281,13 +281,13 @@ module.exports = function (request, response) {
```
`GET.js` file for non ExpressJS server:
```js
var url = require('url');
var fs = require('fs');
var path = require('path');
const url = require('url');
const fs = require('fs');
const path = require('path');

module.exports = function (request, response) {
var targetFileName = 'GET.json';
var typeQueryParam = url.parse(request.url, true).query.type;
let targetFileName = 'GET.json';
const typeQueryParam = url.parse(request.url, true).query.type;
// Check is a type parameter exist
if (typeQueryParam) {
// Generate a new targetfilename with that type parameter
Expand All @@ -306,18 +306,46 @@ module.exports = function (request, response) {
return;
}

var stat = fs.statSync(filePath);
const stat = fs.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': stat.size
});

var readStream = fs.createReadStream(filePath);
const readStream = fs.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
}
```

## Helper functions for custom responses

Connect-Api-Mocker also presents a bunch of helper functions to speed up writing simple custom responses. There are:

- `status(statusCode)`: Set status code of response
- `notFound(message?)`: Set status code as 404 and optionally sends message
- `created()`: Sets status code as 201
- `success()`: Sets status code as 200
- `delay(duration)`: Delays the request by given duration(in ms).
- `json(data)`: Send given JSON object as response.
- `end(body)`: Ends request and optionally sends the string output

You can use these functions in custom responses, like:

```js
const { notFound } = require('connect-api-mocker/helpers');

module.exports = notFound('Page is not found');
```

Also you can combine multiple functions:

```js
const { delay, created, json } = require('connect-api-mocker/helpers');

module.exports = [delay(500), created(), json({success: true})];
```

## Wildcards in requests

You can use wildcards for paths to handle multiple urls(like for IDs). If you create a folder structure like `api/users/__user_id__/GET.js`, all requests like `/api/users/321` or `/api/users/1` will be responded by custom middleware that defined in your `GET.js`. Also id part of the path will be passed as a request parameter named as `user_id` to your middleware. So you can write a middleware like that:
Expand Down
12 changes: 0 additions & 12 deletions examples/redefine-default-mounting/example.js

This file was deleted.

14 changes: 0 additions & 14 deletions examples/redefine-default-mounting/states/base/profile/GET.js

This file was deleted.

This file was deleted.

3 changes: 3 additions & 0 deletions helpers/created.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const status = require('./status');

module.exports = () => status(201);
3 changes: 3 additions & 0 deletions helpers/delay.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = (duration) => (req, res, next) => {
setTimeout(next, duration);
};
3 changes: 3 additions & 0 deletions helpers/end.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = message => (req, res) => {
res.end(message);
};
9 changes: 9 additions & 0 deletions helpers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
delay: require('./delay'),
json: require('./json'),
status: require('./status'),
notFound: require('./not-found'),
created: require('./created'),
success: require('./success'),
end: require('./end')
};
4 changes: 4 additions & 0 deletions helpers/json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = data => (req, res) => {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify(data));
};
4 changes: 4 additions & 0 deletions helpers/not-found.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const status = require('./status');
const end = require('./end');

module.exports = message => [status(404), end(message)];
4 changes: 4 additions & 0 deletions helpers/status.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = status => (req, res, next) => {
res.statusCode = status;
next();
};
3 changes: 3 additions & 0 deletions helpers/success.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const status = require('./status');

module.exports = () => status(200);
12 changes: 10 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,12 +169,20 @@ module.exports = function (urlRoot, pathRoot) {
req, filePath, fileType: 'js', config
});
delete require.cache[require.resolve(path.resolve(filePath))];
const customMiddleware = require(path.resolve(filePath));
let customMiddleware = require(path.resolve(filePath));
if (requestParams) {
req.params = requestParams;
}
bodyParser.json()(req, res, () => {
customMiddleware(req, res, next);
if (typeof customMiddleware === 'function') {
customMiddleware = [customMiddleware];
}
// flatten middlewares
customMiddleware = [].concat(...customMiddleware);

customMiddleware.reduce((chain, middleware) => chain.then(
() => new Promise(resolve => middleware(req, res, resolve))
), Promise.resolve()).then(next);
});
} else {
let fileType = config.type || 'json';
Expand Down
37 changes: 0 additions & 37 deletions test/examples.spec.js

This file was deleted.

31 changes: 31 additions & 0 deletions test/mock-helpers.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const request = require('supertest');
const express = require('express');
const apiMocker = require('..');

const app = express();

app.use('/api', apiMocker('test/mocks/helpers'));

describe('Helpers', () => {
it('delay, created(status), json response', (done) => {
request(app)
.post('/api/users')
.expect('Content-Type', /json/)
.expect(201)
.expect({
success: true
}, done);
});

it('notFound', (done) => {
request(app)
.get('/api/users')
.expect(404, done);
});

it('success', (done) => {
request(app)
.patch('/api/users')
.expect(200, done);
});
});
3 changes: 3 additions & 0 deletions test/mocks/helpers/users/GET.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { notFound } = require('../../../../helpers');

module.exports = notFound();
3 changes: 3 additions & 0 deletions test/mocks/helpers/users/PATCH.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { success, end } = require('../../../../helpers');

module.exports = [success(), end()];
3 changes: 3 additions & 0 deletions test/mocks/helpers/users/POST.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { delay, created, json } = require('../../../../helpers');

module.exports = [delay(100), created(), json({ success: true })];

0 comments on commit ba5831f

Please sign in to comment.