Skip to content

Commit 3b07b0f

Browse files
committed
feat: json helper now also accepts callback
Please check Readme doc for further information.
1 parent 9b77acc commit 3b07b0f

File tree

4 files changed

+35
-3
lines changed

4 files changed

+35
-3
lines changed

README.md

+12-2
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ Connect-Api-Mocker also presents a bunch of helper functions to speed up writing
367367
- `created()`: Sets status code as 201
368368
- `success()`: Sets status code as 200
369369
- `delay(duration)`: Delays the request by given duration(in ms).
370-
- `json(data)`: Send given JSON object as response.
370+
- `json(data|callback(req,res))`: Send given JSON object as response.
371371
- `file(filePath)`: Responds with the content of file in given path(full path)
372372
- `type(contentType)`: Sets content-type header.
373373
- `end(body)`: Ends request and optionally sends the string output
@@ -388,6 +388,16 @@ const { delay, created, json } = require('connect-api-mocker/helpers');
388388
module.exports = [delay(500), created(), json({success: true})];
389389
```
390390

391+
`json` middleware also accepts a callback that has request and response objects as parameters:
392+
393+
``js
394+
const { json } = require('connect-api-mocker/helpers');
395+
396+
module.exports = [json(req => ({
397+
id: req.params.userId, success: true
398+
}))];
399+
```
400+
391401
Another example to return image as response:
392402
393403
```js
@@ -527,4 +537,4 @@ apiMocker('/api', {
527537
[webpack-dev-server]: https://github.com/webpack/webpack-dev-server
528538
[cra]: https://github.com/facebook/create-react-app
529539
[customize-cra]: https://github.com/arackaf/customize-cra
530-
[react-app-rewired]: https://github.com/timarney/react-app-rewired
540+
[react-app-rewired]: https://github.com/timarney/react-app-rewired

helpers/json.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
module.exports = data => (req, res) => {
2+
let responseData = data;
3+
if (typeof data === 'function') {
4+
responseData = data(req, res);
5+
}
26
res.setHeader('content-type', 'application/json');
3-
res.end(JSON.stringify(data));
7+
res.end(JSON.stringify(responseData));
48
};

test/mock-helpers.spec.js

+10
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,16 @@ describe('Helpers', () => {
1717
}, done);
1818
});
1919

20+
it('json helper with callback', (done) => {
21+
request(app)
22+
.put('/api/users/1')
23+
.expect('Content-Type', /json/)
24+
.expect({
25+
success: true,
26+
id: '1'
27+
}, done);
28+
});
29+
2030
it('notFound', (done) => {
2131
request(app)
2232
.get('/api/users')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const { json } = require('../../../../../helpers');
2+
3+
module.exports = [
4+
json(req => ({
5+
success: true,
6+
id: req.params.userId
7+
}))
8+
];

0 commit comments

Comments
 (0)