Skip to main content

odk_cli/generate/
msw.rs

1//! MSW target — mock handlers and data factories.
2//!
3//! Generates `mocks.ts` containing:
4//! - Per-operation MSW handler factories
5//! - Mock data factories with sensible defaults
6//! - Error mock helpers
7//! - `allHandlers` convenience export
8
9use odk_schema::{CompiledSchema, OperationKind};
10use std::collections::BTreeMap;
11
12use super::util;
13
14/// Generate MSW mock handlers.
15pub fn generate(schema: &CompiledSchema) -> BTreeMap<String, String> {
16    let mut output = BTreeMap::new();
17
18    if schema.operations.is_empty() {
19        return output;
20    }
21
22    output.insert("mocks.ts".to_string(), generate_mocks(schema));
23    output
24}
25
26fn generate_mocks(schema: &CompiledSchema) -> String {
27    let mut lines = Vec::new();
28
29    // Imports
30    lines.push("import { graphql, HttpResponse } from \"msw\";".to_string());
31
32    // Import result types from client
33    let type_imports: Vec<String> = schema
34        .operations
35        .iter()
36        .map(|op| format!("type {}Result", op.name))
37        .collect();
38    lines.push(format!(
39        "import {{ {} }} from \"./client\";",
40        type_imports.join(", ")
41    ));
42    lines.push(String::new());
43
44    // Handler factories, mock data, and error helpers per operation
45    for op in &schema.operations {
46        let mock_name = util::to_mock_name(&op.name);
47        let mock_data_name = util::to_mock_data_name(&op.name);
48        let mock_error_name = util::to_mock_error_name(&op.name);
49
50        let gql_method = match op.kind {
51            OperationKind::Query => "query",
52            OperationKind::Mutation => "mutation",
53            _ => "query",
54        };
55
56        // Determine the root field name (first field in selection set)
57        let root_field = op
58            .selection
59            .as_ref()
60            .and_then(|s| s.fields.first())
61            .map(|f| f.name.as_str())
62            .unwrap_or("data");
63
64        // Handler factory
65        lines.push(format!(
66            "export const {} = (resolver?: () => {}Result[\"{}\"],) =>",
67            mock_name, op.name, root_field
68        ));
69        lines.push(format!("  graphql.{}(\"{}\", () =>", gql_method, op.name));
70        lines.push("    HttpResponse.json({".to_string());
71        lines.push(format!(
72            "      data: {{ {}: resolver?.() ?? {}() }},",
73            root_field, mock_data_name
74        ));
75        lines.push("    }),".to_string());
76        lines.push("  );".to_string());
77        lines.push(String::new());
78
79        // Mock data factory
80        lines.push(format!("export const {} = (", mock_data_name));
81        lines.push(format!(
82            "  overrides?: Partial<{}Result[\"{}\"]>,",
83            op.name, root_field
84        ));
85        lines.push(format!("): {}Result[\"{}\"] => ({{", op.name, root_field));
86
87        // Generate default values from the selection set
88        if let Some(sel) = &op.selection {
89            if let Some(root) = sel.fields.first() {
90                if let Some(nested) = &root.selection {
91                    for field in &nested.fields {
92                        let default = guess_mock_default(&field.name, field.selection.is_some());
93                        lines.push(format!("  {}: {},", field.name, default));
94                    }
95                }
96            }
97        }
98
99        lines.push("  ...overrides,".to_string());
100        lines.push("});".to_string());
101        lines.push(String::new());
102
103        // Error helper
104        lines.push(format!(
105            "export const {} = (message = \"An error occurred\") =>",
106            mock_error_name
107        ));
108        lines.push(format!("  graphql.{}(\"{}\", () =>", gql_method, op.name));
109        lines.push("    HttpResponse.json({".to_string());
110        lines.push("      errors: [{ message }],".to_string());
111        lines.push("    }),".to_string());
112        lines.push("  );".to_string());
113        lines.push(String::new());
114    }
115
116    // allHandlers convenience export
117    let handler_calls: Vec<String> = schema
118        .operations
119        .iter()
120        .map(|op| format!("{}()", util::to_mock_name(&op.name)))
121        .collect();
122    lines.push(format!(
123        "export const allHandlers = [{}];",
124        handler_calls.join(", ")
125    ));
126
127    lines.join("\n")
128}
129
130/// Guess a sensible mock default value for a field based on its name.
131fn guess_mock_default(name: &str, has_children: bool) -> &'static str {
132    if has_children {
133        return "[]";
134    }
135    match name {
136        "id" => "\"mock-id\"",
137        "name" | "title" | "label" => "\"Mock Value\"",
138        "email" => "\"mock@example.com\"",
139        "url" | "href" | "link" => "\"https://example.com\"",
140        "description" | "bio" | "body" | "content" => "\"Mock text\"",
141        "createdAt" | "updatedAt" | "publishedAt" => "\"2024-01-01T00:00:00Z\"",
142        "count" | "total" | "amount" | "price" | "quantity" | "size" | "length" | "age"
143        | "width" | "height" | "weight" | "offset" | "limit" | "page" | "index" => "0",
144        _ if name.ends_with("Count") || name.ends_with("Total") || name.ends_with("Amount") => "0",
145        _ if name.ends_with("At") => "\"2024-01-01T00:00:00Z\"",
146        _ if name.ends_with("Id") => "\"mock-id\"",
147        _ if name.ends_with("Url") || name.ends_with("URI") => "\"https://example.com\"",
148        _ if name.ends_with("Name") => "\"Mock Value\"",
149        _ if name.ends_with("Email") => "\"mock@example.com\"",
150        "active" | "enabled" | "published" | "verified" => "false",
151        "slug" => "\"mock-slug\"",
152        "avatar" | "image" | "thumbnail" => "\"https://example.com/image.png\"",
153        _ => "\"\"",
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use odk_schema::*;
161
162    fn test_schema() -> CompiledSchema {
163        let mut schema = CompiledSchema::new("TestAPI");
164
165        schema.add_operation(CompiledOperation {
166            name: "GetUser".into(),
167            kind: OperationKind::Query,
168            input: None,
169            output: CompiledType::Ref {
170                name: "User".into(),
171            },
172            variables: vec![Variable {
173                name: "id".into(),
174                variable_type: CompiledType::Scalar {
175                    name: ScalarType::String,
176                },
177                required: true,
178                default_value: None,
179                description: None,
180            }],
181            selection: Some(SelectionSet {
182                fields: vec![FieldSelection {
183                    name: "user".into(),
184                    alias: None,
185                    arguments: vec![],
186                    selection: Some(SelectionSet {
187                        fields: vec![
188                            FieldSelection {
189                                name: "id".into(),
190                                alias: None,
191                                arguments: vec![],
192                                selection: None,
193                                directives: vec![],
194                            },
195                            FieldSelection {
196                                name: "name".into(),
197                                alias: None,
198                                arguments: vec![],
199                                selection: None,
200                                directives: vec![],
201                            },
202                            FieldSelection {
203                                name: "email".into(),
204                                alias: None,
205                                arguments: vec![],
206                                selection: None,
207                                directives: vec![],
208                            },
209                        ],
210                        fragment_spreads: vec![],
211                        inline_fragments: vec![],
212                    }),
213                    directives: vec![],
214                }],
215                fragment_spreads: vec![],
216                inline_fragments: vec![],
217            }),
218            description: None,
219            extensions: Extensions::default(),
220            directives: vec![],
221        });
222
223        schema
224    }
225
226    #[test]
227    fn test_generates_mocks_file() {
228        let output = generate(&test_schema());
229        assert!(output.contains_key("mocks.ts"));
230    }
231
232    #[test]
233    fn test_mocks_has_handler() {
234        let output = generate(&test_schema());
235        let mocks = &output["mocks.ts"];
236        assert!(mocks.contains("export const mockGetUser"));
237        assert!(mocks.contains("graphql.query(\"GetUser\""));
238    }
239
240    #[test]
241    fn test_mocks_has_data_factory() {
242        let output = generate(&test_schema());
243        let mocks = &output["mocks.ts"];
244        assert!(mocks.contains("export const mockGetUserData"));
245        assert!(mocks.contains("id: \"mock-id\""));
246        assert!(mocks.contains("name: \"Mock Value\""));
247        assert!(mocks.contains("email: \"mock@example.com\""));
248        assert!(mocks.contains("...overrides"));
249    }
250
251    #[test]
252    fn test_mocks_has_error_helper() {
253        let output = generate(&test_schema());
254        let mocks = &output["mocks.ts"];
255        assert!(mocks.contains("export const mockGetUserError"));
256        assert!(mocks.contains("errors: [{ message }]"));
257    }
258
259    #[test]
260    fn test_mocks_has_all_handlers() {
261        let output = generate(&test_schema());
262        let mocks = &output["mocks.ts"];
263        assert!(mocks.contains("export const allHandlers"));
264        assert!(mocks.contains("mockGetUser()"));
265    }
266}