Skip to main content

odk_cli/generate/
sdk.rs

1//! SDK target — vanilla typed GraphQL client.
2//!
3//! Generates `client.ts` containing:
4//! - gql.tada operation documents (type-inferred)
5//! - Re-exported result/variable types
6//! - Typed client factory with named methods
7
8use odk_schema::CompiledSchema;
9use std::collections::BTreeMap;
10
11use super::util;
12
13/// Generate the SDK client.
14pub fn generate(schema: &CompiledSchema) -> BTreeMap<String, String> {
15    let mut output = BTreeMap::new();
16
17    if schema.operations.is_empty() {
18        return output;
19    }
20
21    let content = generate_client(schema);
22    output.insert("client.ts".to_string(), content);
23    output
24}
25
26fn generate_client(schema: &CompiledSchema) -> String {
27    let mut lines = Vec::new();
28
29    // Imports
30    lines
31        .push("import { graphql, type ResultOf, type VariablesOf } from \"gql.tada\";".to_string());
32    lines.push("import { GraphQLClient } from \"graphql-request\";".to_string());
33    lines.push(String::new());
34
35    // Operation documents
36    for op in &schema.operations {
37        let doc_text = util::reconstruct_operation(
38            &op.name,
39            &op.kind,
40            &op.variables,
41            &op.selection,
42            &schema.fragments,
43        );
44
45        lines.push(format!("export const {}Document = graphql(`", op.name));
46        for doc_line in doc_text.lines() {
47            lines.push(format!("  {}", doc_line));
48        }
49        lines.push("`);".to_string());
50        lines.push(String::new());
51    }
52
53    // Type re-exports
54    for op in &schema.operations {
55        lines.push(format!(
56            "export type {}Result = ResultOf<typeof {}Document>;",
57            op.name, op.name
58        ));
59        if !op.variables.is_empty() {
60            lines.push(format!(
61                "export type {}Variables = VariablesOf<typeof {}Document>;",
62                op.name, op.name
63            ));
64        }
65    }
66    lines.push(String::new());
67
68    // Client factory
69    lines.push("export const createClient = (url: string, options?: RequestInit) => {".to_string());
70    lines.push("  const gql = new GraphQLClient(url, options);".to_string());
71    lines.push("  return {".to_string());
72
73    for op in &schema.operations {
74        let method = util::to_method_name(&op.name);
75        if op.variables.is_empty() {
76            lines.push(format!(
77                "    {}: () => gql.request({}Document),",
78                method, op.name
79            ));
80        } else {
81            lines.push(format!(
82                "    {}: (variables: {}Variables) => gql.request({}Document, variables),",
83                method, op.name, op.name
84            ));
85        }
86    }
87
88    lines.push("  };".to_string());
89    lines.push("};".to_string());
90    lines.push(String::new());
91
92    // Export client type
93    lines.push("export type Client = ReturnType<typeof createClient>;".to_string());
94
95    lines.join("\n")
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use odk_schema::*;
102
103    fn test_schema() -> CompiledSchema {
104        let mut schema = CompiledSchema::new("TestAPI");
105
106        schema.add_operation(CompiledOperation {
107            name: "GetUser".into(),
108            kind: OperationKind::Query,
109            input: None,
110            output: CompiledType::Ref {
111                name: "User".into(),
112            },
113            variables: vec![Variable {
114                name: "id".into(),
115                variable_type: CompiledType::Scalar {
116                    name: ScalarType::String,
117                },
118                required: true,
119                default_value: None,
120                description: None,
121            }],
122            selection: Some(SelectionSet {
123                fields: vec![
124                    FieldSelection {
125                        name: "id".into(),
126                        alias: None,
127                        arguments: vec![],
128                        selection: None,
129                        directives: vec![],
130                    },
131                    FieldSelection {
132                        name: "name".into(),
133                        alias: None,
134                        arguments: vec![],
135                        selection: None,
136                        directives: vec![],
137                    },
138                ],
139                fragment_spreads: vec![],
140                inline_fragments: vec![],
141            }),
142            description: None,
143            extensions: Extensions::default(),
144            directives: vec![],
145        });
146
147        schema.add_operation(CompiledOperation {
148            name: "CreatePost".into(),
149            kind: OperationKind::Mutation,
150            input: None,
151            output: CompiledType::Ref {
152                name: "Post".into(),
153            },
154            variables: vec![Variable {
155                name: "input".into(),
156                variable_type: CompiledType::Ref {
157                    name: "CreatePostInput".into(),
158                },
159                required: true,
160                default_value: None,
161                description: None,
162            }],
163            selection: Some(SelectionSet {
164                fields: vec![
165                    FieldSelection {
166                        name: "id".into(),
167                        alias: None,
168                        arguments: vec![],
169                        selection: None,
170                        directives: vec![],
171                    },
172                    FieldSelection {
173                        name: "title".into(),
174                        alias: None,
175                        arguments: vec![],
176                        selection: None,
177                        directives: vec![],
178                    },
179                ],
180                fragment_spreads: vec![],
181                inline_fragments: vec![],
182            }),
183            description: None,
184            extensions: Extensions::default(),
185            directives: vec![],
186        });
187
188        schema
189    }
190
191    #[test]
192    fn test_generates_client_file() {
193        let schema = test_schema();
194        let output = generate(&schema);
195        assert!(output.contains_key("client.ts"));
196    }
197
198    #[test]
199    fn test_client_has_imports() {
200        let schema = test_schema();
201        let output = generate(&schema);
202        let client = &output["client.ts"];
203        assert!(
204            client
205                .contains("import { graphql, type ResultOf, type VariablesOf } from \"gql.tada\"")
206        );
207        assert!(client.contains("import { GraphQLClient } from \"graphql-request\""));
208    }
209
210    #[test]
211    fn test_client_has_operation_documents() {
212        let schema = test_schema();
213        let output = generate(&schema);
214        let client = &output["client.ts"];
215        assert!(client.contains("export const GetUserDocument = graphql(`"));
216        assert!(client.contains("export const CreatePostDocument = graphql(`"));
217        assert!(client.contains("query GetUser($id: String!)"));
218        assert!(client.contains("mutation CreatePost($input: CreatePostInput!)"));
219    }
220
221    #[test]
222    fn test_client_has_type_exports() {
223        let schema = test_schema();
224        let output = generate(&schema);
225        let client = &output["client.ts"];
226        assert!(client.contains("export type GetUserResult = ResultOf<typeof GetUserDocument>"));
227        assert!(
228            client.contains("export type GetUserVariables = VariablesOf<typeof GetUserDocument>")
229        );
230        assert!(
231            client.contains("export type CreatePostResult = ResultOf<typeof CreatePostDocument>")
232        );
233    }
234
235    #[test]
236    fn test_client_has_factory_methods() {
237        let schema = test_schema();
238        let output = generate(&schema);
239        let client = &output["client.ts"];
240        assert!(client.contains("getUser: (variables: GetUserVariables)"));
241        assert!(client.contains("createPost: (variables: CreatePostVariables)"));
242    }
243
244    #[test]
245    fn test_empty_operations_no_output() {
246        let schema = CompiledSchema::new("Empty");
247        let output = generate(&schema);
248        assert!(output.is_empty());
249    }
250}