Skip to content

Angular tanstack query #2206

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

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
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
18 changes: 17 additions & 1 deletion packages/plugins/tanstack-query/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@
"import": "./runtime-v5/svelte.mjs",
"require": "./runtime-v5/svelte.js",
"default": "./runtime-v5/svelte.js"
},
"./runtime-v5/angular": {
"types": "./runtime-v5/angular.d.ts",
"import": "./runtime-v5/angular.mjs",
"require": "./runtime-v5/angular.js",
"default": "./runtime-v5/angular.js"
}
},
"repository": {
Expand Down Expand Up @@ -87,7 +93,14 @@
"ts-morph": "^16.0.0",
"ts-pattern": "^4.3.0"
},
"peerDependencies": {
"@tanstack/angular-query-experimental": "^5.0.0"
},
"devDependencies": {
"@angular/core": "^20.0.0",
"@angular/common": "^20.0.0",
"@angular/platform-browser": "^20.0.0",
"@tanstack/angular-query-v5": "npm:@tanstack/angular-query-experimental@5.84.x",
"@tanstack/react-query": "^4.29.7",
"@tanstack/react-query-v5": "npm:@tanstack/react-query@5.56.x",
"@tanstack/svelte-query": "^4.29.7",
Expand All @@ -103,9 +116,12 @@
"nock": "^13.3.6",
"react": "18.2.0",
"react-test-renderer": "^18.2.0",
"rxjs": "^7.8.0",
"svelte": "^4.2.1",
"swr": "^2.0.3",
"tmp": "^0.2.3",
"vue": "^3.3.4"
"typescript": "^5.0.0",
"vue": "^3.3.4",
"zone.js": "^0.15.0"
}
}
7 changes: 7 additions & 0 deletions packages/plugins/tanstack-query/scripts/postbuild.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,10 @@ replaceSync({
from: /@tanstack\/vue-query-v5/g,
to: '@tanstack/vue-query',
});

console.log('Replacing @tanstack/angular-query-v5');
replaceSync({
file: 'dist/runtime-v5/angular*(.d.ts|.d.mts|.js|.mjs)',
from: /@tanstack\/angular-query-v5/g,
to: '@tanstack/angular-query-experimental',
});
28 changes: 27 additions & 1 deletion packages/plugins/tanstack-query/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { Project, SourceFile, VariableDeclarationKind } from 'ts-morph';
import { P, match } from 'ts-pattern';
import { name } from '.';

const supportedTargets = ['react', 'vue', 'svelte'];
const supportedTargets = ['react', 'vue', 'svelte', 'angular'];
type TargetFramework = (typeof supportedTargets)[number];
type TanStackVersion = 'v4' | 'v5';

Expand All @@ -41,6 +41,11 @@ export async function generate(model: Model, options: PluginOptions, dmmf: DMMF.
throw new PluginError(name, `Unsupported version "${version}": use "v4" or "v5"`);
}

// Angular is only supported in v5
if (target === 'angular' && version !== 'v5') {
throw new PluginError(name, `Angular target is only supported with version "v5", got "${version}"`);
}

