che-rest 0.3.0

Typed REST framework and project tooling for che-orm applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use std::{collections::BTreeSet, fs, path::Path};

use crate::module::ApiEndpoint;

const HEADER: &str = "// This file is generated by che-rest. Do not edit manually.\n// Run the appropriate che-rest management generator to update it.\n\n";

pub fn generate(
    out: &Path,
    endpoints: &[ApiEndpoint],
    force: bool,
) -> Result<Vec<String>, std::io::Error> {
    // Auxiliary endpoints can expose the same model under a different resource.
    // The admin UI manages each model once, through its primary endpoint.
    let mut model_names = BTreeSet::new();
    let endpoints = endpoints
        .iter()
        .filter(|endpoint| model_names.insert(endpoint.model_name.as_str()))
        .cloned()
        .collect::<Vec<_>>();
    let admin_generated = out.join("src/admin/generated");
    let admin_dir = out.join("src/admin");
    fs::create_dir_all(&admin_generated)?;
    fs::create_dir_all(&admin_dir)?;
    let schema_path = admin_generated.join("adminSchema.ts");
    let routes_path = admin_generated.join("adminRoutes.ts");
    fs::write(&schema_path, admin_schema(&endpoints))?;
    fs::write(&routes_path, admin_routes(&endpoints))?;
    fs::write(
        admin_dir.join("adminSchema.ts"),
        format!("{HEADER}export * from \"./generated/adminSchema\";\n"),
    )?;
    for (relative, contents) in static_files(&endpoints) {
        let path = out.join(relative);
        if force || !path.exists() {
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(path, contents)?;
        }
    }
    Ok(vec![
        "src/admin/generated/adminSchema.ts".into(),
        "src/admin/generated/adminRoutes.ts".into(),
        "src/admin/adminSchema.ts".into(),
    ])
}

fn admin_schema(endpoints: &[ApiEndpoint]) -> String {
    let mut out = HEADER.to_owned();
    out.push_str("import {\n");
    let mut apps = Vec::new();
    for endpoint in endpoints {
        out.push_str(&format!("  {}Api,\n", api_name(endpoint, endpoints)));
    }
    out.push_str("} from \"../../generated/api\";\n\n");
    out.push_str("export type AdminFieldType = \"integer\" | \"text\" | \"boolean\" | \"real\" | \"datetime\" | \"image\";\n\n");
    out.push_str(
        "export interface AdminField { name: string; source: string; type: AdminFieldType; label: string; readOnly: boolean; writeOnly: boolean; required: boolean; nullable: boolean; hasDefault: boolean; choices?: string[]; relatedModel?: string; relationField?: string; }\n\nexport interface AdminFilter { name: string; source: string; type: AdminFieldType; label: string; nullable: boolean; choices?: string[]; }\n\nexport interface AdminModelApi { list: (params?: any) => Promise<{ count: number; results: any[] }>; retrieve: (id: number) => Promise<any>; create: (payload: any) => Promise<any>; update: (id: number, payload: any) => Promise<any>; remove: (id: number) => Promise<void>; }\n\nexport interface AdminModel { appName: string; name: string; resource: string; api: AdminModelApi; fields: AdminField[]; listFields: string[]; filters: AdminFilter[]; }\nexport interface AdminApp { name: string; models: AdminModel[]; }\n\nexport const adminModels: AdminModel[] = [\n",
    );
    for endpoint in endpoints {
        out.push_str("  {\n");
        out.push_str(&format!(
            "    appName: {}, name: {}, resource: {}, api: {}Api,\n",
            js(endpoint.app_name),
            js(&endpoint.model_name),
            js(&endpoint.resource),
            api_name(endpoint, endpoints)
        ));
        out.push_str("    fields: [\n");
        for field in &endpoint.fields {
            let related = field.related_model.map(last_path_part);
            let source = field.source.to_owned();
            let ty = admin_type(field.rust_type, related.is_some());
            let nested_relation = related.is_some_and(|_| field.name != field.source);
            let read_only = field.read_only || nested_relation;
            let column = endpoint
                .columns
                .iter()
                .find(|column| column.name == source || column.field_name == source);
            let nullable = column.is_some_and(|column| column.nullable);
            let has_default = column.is_some_and(|column| column.has_default);
            let choices = column
                .and_then(|column| column.choices.as_ref())
                .map(|choices| format!(", choices: {}", serde_json::to_string(choices).unwrap()))
                .unwrap_or_default();
            let related_model = related
                .map(|value| format!(", relatedModel: {}", js(value)))
                .unwrap_or_default();
            let relation_field = if nested_relation {
                format!(", relationField: {}", js(field.name))
            } else {
                String::new()
            };
            out.push_str(&format!("      {{ name: {}, source: {}, type: {}, label: {}, readOnly: {}, writeOnly: {}, required: {}, nullable: {}, hasDefault: {}{}{}{} }},\n", js(field.name), js(&source), js(ty), js(&label(field.name)), read_only, field.write_only, !read_only && !field.write_only && !nullable && !has_default, nullable, has_default, choices, related_model, relation_field));
        }
        out.push_str("    ],\n    listFields: [");
        for field in &endpoint.list_fields {
            if !field.write_only {
                out.push_str(&format!("{}, ", js(field.name)));
            }
        }
        out.push_str("],\n    filters: [\n");
        for filter in &endpoint.filters {
            let suffix = match filter.lookup {
                crate::Lookup::Exact => "",
                crate::Lookup::Contains => "__contains",
                crate::Lookup::Gt => "__gt",
                crate::Lookup::Gte => "__gte",
                crate::Lookup::Lt => "__lt",
                crate::Lookup::Lte => "__lte",
            };
            let name = format!("{}{}", filter.name, suffix);
            let choices = endpoint
                .columns
                .iter()
                .find(|column| column.name == filter.source)
                .and_then(|column| column.choices.as_ref())
                .map(|choices| format!(", choices: {}", serde_json::to_string(choices).unwrap()))
                .unwrap_or_default();
            out.push_str(&format!(
                "      {{ name: {}, source: {}, type: {}, label: {}, nullable: false{} }},\n",
                js(&name),
                js(filter.source),
                js(filter_type(filter.source)),
                js(&label(&name)),
                choices
            ));
        }
        out.push_str("    ],\n  },\n");
    }
    out.push_str("];\n\n");
    for endpoint in endpoints {
        out.push_str(&format!("export const {}AdminModel = adminModels.find((model) => model.appName === {} && model.resource === {}) as AdminModel;\n", api_name(endpoint, endpoints), js(endpoint.app_name), js(&endpoint.resource)));
    }
    out.push_str("\nexport const adminApps: AdminApp[] = [\n");
    for endpoint in endpoints {
        if apps.contains(&endpoint.app_name) {
            continue;
        }
        apps.push(endpoint.app_name);
        out.push_str(&format!(
            "  {{ name: {}, models: adminModels.filter((model) => model.appName === {}) }},\n",
            js(endpoint.app_name),
            js(endpoint.app_name)
        ));
    }
    out.push_str("];\n");
    out
}

