Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.ts

143 lines4.3 KB

1import { addRootProvider } from '@schematics/angular/utility'
2import {
3 NodeDependencyType,
4 addPackageJsonDependency,
5} from '@schematics/angular/utility/dependencies'
6import {
7 getAppModulePath,
8 isStandaloneApp,
9} from '@schematics/angular/utility/ng-ast-utils'
10import { findAppConfig } from '@schematics/angular/utility/standalone/app_config'
11import {
12 findBootstrapApplicationCall,
13 getMainFilePath,
14} from '@schematics/angular/utility/standalone/util'
15import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'
16import { chain } from '@angular-devkit/schematics'
17import ts from 'typescript'
18import type { Rule, Tree } from '@angular-devkit/schematics'
19import type { Schema } from './schema'
20​
21// Replaced with package metadata by scripts/inject-schematic-package-info.js.
22// The published schematic contains literal values and does not read package.json.
23const PACKAGE_NAME = '__ANGULAR_QUERY_PACKAGE_NAME__'
24const DEVTOOLS_PACKAGE_NAME = '__ANGULAR_QUERY_DEVTOOLS_PACKAGE_NAME__'
25const DEVTOOLS_PACKAGE_VERSION = '__ANGULAR_QUERY_DEVTOOLS_PACKAGE_VERSION__'
26​
27function hasPackageDependency(tree: Tree, name: string) {
28 const packageJsonPath = tree.exists('/package.json')
29 ? '/package.json'
30 : 'package.json'
31 const packageJson = JSON.parse(tree.readText(packageJsonPath)) as Record<
32 string,
33 Record<string, string> | undefined
34 >
35​
36 return ['dependencies', 'devDependencies', 'optionalDependencies'].some(
37 (dependencyType) => packageJson[dependencyType]?.[name] !== undefined,
38 )
40​
41function addDevtoolsDependency(): Rule {
42 return (tree, context) => {
43 if (hasPackageDependency(tree, DEVTOOLS_PACKAGE_NAME)) return tree
44​
45 addPackageJsonDependency(tree, {
46 type: NodeDependencyType.Default,
47 name: DEVTOOLS_PACKAGE_NAME,
48 version: DEVTOOLS_PACKAGE_VERSION,
49 overwrite: false,
50 })
51 context.addTask(new NodePackageInstallTask())
52 return tree
53 }
55​
56function hasProviderCall(tree: Tree, sourcePath: string) {
57 const source = ts.createSourceFile(
58 sourcePath,
59 tree.readText(sourcePath),
60 ts.ScriptTarget.Latest,
61 true,
62 )
63 const localProviderNames = new Set<string>()
64​
65 for (const statement of source.statements) {
66 if (
67 !ts.isImportDeclaration(statement) ||
68 !ts.isStringLiteral(statement.moduleSpecifier) ||
69 statement.moduleSpecifier.text !== PACKAGE_NAME ||
70 !statement.importClause?.namedBindings ||
71 !ts.isNamedImports(statement.importClause.namedBindings)
72 ) {
73 continue
74 }
75​
76 for (const element of statement.importClause.namedBindings.elements) {
77 if (
78 (element.propertyName ?? element.name).text === 'provideTanStackQuery'
79 ) {
80 localProviderNames.add(element.name.text)
81 }
82 }
83 }
84​
85 if (localProviderNames.size === 0) return false
86​
87 let found = false
88 const visit = (node: ts.Node) => {
89 if (
90 ts.isCallExpression(node) &&
91 ts.isIdentifier(node.expression) &&
92 localProviderNames.has(node.expression.text)
93 ) {
94 found = true
95 return
96 }
97​
98 if (!found) ts.forEachChild(node, visit)
99 }
100 visit(source)
101 return found
103​
104async function hasRootQueryProvider(tree: Tree, projectName: string) {
105 const mainFilePath = await getMainFilePath(tree, projectName)
106 const rootFilePath = isStandaloneApp(tree, mainFilePath)
107 ? (findAppConfig(
108 findBootstrapApplicationCall(tree, mainFilePath),
109 tree,
110 mainFilePath,
111 )?.filePath ?? mainFilePath)
112 : getAppModulePath(tree, mainFilePath)
113​
114 return hasProviderCall(tree, rootFilePath)
116​
117function addQueryProvider(project: string): Rule {
118 return async (tree) => {
119 if (await hasRootQueryProvider(tree, project)) return tree
120​
121 return addRootProvider(
122 project,
123 ({ code, external }) =>
124 code`${external(
125 'provideTanStackQuery',
126 PACKAGE_NAME,
127 )}(() => new ${external(
128 'QueryClient',
129 PACKAGE_NAME,
130 )}(), ${external('withDevtools', DEVTOOLS_PACKAGE_NAME)}())`,
131 )
132 }
134​
135/**
136 * Configures TanStack Query at the application root.
137 *
138 * The QueryClient factory is resolved by each root injector, preventing query
139 * caches from being shared between SSR requests.
140 */
141export function ngAdd(options: Schema): Rule {
142 return chain([addDevtoolsDependency(), addQueryProvider(options.project)])