Defining a message handler in a module
Description
I've followed the Express All Interactions Example and it defines all interactive message handlers inside server.js, which is fine for a small project, but I'm trying to understand how best to define message handlers for use in a large project composed of many different modules.
For example, say I have a project module, and I want this to contain the logic for an updateProject action. I've been able to do this using the following structure:
// server.js
const project = require('./path/to/project')
const slackInteractions = createMessageAdapter(process.env.SLACK_VERIFICATION_TOKEN);
app.use('/slack/actions', slackInteractions.expressMiddleware());
project.initInteractionHandlers(slackInteractions)
// project.js
module.exports.initInteractionHandlers = function(slackInteractions) {
slackInteractions.action('updateProject', (payload, respond) => {
console.log(`The user ${payload.user.name} in team ${payload.team.domain} submitted a dialog`);
}
}
The above example works, but I'm not sure if this is the correct way to handle this. Can someone please let me know if I'm on the right track, or if there's a better way to handle it?
Ideally, it would be great to have another example added to the Express All Interactions Example to show exactly how to define a handler outside of server.js. Thanks!
What type of issue is this?
- [x] question
Requirements
- [x] I've read and understood the Contributing guidelines and have done my best effort to follow them.
- [x] I've read and agree to the Code of Conduct.
- [x] I've searched for any related issues and avoided creating a duplicate issue.
@adamcohen you raised an interesting point: we haven't provided any guidance on how to modularize an application using this adapter. in express parlance, the question is "what's the equivalent of an express.Router for the adapter?"
if this worked like express, you'd instantiate a mini-adapter inside one module, and then export it. then some other module would aggregate all the mini-adapters and mount them into the larger adapter. but at this point i'm not certain it should be the job of this package to provide a mini-adapter.
i see this package as a low-level component that should remain as flexible as possible, so that any application developer or framework can use it and adapt it to whichever pattern they prefer.
but as you are pointing out, its unhelpful to leave app developers off to figure out a reasonable pattern all on their own. so in short, i agree with you that a new example app may be the best vehicle to demonstrate this usage and provide reasonable guidelines.
getting to the actual implementation. i think its reasonable for your project.js to import @slack/interactive-messages, and call createMessageAdapter() directly. then it would export the return value of slackInteractions.expressMiddleware(), which server.jswould import. this would allowserver.jsto remain decoupled from the idea of how slack messages are handled and what the adapter does, it only deals in HTTP middleware. thenserver.js's job becomes to mount that middleware on the desired path and run the server. one day, if your project gains another module like project.js`, that module can also create its own message adapter, completely independent of the first, and export its middleware.
does this sound like a reasonable approach for the application you are building? once we come up with something that works for you, i'm happy to turn that into a spec for a sample, and work on landing that (maybe even from you)!
thanks for kicking off this discussion.
@aoberoi thanks for the response, your approach sounds reasonable, I've tested it out in the Express All Interactions Example and it seemed to work well.
This is what I did:
-
Created a
slack-interactionsmodule for creating the message adapter:slack-interactions.js
const { createMessageAdapter } = require('@slack/interactive-messages'); module.exports = createMessageAdapter(process.env.SLACK_VERIFICATION_TOKEN); -
Created
projectandusermodules which exportedslackInteractions, and then I provided their middleware as an array toserver.js:project.js
const slackInteractions = require('./slack-interactions') slackInteractions.action('project_submit', (payload, respond) => { ... } module.exports = { middleware: slackInteractions.expressMiddleware() }user.js
const slackInteractions = require('./slack-interactions') slackInteractions.action('user_submit', (payload, respond) => { ... } module.exports = { middleware: slackInteractions.expressMiddleware() } -
Provided the
projectandusermiddleware as an array toexpressinserver.js:server.js
const project = require('./project'); const user = require('./user'); app.use('/slack/actions', [project.middleware, user.middleware]);
Is this the pattern that you had in mind?
I've been playing around a bit more and have run into a bit of blocker. I'm trying to use a project module and define the interactive message hander in a class:
slack-interactions.js
const { createMessageAdapter } = require('@slack/interactive-messages');
module.exports = createMessageAdapter(process.env.SLACK_VERIFICATION_TOKEN);
server.js
const project = require('./project');
app.use('/slack/actions', project.interactionDispatcherMiddleware);
project.js
const slackInteractions = require('./slack-interactions')
class Project {
constructor() {
slackInteractions.action('project.select', this.projectSelect)
this.interactionDispatcherMiddleware = slackInteractions.expressMiddleware()
}
async projectSelect(payload, respond) {
try {
const selectedID = payload.actions[0].selected_options[0].value
const project = await Project.findByID(selectedID)
const someResult = await this.doSomething()
respond({ text: `Project name ${project.name} was selected. Result: ${someResult}` });
} catch (err) {
respond({ text: `An error occurred: ${err}` });
}
}
async doSomething() {
// implement me
}
}
The above fails with the following error:
project.select TypeError: this.doSomething is not a function
This is because the middleware function doesn't have access to instance methods in the class. I can't seem to figure out how to get around this, since it seems like I would need to pass an instance of the class when calling slackInteractions.expressMiddleware(). If you have any ideas how to solve this, I'd appreciate it.
@aoberoi any thoughts about how to get node-slack-interactive-messages to allow access to class level functions from within the middleware callback? I've found the following stackoverflow question which seems similar to what I'm trying to do, and one of the answers is to use:
app.use(Middle.middleware(middle));
Which looks like it would require a change on your end to allow me to call slackInteractions.expressMiddleware() and provide an argument. Is that correct, or is it possible to solve this without any changes in the node-slack-interactive-messages package?
what are the exports of project.js? if you export the class itself (export class Project { /* ... */ }, then in server.js, you could create an instance of the class and the methods would be available.
that is one approach, and i think it lends itself well to the idea of dependency injection. imagine, for example, that server.js had some state that is required to "configure" Project to behave correctly (an instance of a database connection or an API key). you could pass those into the Project constructor from server.js and Project can remain unconcerned with how to create a database or where to read the API key from. this really comes in handy when you need to implement unit tests. while unit testing Project, you probably don't want to give it a real database (it wouldn't be much of a unit test if its integrating the database code), but rather a mock of a database connection. this is much easier to accomplish when the constructor takes that configuration up front.
that being said, maybe your application isn't that complex, maybe its actually as simple as the examples you've shown above. in that case, i would steer away from using classes all together. there's no use in placing these functions inside a class if you never intend on instantiating it (this implies Project is meant to be a singleton). in that case, project.js would just export a collection of functions as shown:
const slackInteractions = require('./slack-interactions')
// initalization
slackInteractions.action('project.select', this.projectSelect)
export const interactionDispatcherMiddleware = slackInteractions.expressMiddleware()
export async function projectSelect(payload, respond) {
try {
const selectedID = payload.actions[0].selected_options[0].value
const project = await Project.findByID(selectedID)
const someResult = await this.doSomething()
respond({ text: `Project name ${project.name} was selected. Result: ${someResult}` });
} catch (err) {
respond({ text: `An error occurred: ${err}` });
}
}
export async function doSomething() {
// implement me
}
let me know if this clears things up for you. we're getting into application architecture patterns more than the specifics of this package, but i'm happy to have that discussion still.
Hi @adamcohen,
I'm going to close this issue out since been a while since the last reply. It seems like you may have figured this one out. If not, feel free to open a new issue in https://github.com/slackapi/node-slack-sdk/issues which is the new home for this project.