Skip to content

Commit

Permalink
fix: Proxy route.params onto the request instead of mutating req
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonmit committed Jun 13, 2018
1 parent c7c24ed commit 5bcd4f9
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 12 deletions.
3 changes: 0 additions & 3 deletions packages/@pollyjs/core/src/-private/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,6 @@ export default class PollyRequest {
*/
this.action = null;

// This will be overridden by the route when a method is invoked
this.params = {};

// Lookup the associated route for this request
this[ROUTE] = polly.server.lookup(this.method, this.url);
}
Expand Down
19 changes: 10 additions & 9 deletions packages/@pollyjs/core/src/server/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@ import Handler from './handler';

async function invoke(fn, route, req, ...args) {
if (typeof fn === 'function') {
const params = req.params;
const proxyReq = new Proxy(req, {
get(source, prop) {
if (prop === 'params') {
// Set the request's params to given route's matched params
return route.params;
}

// Set the request's params to given route's matched params
req.params = route.params || {};
return source[prop];
}
});

const result = await fn(req, ...args);

// Reset the params object to what it was before
req.params = params;

return result;
return await fn(proxyReq, ...args);
}
}

Expand Down
19 changes: 19 additions & 0 deletions packages/@pollyjs/core/tests/integration/persisters-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,25 @@ describe('Integration | Persisters', function() {
expect(savedRecording.entries[entryKeys[0]].length).to.equal(2);
expect(savedRecording.entries[entryKeys[1]].length).to.equal(1);
});

it('should emit beforePersist', async function() {
const { persister, server } = this.polly;
let beforePersistCalled = false;

server.get('/api/db/:id').on('beforePersist', (req /*, res*/) => {
expect(req.params.id).to.equal('foo');
expect(beforePersistCalled).to.be.false;
beforePersistCalled = true;
});

this.polly.record();

await this.fetch('/api/db/foo');
expect(beforePersistCalled).to.be.false;

await persister.persist();
expect(beforePersistCalled).to.be.true;
});
});

describe(`${name} | recordFailedRequests set to false`, function() {
Expand Down

0 comments on commit 5bcd4f9

Please sign in to comment.