Skip to content

POC: Dynamically generated Backend service #9503

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 155 additions & 1 deletion apps/desktop/src/lib/backend/backendService.svelte.ts
Original file line number Diff line number Diff line change
@@ -1 +1,155 @@
export default class BackendService {}
import {
createMutationEndpoint,
createQueryEndpointWithTransform,
type CustomBuilder,
type EndpointMap
} from '$lib/state/butlerModule';
import { invalidatesItem, invalidatesList, providesItems, ReduxTag } from '$lib/state/tags';
import { createEntityAdapter, type EntityState } from '@reduxjs/toolkit';
import type {
CreateRuleRequest,
UpdateRuleRequest,
WorkspaceRule,
WorkspaceRuleId
} from '$lib/rules/rule';
import type { BackendApi } from '$lib/state/clientState.svelte';

function typedEntries<T extends Record<string, unknown>>(obj: T): [keyof T, T[keyof T]][] {
return Object.entries(obj) as [keyof T, T[keyof T]][];
}

function typedFromEntries<T extends Record<string, unknown>>(entries: [keyof T, T[keyof T]][]): T {
return Object.fromEntries(entries) as T;
}

export default class BackendService {
private static instance: BackendService;
private mutationApi: ReturnType<typeof injectMutationEndpoints>;
private queryApi: ReturnType<typeof injectQueryEndpoints>;

private constructor(backendApi: BackendApi) {
this.mutationApi = injectMutationEndpoints(backendApi);
this.queryApi = injectQueryEndpoints(backendApi);
}

Comment on lines +30 to +33
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We then store them in private properties

static getInstance(backendApi: BackendApi): BackendService {
if (!BackendService.instance) {
BackendService.instance = new BackendService(backendApi);
}
return BackendService.instance;
}

get() {
// Mutations
type MutationEndpoints = typeof this.mutationApi.endpoints;

type MutateMap = {
[K in keyof MutationEndpoints as `${K}Mutate`]: MutationEndpoints[K]['mutate'];
};

type UseMutationMap = {
[K in keyof MutationEndpoints as `${K}UseMutation`]: MutationEndpoints[K]['useMutation'];
};

const mutate = typedFromEntries(
typedEntries(this.mutationApi.endpoints).map(
([key, value]) => [`${key}Mutate`, value.mutate] as const
)
) as MutateMap;

const useMutation = typedFromEntries(
typedEntries(this.mutationApi.endpoints).map(
([key, value]) => [`${key}UseMutation`, value.useMutation] as const
)
) as UseMutationMap;

// Queries
type QueryEndpoints = typeof this.queryApi.endpoints;

type UseQueryMap = {
[K in keyof QueryEndpoints as `${K}UseQuery`]: (typeof this.queryApi.endpoints)[K]['useQuery'];
};

type FetchMap = {
[K in keyof QueryEndpoints as `${K}Fetch`]: (typeof this.queryApi.endpoints)[K]['fetch'];
};

const useQuery = typedFromEntries(
typedEntries(this.queryApi.endpoints).map(
([key, value]) => [`${key}UseQuery`, value.useQuery] as const
)
) as UseQueryMap;

const fetchMap = typedFromEntries(
typedEntries(this.queryApi.endpoints).map(
([key, value]) => [`${key}Fetch`, value.fetch] as const
)
) as FetchMap;

return {
...mutate,
...useMutation,
...useQuery,
...fetchMap
};
}
}
Comment on lines +42 to +95
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And then, out of the endpoint entries, we generate the map of functions


function injectQueryEndpoints(api: BackendApi) {
return api.injectEndpoints({
endpoints: (build) => getQueryEndpointMap(build)
});
}

function injectMutationEndpoints(api: BackendApi) {
return api.injectEndpoints({
endpoints: (build) => getMutationEndpointMap(build)
});
}

function getMutationEndpointMap(builder: CustomBuilder) {
return {
createWorkspaceRule: createMutationEndpoint<
WorkspaceRule,
{ projectId: string; request: CreateRuleRequest }
>(builder, 'create_workspace_rule', () => [invalidatesList(ReduxTag.WorkspaceRules)]),
deleteWorkspaceRule: createMutationEndpoint<
void,
{ projectId: string; ruleId: WorkspaceRuleId }
>(builder, 'delete_workspace_rule', () => [invalidatesList(ReduxTag.WorkspaceRules)]),
updateWorkspaceRule: createMutationEndpoint<
WorkspaceRule,
{ projectId: string; request: UpdateRuleRequest }
>(builder, 'update_workspace_rule', (result) =>
result
? [
invalidatesItem(ReduxTag.WorkspaceRules, result.id),
invalidatesList(ReduxTag.WorkspaceRules)
]
: []
)
} satisfies EndpointMap;
}