let outDir = requireOption<string>(options, 'output', name);
outDir = resolvePath(outDir, options);
ensureEmptyDir(outDir);
Expand Down Expand Up @@ -224,6 +229,7 @@ function generateMutationHook(
switch (target) {
case 'react':
case 'vue':
case 'angular':
// override the mutateAsync function to return the correct type
func.addVariableStatement({
declarationKind: VariableDeclarationKind.Const,
Expand Down Expand Up @@ -597,6 +603,11 @@ function generateIndex(
case 'svelte':
sf.addStatements(`export { SvelteQueryContextKey, setHooksContext } from '${runtimeImportBase}/svelte';`);
break;
case 'angular':
sf.addStatements(
`export { AngularQueryContextKey, provideAngularQueryContext } from '${runtimeImportBase}/angular';`
);
break;
}
sf.addStatements(`export { default as metadata } from './__model_meta';`);
}
Expand All @@ -609,6 +620,8 @@ function makeGetContext(target: TargetFramework) {
return 'const { endpoint, fetch } = getHooksContext();';
case 'svelte':
return `const { endpoint, fetch } = getHooksContext();`;
case 'angular':
return 'const { endpoint, fetch } = getHooksContext();';
default:
throw new PluginError(name, `Unsupported target "${target}"`);
}
Expand Down Expand Up @@ -658,6 +671,13 @@ function makeBaseImports(target: TargetFramework, version: TanStackVersion) {
...shared,
];
}
case 'angular': {
return [
`import type { CreateMutationOptions, CreateQueryOptions, CreateInfiniteQueryOptions, InfiniteData } from '@tanstack/angular-query-v5';`,
`import { getHooksContext } from '${runtimeImportBase}/${target}';`,
...shared,
];
}
default:
throw new PluginError(name, `Unsupported target: ${target}`);
}
Expand Down Expand Up @@ -707,6 +727,11 @@ function makeQueryOptions(
? `Omit<CreateQueryOptions<${returnType}, TError, ${dataType}>, 'queryKey'>`
: `StoreOrVal<Omit<CreateQueryOptions<${returnType}, TError, ${dataType}>, 'queryKey'>>`
)
.with('angular', () =>
infinite
? `Omit<CreateInfiniteQueryOptions<${returnType}, TError, InfiniteData<${dataType}>>, 'queryKey' | 'initialPageParam'>`
: `Omit<CreateQueryOptions<${returnType}, TError, ${dataType}>, 'queryKey'>`
)
.otherwise(() => {
throw new PluginError(name, `Unsupported target: ${target}`);
});
Expand All @@ -727,6 +752,7 @@ function makeMutationOptions(target: string, returnType: string, argsType: strin
return `MaybeRefOrGetter<${baseOption}> | ComputedRef<${baseOption}>`;
})
.with('svelte', () => `MutationOptions<${returnType}, DefaultError, ${argsType}>`)
.with('angular', () => `CreateMutationOptions<${returnType}, DefaultError, ${argsType}>`)
.otherwise(() => {
throw new PluginError(name, `Unsupported target: ${target}`);
});
Expand Down
207 changes: 207 additions & 0 deletions packages/plugins/tanstack-query/src/runtime-v5/angular.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
injectQuery,
injectMutation,
injectInfiniteQuery,
QueryClient,
type CreateQueryOptions,
type CreateMutationOptions,
type CreateInfiniteQueryOptions,
type InfiniteData,
CreateInfiniteQueryResult,
QueryKey,
} from '@tanstack/angular-query-v5';
import type { ModelMeta } from '@zenstackhq/runtime/cross';
import { inject, InjectionToken } from '@angular/core';
import {
APIContext,
DEFAULT_QUERY_ENDPOINT,
fetcher,
getQueryKey,
makeUrl,
marshal,
setupInvalidation,
setupOptimisticUpdate,
type ExtraMutationOptions,
type ExtraQueryOptions,
type FetchFn,
} from '../runtime/common';

export { APIContext as RequestHandlerContext } from '../runtime/common';

export const AngularQueryContextKey = new InjectionToken<APIContext>('zenstack-angular-query-context');

/**
* Provide context for the generated TanStack Query hooks.
*/
export function provideAngularQueryContext(context: APIContext) {
return {
provide: AngularQueryContextKey,
useValue: context,
};
}

/**
* Hooks context.
*/
export function getHooksContext() {
const context = inject(AngularQueryContextKey, {
optional: true,
}) || {
endpoint: DEFAULT_QUERY_ENDPOINT,
fetch: undefined,
logging: false,
};

const { endpoint, ...rest } = context;
return { endpoint: endpoint ?? DEFAULT_QUERY_ENDPOINT, ...rest };
}

