diff --git a/src/plugins.js b/src/plugins.js index 06b36fb..6b83fec 100644 --- a/src/plugins.js +++ b/src/plugins.js @@ -12,21 +12,29 @@ function getPlugins() { async function executePreRequest(event) { let response = null; //@TODO: only loop through plugins with preRequest. - //@TODO: allow multiple reponses, currently last one wins. for (let i = 0; i < plugins.length; i++) { let plugin = plugins[i]; if (plugin.preRequest) { - response = await plugin.preRequest(event); + response = await plugin.preRequest(event, response); } } return response; } -async function executePostRequest() { +async function executePostRequest(event, response) { + //@TODO: only loop through plugins with postRequest. + for (let i = 0; i < plugins.length; i++) { + let plugin = plugins[i]; + if (plugin.postRequest) { + response = await plugin.postRequest(event, response); + } + } + return response; } module.exports.register = register; module.exports.getPlugins = getPlugins; -module.exports.executePreRequest = executePreRequest; \ No newline at end of file +module.exports.executePreRequest = executePreRequest; +module.exports.executePostRequest = executePostRequest; \ No newline at end of file diff --git a/tests/plugins.test.js b/tests/plugins.test.js index 2bb72b6..ae2a71d 100644 --- a/tests/plugins.test.js +++ b/tests/plugins.test.js @@ -20,8 +20,8 @@ test('Execute preRequest', async () => { const body = 'foo'; plugins.register({ - name: 'Hello World', - preRequest: async function(event) { + name: 'preRequest', + preRequest: async function(event, response) { return { statusCode: 200, body: event.test, @@ -32,4 +32,48 @@ test('Execute preRequest', async () => { const response = await plugins.executePreRequest({test: body}); expect(response.body).toEqual(body); expect(response.statusCode).toEqual(statusCode); +}); + +test('Execute multiple preRequest', async () => { + const body = 'foo'; + + plugins.register({ + name: '1', + preRequest: async function(event, response) { + return { + statusCode: 200, + body: event.test, + } + }, + }); + + plugins.register({ + name: '2', + preRequest: async function(event, response) { + if (response?.statusCode) { + response.statusCode = response.statusCode + 1; + } + return response; + }, + }); + + const response = await plugins.executePreRequest({test: body}); + expect(response.body).toEqual(body); + expect(response.statusCode).toEqual(201); +}); + +test('Execute postRequest', async () => { + plugins.register({ + name: 'postRequest', + postRequest: async function(event, response) { + return { + statusCode: response.statusCode + 1, + body: 'Foo' + } + } + }); + + const response = await plugins.executePostRequest({test: 'foo'}, {statusCode: 200, body: 'Test'}); + expect(response.body).toEqual('Foo'); + expect(response.statusCode).toEqual(201); }); \ No newline at end of file