Skip to content

Commit

Permalink
add subscribe composable factory
Browse files Browse the repository at this point in the history
  • Loading branch information
SchroterQuentin committed Nov 5, 2024
1 parent 58acdd5 commit b9a1df9
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Bones.UI/abstractions/inotifyService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ export type AllEvent = NotifyEvent | "all";
export type AddOrUpdateCallback<TDetails> = (ev: AddOrUpdateEvent, payload: TDetails) => void;
export type DeleteCallback = (ev: DeleteEvent, id: any) => void;
export type ResetCallback = (ev: ResetEvent) => void;
export type AllCallback<TDetails> = AddOrUpdateCallback<TDetails> | DeleteCallback | ResetCallback;
export type AllCallback<TDetails> = AddOrUpdateCallback<TDetails> | DeleteCallback | ResetCallback;

export type SubscribeCall<TDetails> = [AddOrUpdateEvent, AddOrUpdateCallback<TDetails>] | [DeleteEvent, DeleteCallback] | [ResetEvent, ResetCallback] | [AllEvent, AllCallback<TDetails>];
21 changes: 21 additions & 0 deletions src/Bones.UI/core/composableFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,27 @@ export class ComposableFactory {
return ComposableFactory.customRemove(service.remove);
}

public static subscribe<TDetails>(service: INotifyService<TDetails>) {
return () => {
let subscribersIds: number[] = [];

onUnmounted(() => {
subscribersIds.forEach(id => service.unsubscribe(id));
subscribersIds = [];
});

const subscribe: INotifyService<TDetails>["subscribe"] = (ev: any, callback: any) => {
const subscriberId = service.subscribe(ev, callback);
subscribersIds.push(subscriberId);
return subscriberId;
}

return {
subscribe
}
}
}

public static custom<TDetails, TArgs extends any[]>(method: (...args: TArgs) => Promise<TDetails>, applyFactory?: () => (entity: Ref<TDetails>) => void) {
return () => {
const apply = applyFactory ? applyFactory() : () => { };
Expand Down
7 changes: 7 additions & 0 deletions tests/Bones.UI.Tests/services/testUserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ const AccountLoginFactory = new ServiceFactory<TestUserDetailsDTO, TestUserDetai
export const useTestUsersSync = ComposableFactory.sync<TestUserDetails, TestUserInfos>(testUserServiceFactory);
export const useTestUserTrack = ComposableFactory.trackRef(testUserServiceFactory);

export const useTestUserSubscribe = ComposableFactory.subscribe(testUserServiceFactory);

const { subscribe } = useTestUserSubscribe();

subscribe("add", (ev, payload) => {
console.log(ev, payload);
});

export const useLogin = ComposableFactory.custom(AccountLoginFactory.login, () => {
const { sync } = useTestUsersSync();
Expand Down

0 comments on commit b9a1df9

Please sign in to comment.