smartuniverse/ts/smartuniverse.classes.reactionresponse.ts

64 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-09-09 22:39:18 +00:00
import * as plugins from './smartuniverse.plugins';
2019-09-10 17:36:10 +00:00
import { ICombinatorPayload } from './smartuniverse.classes.reactionrequest';
import { UniverseChannel } from './smartuniverse.classes.universechannel';
import { ClientUniverseChannel } from './smartuniverse.classes.clientuniversechannel';
import { UniverseMessage } from './smartuniverse.classes.universemessage';
import { ClientUniverseMessage } from './smartuniverse.classes.clientuniversemessage';
2019-11-09 12:00:30 +00:00
export type TReactionResponseFuncDef<T extends plugins.typedrequestInterfaces.ITypedRequest> = (
dataArg: T['request']
) => Promise<T['response']>;
2019-09-11 08:11:34 +00:00
export interface IReactionResponseConstructorOptions<
T extends plugins.typedrequestInterfaces.ITypedRequest
> {
2019-09-10 17:36:10 +00:00
method: T['method'];
channels: Array<UniverseChannel | ClientUniverseChannel>;
2019-09-11 08:11:34 +00:00
funcDef: TReactionResponseFuncDef<T>;
2019-09-10 17:36:10 +00:00
}
export class ReactionResponse<T extends plugins.typedrequestInterfaces.ITypedRequest> {
public method: T['method'];
2020-09-24 18:13:48 +00:00
public channels = new plugins.lik.ObjectMap<UniverseChannel | ClientUniverseChannel>();
2019-09-11 08:11:34 +00:00
public funcDef: TReactionResponseFuncDef<T>;
2019-09-10 17:36:10 +00:00
constructor(optionsArg: IReactionResponseConstructorOptions<T>) {
2019-09-11 08:11:34 +00:00
this.method = optionsArg.method;
2019-09-10 17:36:10 +00:00
this.channels.addArray(optionsArg.channels);
2019-09-11 08:11:34 +00:00
this.funcDef = optionsArg.funcDef;
2019-09-10 17:36:10 +00:00
for (const channel of this.channels.getArray()) {
channel.subscribe(messageArg => {
2019-09-11 08:11:34 +00:00
this.processMessageForReaction(channel, messageArg);
2019-09-10 17:36:10 +00:00
});
}
}
2019-09-11 08:11:34 +00:00
private async processMessageForReaction(
channelArg: UniverseChannel | ClientUniverseChannel,
messageArg:
| UniverseMessage<ICombinatorPayload<T>>
| ClientUniverseMessage<ICombinatorPayload<T>>
) {
if (
messageArg.messageText === 'reactionRequest' &&
messageArg.payload.typedRequestPayload.method === this.method
) {
2019-11-09 12:00:30 +00:00
const response: T['response'] = await this.funcDef(
messageArg.payload.typedRequestPayload.request
);
2019-09-11 08:11:34 +00:00
const payload: ICombinatorPayload<T> = {
...messageArg.payload,
typedRequestPayload: {
...messageArg.payload.typedRequestPayload,
response
}
};
channelArg.sendMessage({
messageText: 'reactionResponse',
2019-11-09 12:00:30 +00:00
payload
2019-09-11 08:11:34 +00:00
});
}
2019-09-10 17:36:10 +00:00
}
2019-09-10 16:03:46 +00:00
}