Skip to content
This repository has been archived by the owner on Oct 23, 2023. It is now read-only.

add middleware layer support #172

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/dialogflow-fulfillment.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,14 @@ class WebhookClient {
*/
this.alternativeQueryResults = null;

/**
* List of middlewares defined by the developer
*
* @private
* @type {Object[]}
*/
this.middlewares_ = [];

/**
* Platform contants, to define platforms, includes supported platforms and unspecified
* @example
Expand Down Expand Up @@ -309,6 +317,10 @@ class WebhookClient {
));
}

for (const middleware of this.middlewares_) {
middleware(this);
}

if (handler.get(this.intent)) {
let result = handler.get(this.intent)(this);
// If handler is a promise use it, otherwise create use default (empty) promise
Expand All @@ -328,6 +340,32 @@ class WebhookClient {
}
}

/**
* Add a middleware function
*
* * @example
* const { WebhookClient } = require('dialogflow-webhook');
* const agent = new WebhookClient({request: request, response: response});
* class Helper {
* constructor(agent) {
* this.agent = agent;
* }
*
* func1() {
* this.agent.add(`What's up?`);
* }
* }
* agent.middleware(a => {
* a.helper = new Helper(a);
* });
*
* @param {requestCallback} handler
*/
middleware(handler) {
if (typeof handler === 'function') {
this.middlewares_.push(handler);
}
}
// --------------------------------------------------------------------------
// Deprecated Context methods
// --------------------------------------------------------------------------
Expand Down
16 changes: 16 additions & 0 deletions test/webhook-integration-v2-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,16 @@ test('v2 Integration test', async (t) => {
function webhookTest(request, callback) {
let response = new ResponseMock(callback);
const agent = new WebhookClient({request: request, response: response});

agent.middleware((agent) => {
if (agent.intent === 'Custom Intent') {
agent.setContext({
name: 'other',
lifespan: 2,
parameters: {city: 'Toronto'},
});
}
});
/**
* Handler function to welcome
* @param {Object} agent
Expand Down Expand Up @@ -255,6 +265,12 @@ const mockSimulatorV2ResponseOther = {
lifespanCount: 2,
parameters: {city: 'Rome'},
},
{
name:
'projects/agent52-3e1ea/agent/sessions/669d7da3-de6f-4b1d-8394-d79c6973e516/contexts/other',
lifespanCount: 2,
parameters: {city: 'Toronto'},
},
],
};
// Mock webhook request and reponse from Dialogflow for sample v2
Expand Down