function getQueryEndpointMap(builder: CustomBuilder) {
return {
listWorkspaceRules: createQueryEndpointWithTransform<
WorkspaceRule[],
{ projectId: string },
EntityState<WorkspaceRule, WorkspaceRuleId>
>(
builder,
'list_workspace_rules',
(response: WorkspaceRule[]) => {
return workspaceRulesAdapter.addMany(workspaceRulesAdapter.getInitialState(), response);
},
(result) => providesItems(ReduxTag.WorkspaceRules, result?.ids ?? [])
)
} satisfies EndpointMap;
}

Comment on lines +110 to +149
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So first we defined the endpoints.
The injection happens for queries and mutations separately in order to preserve the type safety when iterating over the entries

const workspaceRulesAdapter = createEntityAdapter<WorkspaceRule, WorkspaceRuleId>({
selectId: (rule) => rule.id
});

export const workspaceRulesSelectors = workspaceRulesAdapter.getSelectors();
74 changes: 9 additions & 65 deletions apps/desktop/src/lib/rules/rulesService.svelte.ts
Original file line number Diff line number Diff line change
@@ -1,87 +1,31 @@
import { invalidatesItem, invalidatesList, providesItems, ReduxTag } from '$lib/state/tags';
import { createEntityAdapter, type EntityState } from '@reduxjs/toolkit';
import type {
CreateRuleRequest,
UpdateRuleRequest,
WorkspaceRule,
WorkspaceRuleId
} from '$lib/rules/rule';
import BackendService, { workspaceRulesSelectors } from '$lib/backend/backendService.svelte';
import type { BackendApi } from '$lib/state/clientState.svelte';

export default class RulesService {
private api: ReturnType<typeof injectEndpoints>;
private backendService: BackendService;
private apis: ReturnType<typeof this.backendService.get>;

constructor(backendApi: BackendApi) {
this.api = injectEndpoints(backendApi);
this.backendService = BackendService.getInstance(backendApi);
this.apis = this.backendService.get();
}
Comment on lines -15 to +10
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The backend service here is consumed as a singleton


get createWorkspaceRule() {
return this.api.endpoints.createWorkspaceRule.useMutation();
return this.apis.createWorkspaceRuleUseMutation();
}

get deleteWorkspaceRule() {
return this.api.endpoints.deleteWorkspaceRule.useMutation();
return this.apis.deleteWorkspaceRuleUseMutation();
}

get updateWorkspaceRule() {
return this.api.endpoints.updateWorkspaceRule.useMutation();
return this.apis.updateWorkspaceRuleUseMutation();
}

listWorkspaceRules(projectId: string) {
return this.api.endpoints.listWorkspaceRules.useQuery(
return this.apis.listWorkspaceRulesUseQuery(
{ projectId },
{ transform: (result) => workspaceRulesSelectors.selectAll(result) }
);
}
Comment on lines +26 to 29
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the result is transformed into an entity state instance, we need to select it when consuming it.

}

function injectEndpoints(api: BackendApi) {
return api.injectEndpoints({
endpoints: (build) => ({
createWorkspaceRule: build.mutation<
WorkspaceRule,
{ projectId: string; request: CreateRuleRequest }
>({
extraOptions: { command: 'create_workspace_rule' },
query: (args) => args,
invalidatesTags: () => [invalidatesList(ReduxTag.WorkspaceRules)]
}),
deleteWorkspaceRule: build.mutation<void, { projectId: string; ruleId: WorkspaceRuleId }>({
extraOptions: { command: 'delete_workspace_rule' },
query: (args) => args,
invalidatesTags: () => [invalidatesList(ReduxTag.WorkspaceRules)]
}),
updateWorkspaceRule: build.mutation<
WorkspaceRule,
{ projectId: string; request: UpdateRuleRequest }
>({
extraOptions: { command: 'update_workspace_rule' },
query: (args) => args,
invalidatesTags: (result) =>
result
? [
invalidatesItem(ReduxTag.WorkspaceRules, result.id),
invalidatesList(ReduxTag.WorkspaceRules)
]
: []
}),
listWorkspaceRules: build.query<
EntityState<WorkspaceRule, WorkspaceRuleId>,
{ projectId: string }
>({
extraOptions: { command: 'list_workspace_rules' },
query: (args) => args,
providesTags: (result) => providesItems(ReduxTag.WorkspaceRules, result?.ids ?? []),
transformResponse: (response: WorkspaceRule[]) => {
return workspaceRulesAdapter.addMany(workspaceRulesAdapter.getInitialState(), response);
}
})
})
});
}

const workspaceRulesAdapter = createEntityAdapter<WorkspaceRule, WorkspaceRuleId>({
selectId: (rule) => rule.id
});

const workspaceRulesSelectors = workspaceRulesAdapter.getSelectors();
Loading
Loading