How to Write Custom Middlewares


#1

There are examples of how to create hooks for Jovo-supplied middlewares.

I am wondering if it is possile to create your own middlewares (either stand-alone or as part of a plugin) that an app developer (or developers using your plugin) could then take advantage of?

What are some examples of what you can do with custom middlewares?

@AlexSwe


#2

What are the differences/benefits to using middleware vs hooks?

app.middleware('after.platform.init').use((handleRequest) => { 
  // handleRequest.jovo 
  console.log('middleware');
});

VS.

app.hook('after.platform.init', (error, host, jovo) => {
  // jovo 
  console.log('hook');
});


#3

Technically, both methods are the same. hook was added afterwards because it’s a bit cleaner.

You can do everything with middlewares. Basically every plugin uses middlewares :slight_smile:

Here’s an example: It replaces the text spoken by Alexa with a Polly voice:

app.hook('before.platform.output', async (error, host, jovo) => {
    const pollyName = 'Hans';
    if (jovo.isAlexaSkill()) {
        if (jovo.$output.tell) {
            jovo.$output.tell.speech = `<voice name="${pollyName}">${jovo.$output.tell.speech}</voice>`;
        }

        if (jovo.$output.ask) {
            jovo.$output.ask.speech = `<voice name="${pollyName}">${jovo.$output.ask.speech}</voice>`;
            jovo.$output.ask.reprompt = `<voice name="${pollyName}">${jovo.$output.ask.reprompt}</voice>`;
        }
    }
});

Log the size of the response json payload.

app.hook("after.platform.output", (error: Error, host: Host, jovo: Jovo) => {
  console.log(`Size of response: ${JSON.stringify(jovo.$response!).length}`); // Limit: ~ 24500 
characters
// send notification
});

Setup middleware. It’s called on the first request .

app.middleware("setup")!.use((handleRequest: HandleRequest) => {
 // do API calls for data that is used globally
});