/**
* Creates an Angular TanStack Query query.
*
* @param model The name of the model under query.
* @param url The request URL.
* @param args The request args object, URL-encoded and appended as "?q=" parameter
* @param options The Angular query options object
* @param fetch The fetch function to use for sending the HTTP request
* @returns injectQuery hook
*/
export function useModelQuery<TQueryFnData, TData, TError>(
model: string,
url: string,
args?: unknown,
options?: Omit<CreateQueryOptions<TQueryFnData, TError, TData>, 'queryKey'> & ExtraQueryOptions,
fetch?: FetchFn
) {
const reqUrl = makeUrl(url, args);
const queryKey = getQueryKey(model, url, args, {
infinite: false,
optimisticUpdate: options?.optimisticUpdate !== false,
});
return {
queryKey,
...injectQuery(() => ({
queryKey,
queryFn: ({ signal }) => fetcher<TQueryFnData, false>(reqUrl, { signal }, fetch, false),
...options,
})),
};
}

/**
* Creates an Angular TanStack Query infinite query.
*
* @param model The name of the model under query.
* @param url The request URL.
* @param args The initial request args object, URL-encoded and appended as "?q=" parameter
* @param options The Angular infinite query options object
* @param fetch The fetch function to use for sending the HTTP request
* @returns injectInfiniteQuery hook
*/
export function useInfiniteModelQuery<TQueryFnData, TData, TError>(
model: string,
url: string,
args: unknown,
options: Omit<
CreateInfiniteQueryOptions<TQueryFnData, TError, InfiniteData<TData>>,
'queryKey' | 'initialPageParam'
>,
fetch?: FetchFn
): CreateInfiniteQueryResult<InfiniteData<TData>, TError> & { queryKey: QueryKey } {
const queryKey = getQueryKey(model, url, args, { infinite: true, optimisticUpdate: false });
return {
queryKey,
...injectInfiniteQuery(() => ({
queryKey,
queryFn: ({ pageParam, signal }) => {
return fetcher<TQueryFnData, false>(makeUrl(url, pageParam ?? args), { signal }, fetch, false);
},
initialPageParam: args,
...options,
})),
};
}

/**
* Creates an Angular TanStack Query mutation.
*
* @param model The name of the model under mutation.
* @param method The HTTP method.
* @param url The request URL.
* @param modelMeta The model metadata.
* @param options The Angular mutation options.
* @param fetch The fetch function to use for sending the HTTP request
* @param checkReadBack Whether to check for read back errors and return undefined if found.
* @returns injectMutation hook
*/
export function useModelMutation<
TArgs,
TError,
R = any,
C extends boolean = boolean,
Result = C extends true ? R | undefined : R
>(
model: string,
method: 'POST' | 'PUT' | 'DELETE',
url: string,
modelMeta: ModelMeta,
options?: Omit<CreateMutationOptions<Result, TError, TArgs>, 'mutationFn'> & ExtraMutationOptions,
fetch?: FetchFn,
checkReadBack?: C
) {
const queryClient = inject(QueryClient);
const mutationFn = (data: unknown) => {
const reqUrl = method === 'DELETE' ? makeUrl(url, data) : url;
const fetchInit: RequestInit = {
method,
...(method !== 'DELETE' && {
headers: {
'content-type': 'application/json',
},
body: marshal(data),
}),
};
return fetcher<R, C>(reqUrl, fetchInit, fetch, checkReadBack) as Promise<Result>;
};

const finalOptions = { ...options, mutationFn };
const operation = url.split('/').pop();
const invalidateQueries = options?.invalidateQueries !== false;
const optimisticUpdate = !!options?.optimisticUpdate;

if (operation) {
const { logging } = getHooksContext();
if (invalidateQueries) {
setupInvalidation(
model,
operation,
modelMeta,
finalOptions,
(predicate) => queryClient.invalidateQueries({ predicate }),
logging
);
}

if (optimisticUpdate) {
setupOptimisticUpdate(
model,
operation,
modelMeta,
finalOptions,
queryClient.getQueryCache().getAll(),
(queryKey, data) => {
// update query cache
queryClient.setQueryData<unknown>(queryKey, data);
// cancel on-flight queries to avoid redundant cache updates,
// the settlement of the current mutation will trigger a new revalidation
queryClient.cancelQueries({ queryKey }, { revert: false, silent: true });
},
invalidateQueries ? (predicate) => queryClient.invalidateQueries({ predicate }) : undefined,
logging
);
}
}

return injectMutation(() => finalOptions);
}
Loading