fn static_files(endpoints: &[ApiEndpoint]) -> Vec<(String, String)> {
    let mut files = vec![
        ("package.json".into(), r#"{"name":"che-rest-admin","private":true,"version":"0.1.0","type":"module","scripts":{"build":"vue-tsc --noEmit && vite build","dev":"vite"},"dependencies":{"@vitejs/plugin-vue":"^5.2.1","axios":"^1.20.0","typescript":"^5.7.2","vite":"^6.0.3","vue":"^3.5.44","vue-router":"^4.5.0","vue-tsc":"^2.1.10"}}"#.into()),
        ("index.html".into(), "<!doctype html><html><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><title>che-rest admin</title></head><body><div id=\"app\"></div><script type=\"module\" src=\"/src/main.ts\"></script></body></html>".into()),
        ("vite.config.ts".into(), "import vue from \"@vitejs/plugin-vue\";\nimport { defineConfig } from \"vite\";\nexport default defineConfig({ plugins: [vue()] });\n".into()),
        ("tsconfig.json".into(), r#"{"compilerOptions":{"target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"],"skipLibCheck":true,"moduleResolution":"Bundler","allowImportingTsExtensions":true,"resolveJsonModule":true,"isolatedModules":true,"noEmit":true,"jsx":"preserve","strict":true,"types":["vite/client"]},"include":["src/**/*.ts","src/**/*.vue"]}"#.into()),
        ("src/main.ts".into(), "import { createApp } from \"vue\";\nimport App from \"./App.vue\";\nimport router from \"./router\";\ncreateApp(App).use(router).mount(\"#app\");\n".into()),
        ("src/App.vue".into(), "<script setup lang=\"ts\">\nimport { RouterView } from \"vue-router\";\n</script>\n<template><RouterView /></template>\n".into()),
        ("src/router.ts".into(), "import { createRouter, createWebHistory } from \"vue-router\";\nimport { adminRoutes } from \"./admin/generated/adminRoutes\";\nexport default createRouter({ history: createWebHistory(), routes: adminRoutes });\n".to_string()),
        ("src/admin/AdminModelList.vue".into(), "<template><main><h1>Models</h1><RouterLink v-for=\"model in adminModels\" :key=\"model.resource\" :to=\"`/${model.resource}`\">{{ model.name }}</RouterLink></main></template>\n<script setup lang=\"ts\">\nimport { adminModels } from \"./generated/adminSchema\";\n</script>\n".into()),
        ("src/admin/components/GenericModelTable.vue".into(), "<script setup lang=\"ts\">\nimport { onMounted, ref } from \"vue\";\nconst props = defineProps<{ model: any }>(); const rows = ref<any[]>([]);\nonMounted(async () => { rows.value = (await props.model.api.list({ limit: 50 })).results; });\n</script>\n<template><main><h1>{{ model.name }}</h1><table><tr v-for=\"row in rows\" :key=\"row.id\"><td v-for=\"field in model.fields.filter((item: any) => !item.writeOnly)\" :key=\"field.name\">{{ row[field.name] }}</td></tr></table></main></template>\n".into()),
        ("src/admin/components/GenericModelForm.vue".into(), "<script setup lang=\"ts\">\nconst props = defineProps<{ model: any }>();\n</script>\n<template><main><h1>{{ model.name }}</h1><p>Use the generated API to edit this model.</p></main></template>\n".into()),
    ];
    files.clear();
    files.extend([
        (
            "package.json".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/package.json"
            ))
            .into(),
        ),
        (
            "index.html".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/index.html"
            ))
            .into(),
        ),
        (
            "vite.config.ts".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/vite.config.ts"
            ))
            .into(),
        ),
        (
            "tsconfig.json".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/tsconfig.json"
            ))
            .into(),
        ),
        (
            "src/main.ts".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/main.ts"
            ))
            .into(),
        ),
        (
            "src/App.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/App.vue"
            ))
            .into(),
        ),
        (
            "src/router.ts".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/router.ts"
            ))
            .into(),
        ),
        (
            "src/admin/AdminApp.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/AdminApp.vue"
            ))
            .into(),
        ),
        (
            "src/admin/AdminLogin.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/AdminLogin.vue"
            ))
            .into(),
        ),
        (
            "src/admin/AdminModelList.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/AdminModelList.vue"
            ))
            .into(),
        ),
        (
            "src/admin/AdminModelForm.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/AdminModelForm.vue"
            ))
            .into(),
        ),
        (
            "src/admin/AdminModelTable.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/AdminModelTable.vue"
            ))
            .into(),
        ),
        (
            "src/admin/admin.css".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/admin.css"
            ))
            .into(),
        ),
        (
            "src/admin/styles/tokens.css".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/styles/tokens.css"
            ))
            .into(),
        ),
        (
            "src/admin/styles/base.css".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/styles/base.css"
            ))
            .into(),
        ),
        (
            "src/admin/styles/components.css".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/styles/components.css"
            ))
            .into(),
        ),
        (
            "src/admin/components/GenericModelTable.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/components/GenericModelTable.vue"
            ))
            .into(),
        ),
        (
            "src/admin/components/GenericModelForm.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/components/GenericModelForm.vue"
            ))
            .into(),
        ),
        (
            "src/admin/components/AsyncRelationSelect.vue".into(),
            include_str!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/src/admin/templates/components/AsyncRelationSelect.vue"
            ))
            .into(),
        ),
    ]);
    for endpoint in endpoints {
        let page = page_name(endpoint, endpoints);
        let api = api_name(endpoint, endpoints);
        files.push((format!("src/admin/pages/{page}List.vue"), format!("<script setup lang=\"ts\">import {{ {api}AdminModel }} from \"../generated/adminSchema\"; import GenericModelTable from \"../components/GenericModelTable.vue\";</script><template><GenericModelTable :model=\"{api}AdminModel\" /></template>\n")));
        files.push((format!("src/admin/pages/{page}Form.vue"), format!("<script setup lang=\"ts\">import {{ {api}AdminModel }} from \"../generated/adminSchema\"; import GenericModelForm from \"../components/GenericModelForm.vue\";</script><template><GenericModelForm :model=\"{api}AdminModel\" /></template>\n")));
    }
    files
}

