Skip to content

Commit

Permalink
fix(core): add types for hook response based on io-ts contract
Browse files Browse the repository at this point in the history
  • Loading branch information
sckv committed Feb 7, 2022
1 parent 792fb3d commit f197326
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
12 changes: 6 additions & 6 deletions src/engine/typed-bus.ts
Expand Up @@ -12,7 +12,7 @@ const generateConsumerId = hyperid();

type PublishOptions<T> = {
onlySendTo?: string[];
hook?: iots.Any;
hook?: T extends iots.Any ? T : never;
};

export class TypedBusClass {
Expand All @@ -23,26 +23,26 @@ export class TypedBusClass {
this.transports.push(new InternalTransport());
}

async publish<T = false>(
async publish<T, R = T extends iots.Any ? iots.OutputOf<T> : void>(
eventData: any,
options: PublishOptions<T> = {},
): Promise<void | unknown> {
): Promise<R> {
const publishedTransports: string[] = [];
const event = Event.create(eventData, typeof options.hook !== undefined);

this.storeInContext(event);
let hookPromise: unknown = undefined;

if (options.hook) {
hookPromise = new Promise<unknown>((resolve, reject) => {
hookPromise = new Promise<any>((resolve, reject) => {
const consumerId = { id: '' };
const timoutRef = setTimeout(reject, 1000);

const resolver = (resultData: unknown) => {
this.removeConsumer(consumerId.id);
clearTimeout(timoutRef);

resolve(resultData);
resolve(resultData as any);
};

consumerId.id = this.addConsumer(options.hook!, resolver, { hookId: event.hookId }).id;
Expand Down Expand Up @@ -79,7 +79,7 @@ export class TypedBusClass {

if (event.orphanTransports?.size) this.orphanEventsStore.addEvent(event);

return hookPromise;
return hookPromise as any;
}

storeInContext(event: Event): void {
Expand Down
4 changes: 2 additions & 2 deletions src/example/playground.ts
Expand Up @@ -10,7 +10,7 @@ class ConsumerTest {

const hookResponse = await TypedBus.publish(
{ amount: 1234, currency: 'EUR' },
{ hook: iots.type({ hookProp: iots.string, hookValue: iots.number }) },
{ hook: iots.type({ hookProp: iots.literal('value'), hookValue: iots.number }) },
);

console.log('received from hook resolution', hookResponse);
Expand All @@ -20,7 +20,7 @@ class ConsumerTest {
async anotherConsumer(data: any) {
console.log('I just consumed the money event', data);
await TypedBus.publish({ some: 'event', is: 'orphan' });
await TypedBus.publish({ hookProp: 'some value', hookValue: 123 });
await TypedBus.publish({ hookProp: 'value', hookValue: 123 });
console.log(TypedBus.orphanEventsStore);
}
}
Expand Down

0 comments on commit f197326

Please sign in to comment.