Skip to main content

odk_cli/generate/
react_query.rs

1//! React Query target — per-operation hooks and provider.
2//!
3//! Generates:
4//! - `hooks.ts` — useQuery/useMutation hooks per operation
5//! - `provider.tsx` — React context provider for client instance
6
7use odk_schema::{CompiledSchema, OperationKind};
8use std::collections::BTreeMap;
9
10use super::util;
11
12/// Generate React Query hooks and provider.
13pub fn generate(schema: &CompiledSchema) -> BTreeMap<String, String> {
14    let mut output = BTreeMap::new();
15
16    if schema.operations.is_empty() {
17        return output;
18    }
19
20    output.insert("hooks.ts".to_string(), generate_hooks(schema));
21    output.insert("provider.tsx".to_string(), generate_provider());
22    output
23}
24
25fn generate_hooks(schema: &CompiledSchema) -> String {
26    let mut lines = Vec::new();
27
28    // Collect which hook types we need
29    let has_queries = schema
30        .operations
31        .iter()
32        .any(|op| matches!(op.kind, OperationKind::Query));
33    let has_mutations = schema
34        .operations
35        .iter()
36        .any(|op| matches!(op.kind, OperationKind::Mutation));
37
38    // React Query imports
39    let mut rq_imports = Vec::new();
40    if has_queries {
41        rq_imports.push("useQuery");
42        rq_imports.push("type UseQueryOptions");
43    }
44    if has_mutations {
45        rq_imports.push("useMutation");
46        rq_imports.push("type UseMutationOptions");
47    }
48    lines.push(format!(
49        "import {{ {} }} from \"@tanstack/react-query\";",
50        rq_imports.join(", ")
51    ));
52
53    // Client imports
54    let mut client_imports = Vec::new();
55    for op in &schema.operations {
56        client_imports.push(format!("{}Document", op.name));
57        client_imports.push(format!("type {}Result", op.name));
58        if !op.variables.is_empty() {
59            client_imports.push(format!("type {}Variables", op.name));
60        }
61    }
62    lines.push(format!(
63        "import {{ {} }} from \"./client\";",
64        client_imports.join(", ")
65    ));
66    lines.push("import { useODKClient } from \"./provider\";".to_string());
67    lines.push(String::new());
68
69    // Hooks
70    for op in &schema.operations {
71        let hook_name = util::to_hook_name(&op.name);
72        let method_name = util::to_method_name(&op.name);
73
74        match op.kind {
75            OperationKind::Query => {
76                if op.variables.is_empty() {
77                    lines.push(format!("export const {} = (", hook_name));
78                    lines.push(format!(
79                        "  options?: Omit<UseQueryOptions<{}Result>, \"queryKey\" | \"queryFn\">,",
80                        op.name
81                    ));
82                    lines.push(") => {".to_string());
83                    lines.push("  const client = useODKClient();".to_string());
84                    lines.push("  return useQuery({".to_string());
85                    lines.push(format!("    queryKey: [\"{}\"],", op.name));
86                    lines.push(format!(
87                        "    queryFn: ({{ signal }}) => client.{}({{ signal }}),",
88                        method_name
89                    ));
90                    lines.push("    ...options,".to_string());
91                    lines.push("  });".to_string());
92                    lines.push("};".to_string());
93                } else {
94                    lines.push(format!("export const {} = (", hook_name));
95                    lines.push(format!("  variables: {}Variables,", op.name));
96                    lines.push(format!(
97                        "  options?: Omit<UseQueryOptions<{}Result>, \"queryKey\" | \"queryFn\">,",
98                        op.name
99                    ));
100                    lines.push(") => {".to_string());
101                    lines.push("  const client = useODKClient();".to_string());
102                    lines.push("  return useQuery({".to_string());
103                    lines.push(format!("    queryKey: [\"{}\", variables],", op.name));
104                    lines.push(format!(
105                        "    queryFn: ({{ signal }}) => client.{}(variables, {{ signal }}),",
106                        method_name
107                    ));
108                    lines.push("    ...options,".to_string());
109                    lines.push("  });".to_string());
110                    lines.push("};".to_string());
111                }
112            }
113            OperationKind::Mutation => {
114                if op.variables.is_empty() {
115                    lines.push(format!("export const {} = (", hook_name));
116                    lines.push(format!(
117                        "  options?: UseMutationOptions<{}Result, Error>,",
118                        op.name
119                    ));
120                    lines.push(") => {".to_string());
121                    lines.push("  const client = useODKClient();".to_string());
122                    lines.push("  return useMutation({".to_string());
123                    lines.push(format!("    mutationFn: () => client.{}(),", method_name));
124                    lines.push("    ...options,".to_string());
125                    lines.push("  });".to_string());
126                    lines.push("};".to_string());
127                } else {
128                    lines.push(format!("export const {} = (", hook_name));
129                    lines.push(format!(
130                        "  options?: UseMutationOptions<{}Result, Error, {}Variables>,",
131                        op.name, op.name
132                    ));
133                    lines.push(") => {".to_string());
134                    lines.push("  const client = useODKClient();".to_string());
135                    lines.push("  return useMutation({".to_string());
136                    lines.push(format!(
137                        "    mutationFn: (variables: {}Variables) => client.{}(variables),",
138                        op.name, method_name
139                    ));
140                    lines.push("    ...options,".to_string());
141                    lines.push("  });".to_string());
142                    lines.push("};".to_string());
143                }
144            }
145            // Subscriptions deferred — needs transport config
146            _ => {}
147        }
148
149        lines.push(String::new());
150    }
151
152    lines.join("\n")
153}
154
155fn generate_provider() -> String {
156    let mut lines = Vec::new();
157
158    lines.push("import { createContext, useContext } from \"react\";".to_string());
159    lines.push("import type { Client } from \"./client\";".to_string());
160    lines.push(String::new());
161    lines.push("const ODKContext = createContext<Client | null>(null);".to_string());
162    lines.push(String::new());
163    lines.push("export const useODKClient = (): Client => {".to_string());
164    lines.push("  const client = useContext(ODKContext);".to_string());
165    lines.push("  if (!client) {".to_string());
166    lines.push(
167        "    throw new Error(\"useODKClient must be used within an ODKProvider\");".to_string(),
168    );
169    lines.push("  }".to_string());
170    lines.push("  return client;".to_string());
171    lines.push("};".to_string());
172    lines.push(String::new());
173    lines.push("export const ODKProvider = ({".to_string());
174    lines.push("  client,".to_string());
175    lines.push("  children,".to_string());
176    lines.push("}: {".to_string());
177    lines.push("  client: Client;".to_string());
178    lines.push("  children: React.ReactNode;".to_string());
179    lines.push("}) => (".to_string());
180    lines
181        .push("  <ODKContext.Provider value={client}>{children}</ODKContext.Provider>".to_string());
182    lines.push(");".to_string());
183
184    lines.join("\n")
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use odk_schema::*;
191
192    fn test_schema() -> CompiledSchema {
193        let mut schema = CompiledSchema::new("TestAPI");
194
195        schema.add_operation(CompiledOperation {
196            name: "GetUser".into(),
197            kind: OperationKind::Query,
198            input: None,
199            output: CompiledType::Ref {
200                name: "User".into(),
201            },
202            variables: vec![Variable {
203                name: "id".into(),
204                variable_type: CompiledType::Scalar {
205                    name: ScalarType::String,
206                },
207                required: true,
208                default_value: None,
209                description: None,
210            }],
211            selection: Some(SelectionSet {
212                fields: vec![FieldSelection {
213                    name: "id".into(),
214                    alias: None,
215                    arguments: vec![],
216                    selection: None,
217                    directives: vec![],
218                }],
219                fragment_spreads: vec![],
220                inline_fragments: vec![],
221            }),
222            description: None,
223            extensions: Extensions::default(),
224            directives: vec![],
225        });
226
227        schema.add_operation(CompiledOperation {
228            name: "CreatePost".into(),
229            kind: OperationKind::Mutation,
230            input: None,
231            output: CompiledType::Ref {
232                name: "Post".into(),
233            },
234            variables: vec![Variable {
235                name: "input".into(),
236                variable_type: CompiledType::Ref {
237                    name: "CreatePostInput".into(),
238                },
239                required: true,
240                default_value: None,
241                description: None,
242            }],
243            selection: Some(SelectionSet {
244                fields: vec![FieldSelection {
245                    name: "id".into(),
246                    alias: None,
247                    arguments: vec![],
248                    selection: None,
249                    directives: vec![],
250                }],
251                fragment_spreads: vec![],
252                inline_fragments: vec![],
253            }),
254            description: None,
255            extensions: Extensions::default(),
256            directives: vec![],
257        });
258
259        schema
260    }
261
262    #[test]
263    fn test_generates_hooks_and_provider() {
264        let output = generate(&test_schema());
265        assert!(output.contains_key("hooks.ts"));
266        assert!(output.contains_key("provider.tsx"));
267    }
268
269    #[test]
270    fn test_hooks_has_query_hook() {
271        let output = generate(&test_schema());
272        let hooks = &output["hooks.ts"];
273        assert!(hooks.contains("export const useGetUser"));
274        assert!(hooks.contains("useQuery({"));
275        assert!(hooks.contains("queryKey: [\"GetUser\", variables]"));
276    }
277
278    #[test]
279    fn test_hooks_has_mutation_hook() {
280        let output = generate(&test_schema());
281        let hooks = &output["hooks.ts"];
282        assert!(hooks.contains("export const useCreatePost"));
283        assert!(hooks.contains("useMutation({"));
284    }
285
286    #[test]
287    fn test_hooks_imports_from_client() {
288        let output = generate(&test_schema());
289        let hooks = &output["hooks.ts"];
290        assert!(hooks.contains("from \"./client\""));
291        assert!(hooks.contains("GetUserDocument"));
292        assert!(hooks.contains("type GetUserResult"));
293    }
294
295    #[test]
296    fn test_provider_has_context() {
297        let output = generate(&test_schema());
298        let provider = &output["provider.tsx"];
299        assert!(provider.contains("ODKContext"));
300        assert!(provider.contains("useODKClient"));
301        assert!(provider.contains("ODKProvider"));
302    }
303}