fn admin_routes(endpoints: &[ApiEndpoint]) -> String {
    let mut out = HEADER.to_owned();
    out.push_str("import type { RouteRecordRaw } from \"vue-router\";\nimport AdminModelList from \"../AdminModelList.vue\";\n");
    for endpoint in endpoints {
        let page = page_name(endpoint, endpoints);
        out.push_str(&format!("import {page}List from \"../pages/{page}List.vue\";\nimport {page}Form from \"../pages/{page}Form.vue\";\n"));
    }
    out.push_str("\nexport const adminRoutes: RouteRecordRaw[] = [\n  { path: \"\", component: AdminModelList },\n");
    for endpoint in endpoints {
        let page = page_name(endpoint, endpoints);
        out.push_str(&format!("  {{ path: {}, component: {page}List }},\n  {{ path: {}, component: {page}Form }},\n  {{ path: {}, component: {page}Form }},\n", js(&endpoint.resource), js(&format!("{}/new", endpoint.resource)), js(&format!("{}/:id/edit", endpoint.resource))));
    }
    out.push_str("];\n");
    out
}

fn admin_type(rust_type: &str, relation: bool) -> &'static str {
    if rust_type.contains("ImageField") {
        "image"
    } else if rust_type.contains("f64") {
        "real"
    } else if relation || rust_type.contains("i64") {
        "integer"
    } else if rust_type == "bool" {
        "boolean"
    } else if rust_type.contains("OffsetDateTime") {
        "datetime"
    } else {
        "text"
    }
}
fn last_path_part(value: &str) -> &str {
    value.rsplit("::").next().unwrap_or(value).trim()
}
fn lower_first(value: &str) -> String {
    let mut chars = value.chars();
    chars
        .next()
        .map(|c| c.to_ascii_lowercase())
        .into_iter()
        .chain(chars)
        .collect()
}
fn api_name(endpoint: &ApiEndpoint, endpoints: &[ApiEndpoint]) -> String {
    if endpoints
        .iter()
        .filter(|item| item.model_name == endpoint.model_name)
        .count()
        == 1
    {
        return lower_first(&endpoint.model_name);
    }
    endpoint
        .resource
        .split('/')
        .next_back()
        .unwrap_or(&endpoint.resource)
        .trim_end_matches('s')
        .split('-')
        .enumerate()
        .map(|(index, part)| {
            if index == 0 {
                part.to_owned()
            } else {
                let mut chars = part.chars();
                chars
                    .next()
                    .map(|first| first.to_ascii_uppercase())
                    .into_iter()
                    .chain(chars)
                    .collect()
            }
        })
        .collect()
}
fn page_name(endpoint: &ApiEndpoint, endpoints: &[ApiEndpoint]) -> String {
    if endpoints
        .iter()
        .filter(|item| item.model_name == endpoint.model_name)
        .count()
        == 1
    {
        endpoint.model_name.clone()
    } else {
        endpoint
            .resource
            .split('/')
            .next_back()
            .unwrap_or(&endpoint.resource)
            .trim_end_matches('s')
            .split('-')
            .map(|part| {
                let mut chars = part.chars();
                chars
                    .next()
                    .map(|first| first.to_ascii_uppercase())
                    .into_iter()
                    .chain(chars)
                    .collect::<String>()
            })
            .collect()
    }
}
fn label(value: &str) -> String {
    value
        .replace("__", "_")
        .split('_')
        .map(|part| {
            let mut chars = part.chars();
            chars
                .next()
                .map(|c| c.to_ascii_uppercase().to_string() + chars.as_str())
                .unwrap_or_default()
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn filter_type(value: &str) -> &'static str {
    if value == "id" || value.ends_with("_id") {
        "integer"
    } else if value.ends_with("_at") {
        "datetime"
    } else {
        "text"
    }
}
fn js(value: &str) -> String {
    serde_json::to_string(value).expect("serializing string cannot fail")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn endpoint(app_name: &'static str, model_name: &str) -> ApiEndpoint {
        ApiEndpoint {
            app_name,
            model_name: model_name.into(),
            resource: model_name.to_ascii_lowercase(),
            fields: Vec::new(),
            list_fields: Vec::new(),
            columns: Vec::new(),
            filters: Vec::new(),
            extensions: Vec::new(),
        }
    }

    #[test]
    fn groups_multiple_models_under_one_app() {
        let output = admin_schema(&[endpoint("tasks", "Task"), endpoint("tasks", "Note")]);
        assert_eq!(output.matches("name: \"tasks\"").count(), 1);
        assert!(output.contains("taskAdminModel"));
        assert!(output.contains("noteAdminModel"));
    }

    #[test]
    fn creates_static_project_files() {
        let files = static_files(&[endpoint("tasks", "Task")]);
        assert!(files.iter().any(|(path, _)| path == "package.json"));
        assert!(files.iter().any(|(path, _)| path == "tsconfig.json"));
        assert!(
            files
                .iter()
                .any(|(path, _)| path == "src/admin/pages/TaskList.vue")
        );
    }

    #[test]
    fn preserves_static_files_without_force() {
        let root = std::env::temp_dir().join(format!("che_rest_admin_test_{}", std::process::id()));
        let package = root.join("package.json");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(&package, "custom").unwrap();
        generate(&root, &[endpoint("tasks", "Task")], false).unwrap();
        assert_eq!(std::fs::read_to_string(&package).unwrap(), "custom");
        generate(&root, &[endpoint("tasks", "Task")], true).unwrap();
        assert_ne!(std::fs::read_to_string(&package).unwrap(), "custom");
        let _ = std::fs::remove_dir_all(root);
    }
}