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