2017-06-21 08:40:28 +02:00
|
|
|
import { addMessages, inform, print } from 'state/messages';
|
2018-04-05 21:13:32 +02:00
|
|
|
import { isChannel } from 'utils';
|
2017-05-22 03:49:37 +02:00
|
|
|
|
2017-05-28 07:20:43 +02:00
|
|
|
export const beforeHandler = '_before';
|
|
|
|
export const notFoundHandler = 'commandNotFound';
|
2017-05-22 03:49:37 +02:00
|
|
|
|
|
|
|
function createContext({ dispatch, getState }, { server, channel }) {
|
2020-05-06 04:50:27 +02:00
|
|
|
return { dispatch, getState, server, channel, inChannel: isChannel(channel) };
|
2017-05-28 07:20:43 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Pull this out as convenience action
|
|
|
|
function process({ dispatch, server, channel }, result) {
|
|
|
|
if (typeof result === 'string') {
|
|
|
|
dispatch(inform(result, server, channel));
|
|
|
|
} else if (Array.isArray(result)) {
|
|
|
|
if (typeof result[0] === 'string') {
|
|
|
|
dispatch(inform(result, server, channel));
|
|
|
|
} else if (typeof result[0] === 'object') {
|
|
|
|
dispatch(addMessages(result, server, channel));
|
|
|
|
}
|
|
|
|
} else if (typeof result === 'object' && result) {
|
|
|
|
dispatch(print(result.content, server, channel, result.type));
|
|
|
|
}
|
2017-05-22 03:49:37 +02:00
|
|
|
}
|
|
|
|
|
2015-12-29 00:34:32 +01:00
|
|
|
export default function createCommandMiddleware(type, handlers) {
|
2017-05-22 03:49:37 +02:00
|
|
|
return store => next => action => {
|
2015-12-29 00:34:32 +01:00
|
|
|
if (action.type === type) {
|
|
|
|
const words = action.command.slice(1).split(' ');
|
2020-05-01 02:12:21 +02:00
|
|
|
const command = words[0].toLowerCase();
|
2015-12-29 00:34:32 +01:00
|
|
|
const params = words.slice(1);
|
|
|
|
|
2017-04-11 03:49:52 +02:00
|
|
|
if (command in handlers) {
|
2017-05-28 07:20:43 +02:00
|
|
|
const ctx = createContext(store, action);
|
|
|
|
if (beforeHandler in handlers) {
|
|
|
|
process(ctx, handlers[beforeHandler](ctx, command, ...params));
|
|
|
|
}
|
|
|
|
process(ctx, handlers[command](ctx, ...params));
|
|
|
|
} else if (notFoundHandler in handlers) {
|
|
|
|
const ctx = createContext(store, action);
|
2017-06-02 22:24:03 +02:00
|
|
|
process(ctx, handlers[notFoundHandler](ctx, command, ...params));
|
2015-12-29 00:34:32 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return next(action);
|
|
|
|
};
|
|
|
|
}
|