Open jacekelgda opened 6 years ago
For the controllers, I have a couple of suggestions:
export const wakeUp = () => {}
) this way, you can still test the function by just calling it with a mocked request object. This means, that you have a router
file next to all controllers, that does the wiring. This file then has to know, which function has to be invoked on which route. The second option is, to export "annotated callbacks" objects. Each such handler object has an execute function an a route property. Some place in your application can then just loop through all annotated callbacks and add them to a router.Good ideas @andreasgruenh ! Would you be willing to create a proof of concept for your suggestions ? Do you have any ideas for testing RTM API ( websockets ) for slack part ?
It could look something like this:
Advantages of this solution:
Disadvantages
controllers/composeApplyToRouter.js
export default const composeApplyToRouter = ({ method, path }) => function(router) {
router[method](path, this)
}
controllers/auth.js
import composeApplyToRouter from './composeApplyToRouter'
const composeAuth = ({
exchangeCodeForToken,
storeTeamToken,
createNewBotConnection,
sendPostInstallMessage,
}) => {
async function auth(req, res) {
try {
const token = await exchangeCodeForToken(req.query.code)
storeTeamToken(token)
const bot = createNewBotConnection({
token: token.bot.bot_access_token,
team: token.team_id
})
sendPostInstallMessage(bot, token.user_id, token.team_id)
res.send('Thank you for authorizing our application')
} catch (e) {
res.send('Error. Invalid/expired code.')
}
}
auth.applyToRouter = composeApplyToRouter({ method: 'get', path: '/auth' })
return auth
}
export default composeAuth
routes.js
import { Router } from 'express'
import { exchangeCodeForToken } from '../handlers/api'
import { storeTeamToken } from '../handlers/store'
import { createNewBotConnection, sendPostInstallMessage } from '../handlers/bot'
import composeAuth from './auth'
const router = new Router()
composeAuth({
exchangeCodeForToken,
storeTeamToken,
createNewBotConnection,
sendPostInstallMessage
}).applyToRouter(router)
Great suggestions @andreasgruenh, thanks for valuable input! 💯
Your suggestion definitely makes sense, I'm also not a big fan of overwriting require calls so I'd rather proceed with the flow proposed by you.
Regarding the first disadvantage - I don't think that putting that code into router is a big issue.
There is one test added in this project as example. Take a look inside
./util/__tests__
. We need to add unit tests in some parts of this application. There is no good idea to create tests for handlers and controllers right now so discussion is more than welcome.