diff --git a/example/mock/mocks/trees.json b/example/mock/mocks/trees.json new file mode 100644 index 0000000..5d27582 --- /dev/null +++ b/example/mock/mocks/trees.json @@ -0,0 +1,7 @@ +[ + { "id": 1, "name": "Conifer", "maxHeight": 115 }, + { "id": 2, "name": "Eucalyptus", "maxHeight": 210 }, + { "id": 3, "name": "Ash", "maxHeight": 40 }, + { "id": 4, "name": "Elder", "maxHeight": 5 }, + { "id": 5, "name": "Holly", "maxHeight": 10 } +] diff --git a/example/mock/mocks/trees.mock.js b/example/mock/mocks/trees.mock.js index 588259f..70a1f98 100644 --- a/example/mock/mocks/trees.mock.js +++ b/example/mock/mocks/trees.mock.js @@ -1,28 +1,21 @@ -const data = [ - { id: 1, name: 'Conifer', maxHeight: 115 }, - { id: 2, name: 'Eucalyptus', maxHeight: 210 }, - { id: 3, name: 'Ash', maxHeight: 40 }, - { id: 4, name: 'Elder', maxHeight: 5 }, - { id: 5, name: 'Holly', maxHeight: 10 } -] +const data = require('./trees') module.exports = [ /* CREATE */ { request: { method: 'POST' }, - response: { - status: 201, - location: '/tree/1' + response: function (ctx) { + data.push(ctx.request.body) + this.status = 201 + this.location = '/tree/1' } }, /* READ */ { request: { method: 'GET' }, - response: { - status: 200, - body: function (ctx) { - return data.filter(tree => tree.maxHeight > Number(ctx.query.tallerThan)) - } + response: function (ctx) { + this.status = 200 + this.body = data.filter(tree => tree.maxHeight > Number(ctx.query.tallerThan || 0)) } }, /* UPDATE (forbidden on collection)*/ @@ -36,3 +29,6 @@ module.exports = [ response: { status: 404 } } ] + +// curl -i http://localhost:8000/trees -H 'content-type: application/json' -d '{"id":6, "name":"Oak", "maxHeight": 100 }' +// curl -i http://localhost:8000/trees diff --git a/lib/middleware.js b/lib/middleware.js index 8a4de5a..68336d5 100644 --- a/lib/middleware.js +++ b/lib/middleware.js @@ -86,20 +86,12 @@ function mockResponses (options) { mock = mocks.find(mock => !mock.request) } - const mockedReponse = {} - /* resolve any functions on the mock */ - Object.keys(mock.response).forEach(key => { - if (t.isFunction(mock.response[key])) { - mockedReponse[key] = mock.response[key](ctx) - } else { - mockedReponse[key] = mock.response[key] - } - }) - if (mock) { - Object.assign(ctx.response, mockedReponse) - // debug('mocked response', JSON.stringify(mockedReponse)) - // debug('actual response', JSON.stringify(ctx.response)) + let mockedResponse = mock.response + if (t.isFunction(mock.response)) { + mockedResponse = new mock.response(ctx) + } + Object.assign(ctx.response, mockedResponse) } } else { return next()