smartuniverse/ts/smartuniverse.classes.event.reactionresponse.ts
2023-07-25 11:33:13 +02:00

64 lines
2.2 KiB
TypeScript

import * as plugins from './smartuniverse.plugins.js';
import { type ICombinatorPayload } from './smartuniverse.classes.event.reactionrequest.js';
import { UniverseChannel } from './smartuniverse.classes.universechannel.js';
import { ClientUniverseChannel } from './smartuniverse.classes.client.universechannel.js';
import { UniverseMessage } from './smartuniverse.classes.universemessage.js';
import { ClientUniverseMessage } from './smartuniverse.classes.client.universemessage.js';
export type TReactionResponseFuncDef<T extends plugins.typedrequestInterfaces.ITypedRequest> = (
dataArg: T['request']
) => Promise<T['response']>;
export interface IReactionResponseConstructorOptions<
T extends plugins.typedrequestInterfaces.ITypedRequest
> {
method: T['method'];
channels: Array<UniverseChannel | ClientUniverseChannel>;
funcDef: TReactionResponseFuncDef<T>;
}
export class ReactionResponse<T extends plugins.typedrequestInterfaces.ITypedRequest> {
public method: T['method'];
public channels = new plugins.lik.ObjectMap<UniverseChannel | ClientUniverseChannel>();
public funcDef: TReactionResponseFuncDef<T>;
constructor(optionsArg: IReactionResponseConstructorOptions<T>) {
this.method = optionsArg.method;
this.channels.addArray(optionsArg.channels);
this.funcDef = optionsArg.funcDef;
for (const channel of this.channels.getArray()) {
channel.subscribe((messageArg) => {
this.processMessageForReaction(channel, messageArg);
});
}
}
private async processMessageForReaction(
channelArg: UniverseChannel | ClientUniverseChannel,
messageArg:
| UniverseMessage<ICombinatorPayload<T>>
| ClientUniverseMessage<ICombinatorPayload<T>>
) {
if (
messageArg.messageText === 'reactionRequest' &&
messageArg.payload.typedRequestPayload.method === this.method
) {
const response: T['response'] = await this.funcDef(
messageArg.payload.typedRequestPayload.request
);
const payload: ICombinatorPayload<T> = {
...messageArg.payload,
typedRequestPayload: {
...messageArg.payload.typedRequestPayload,
response,
},
};
channelArg.postMessage({
messageText: 'reactionResponse',
payload,
});
}
}
}