1use std::sync::OnceLock;
29
30pub mod client_gen;
31
32use serde_json::{Map, Value, json};
33use umbral::migrate::{Column, ModelMeta};
34use umbral::orm::SqlType;
35use umbral::prelude::*;
36use umbral::web::{Html, IntoResponse, Json, Response, StatusCode, header};
37use umbral_casing::pascal_case_from_ident;
38
39const SWAGGER_UI_HTML: &str = include_str!("../templates/swagger_ui.html");
40
41#[derive(Debug, Clone)]
43pub struct OpenApiPlugin {
44 base_path: String,
45 title: String,
46 version: String,
47 description: Option<String>,
48 extra_exclude: Vec<String>,
49 allow_in_prod: bool,
55 swagger_asset_base: String,
63}
64
65pub const DEFAULT_SWAGGER_ASSET_BASE: &str = "https://unpkg.com/swagger-ui-dist@5.17.14";
69
70const SWAGGER_CSS_SRI: &str =
79 "sha384-wxLW6kwyHktdDGr6Pv1zgm/VGJh99lfUbzSn6HNHBENZlCN7W602k9VkGdxuFvPn";
80const SWAGGER_JS_SRI: &str =
81 "sha384-wmyclcVGX/WhUkdkATwhaK1X1JtiNrr2EoYJ+diV3vj4v6OC5yCeSu+yW13SYJep";
82
83impl Default for OpenApiPlugin {
84 fn default() -> Self {
85 Self::new()
86 }
87}
88
89impl OpenApiPlugin {
90 pub fn new() -> Self {
91 Self {
92 base_path: "/openapi".to_string(),
93 title: "umbral API".to_string(),
94 version: "0.0.1".to_string(),
95 description: None,
96 extra_exclude: Vec::new(),
97 allow_in_prod: false,
98 swagger_asset_base: DEFAULT_SWAGGER_ASSET_BASE.to_string(),
99 }
100 }
101
102 pub fn swagger_asset_base(mut self, base: impl Into<String>) -> Self {
107 self.swagger_asset_base = base.into();
108 self
109 }
110
111 pub fn allow_in_prod(mut self) -> Self {
115 self.allow_in_prod = true;
116 self
117 }
118
119 pub fn at(mut self, path: &str) -> Self {
123 let trimmed = path.trim_end_matches('/');
124 self.base_path = if trimmed.is_empty() {
125 "/".to_string()
126 } else {
127 trimmed.to_string()
128 };
129 self
130 }
131
132 pub fn title(mut self, s: impl Into<String>) -> Self {
134 self.title = s.into();
135 self
136 }
137
138 pub fn version(mut self, s: impl Into<String>) -> Self {
140 self.version = s.into();
141 self
142 }
143
144 pub fn description(mut self, s: impl Into<String>) -> Self {
150 self.description = Some(s.into());
151 self
152 }
153
154 pub fn exclude<I, S>(mut self, tables: I) -> Self
157 where
158 I: IntoIterator<Item = S>,
159 S: Into<String>,
160 {
161 for t in tables {
162 self.extra_exclude.push(t.into());
163 }
164 self
165 }
166
167 fn is_exposed(&self, table: &str) -> bool {
168 !self.extra_exclude.iter().any(|t| t == table)
174 }
175
176 fn spec_url(&self) -> String {
177 if self.base_path == "/" {
178 "/openapi.json".to_string()
179 } else {
180 format!("{}/openapi.json", self.base_path)
181 }
182 }
183
184 fn ui_route(&self) -> String {
185 if self.base_path == "/" {
186 "/".to_string()
187 } else {
188 format!("{}/", self.base_path)
189 }
190 }
191}
192
193static CONFIG: OnceLock<OpenApiPlugin> = OnceLock::new();
197
198pub fn spec_url() -> Option<String> {
211 CONFIG.get().map(|cfg| cfg.spec_url())
212}
213
214impl Plugin for OpenApiPlugin {
215 fn name(&self) -> &'static str {
216 "openapi"
217 }
218
219 fn dependencies(&self) -> &'static [&'static str] {
220 &["rest"]
221 }
222
223 fn commands(&self) -> Vec<Box<dyn umbral::cli::PluginCommand>> {
224 vec![Box::new(GenClientCommand)]
225 }
226
227 fn routes(&self) -> Router {
228 let is_prod = matches!(
231 umbral::settings::get_opt().map(|s| &s.environment),
232 Some(umbral::Environment::Prod)
233 );
234 if is_prod && !self.allow_in_prod {
235 tracing::warn!(
236 "umbral-openapi: not mounting in Environment::Prod (the OpenAPI spec maps your \
237 entire API surface for unauthenticated callers). Call \
238 OpenApiPlugin::new().allow_in_prod() to override, ideally behind a firewall.",
239 );
240 return Router::new();
241 }
242 let _ = CONFIG.set(self.clone());
243 umbral::routes::init_openapi_spec_url(self.spec_url());
248 let mut router = Router::new()
249 .route(&self.spec_url(), get(spec_handler))
250 .route(&self.ui_route(), get(swagger_ui_handler));
251 if self.base_path != "/" {
259 router = router.route(&self.base_path, get(swagger_ui_handler));
260 }
261 router
262 }
263}
264
265async fn spec_handler() -> Response {
270 let cfg = CONFIG.get().expect("OpenApiPlugin::routes was called");
271 let spec = build_spec(cfg);
272 (
275 StatusCode::OK,
276 [(header::CONTENT_TYPE, "application/json")],
277 Json(spec),
278 )
279 .into_response()
280}
281
282async fn swagger_ui_handler() -> Response {
283 let cfg = CONFIG.get().expect("OpenApiPlugin::routes was called");
284 let is_default = cfg.swagger_asset_base == DEFAULT_SWAGGER_ASSET_BASE;
288 let (css_integrity, js_integrity) = if is_default {
289 (
290 format!(" integrity=\"{SWAGGER_CSS_SRI}\""),
291 format!(" integrity=\"{SWAGGER_JS_SRI}\""),
292 )
293 } else {
294 (String::new(), String::new())
295 };
296 let body = SWAGGER_UI_HTML
297 .replace("{ASSET_BASE}", &cfg.swagger_asset_base)
298 .replace("{CSS_INTEGRITY}", &css_integrity)
299 .replace("{JS_INTEGRITY}", &js_integrity)
300 .replace("{SPEC_URL}", &cfg.spec_url());
301 Html(body).into_response()
302}
303
304fn build_spec(cfg: &OpenApiPlugin) -> Value {
311 let mut schemas = Map::new();
312 let mut paths = Map::new();
313
314 let mut table_to_schema: std::collections::HashMap<String, String> =
322 std::collections::HashMap::new();
323 for plugin in umbral::migrate::registered_plugins() {
324 for model in umbral::migrate::models_for_plugin(&plugin) {
325 table_to_schema.insert(model.table.clone(), pascal_case_from_ident(&model.name));
326 }
327 }
328
329 let rest_base = umbral_rest::registered_base_path().to_owned();
333
334 for plugin in umbral::migrate::registered_plugins() {
335 for model in umbral::migrate::models_for_plugin(&plugin) {
336 if !umbral_rest::is_exposed(&model.table) {
345 continue;
346 }
347 if !cfg.is_exposed(&model.table) {
348 continue;
349 }
350 let schema_name = pascal_case_from_ident(&model.name);
351 schemas.insert(schema_name.clone(), model_schema(&model, &table_to_schema));
352 let mut list_params = Vec::new();
359 list_params.extend(pagination_parameters_for_style(
363 umbral_rest::registered_pagination_style(),
364 ));
365 if umbral_rest::search_enabled_for(&model.table) {
366 list_params.push(search_parameter());
367 }
368 list_params.push(fields_parameter(&model));
371 if model.fields.iter().any(|c| c.fk_target.is_some()) {
376 list_params.push(include_parameter(&model));
377 }
378 if umbral_rest::filters_enabled_for(&model.table) {
379 list_params.extend(filter_parameters(&model));
380 }
381 let collection = collection_paths(&model.table, &schema_name, &list_params);
385 if has_operations(&collection) {
386 paths.insert(format!("{}/{}/", rest_base, model.table), collection);
387 }
388 let mut item_params = vec![fields_parameter(&model)];
392 if model.fields.iter().any(|c| c.fk_target.is_some()) {
393 item_params.push(include_parameter(&model));
394 }
395 let item = item_paths(&model.table, &schema_name, &item_params);
399 if has_operations(&item) {
400 paths.insert(format!("{}/{}/{{id}}", rest_base, model.table), item);
401 }
402 }
403 }
404
405 if let Some(entries) = umbral::routes::registered_openapi_paths() {
411 for (path, item) in entries {
412 paths.insert(path.clone(), item.clone());
413 }
414 }
415
416 for action in umbral_rest::registered_action_schemas() {
421 let path = if action.detail {
422 format!(
423 "{}/{}/{{id}}/{}/",
424 action.base_path, action.table, action.name
425 )
426 } else {
427 format!("{}/{}/{}/", action.base_path, action.table, action.name)
428 };
429 paths.insert(path, action_path_item(&action));
430 }
431
432 let mut info = Map::new();
433 info.insert("title".into(), Value::String(cfg.title.clone()));
434 info.insert("version".into(), Value::String(cfg.version.clone()));
435 if let Some(desc) = &cfg.description {
436 info.insert("description".into(), Value::String(desc.clone()));
437 }
438
439 let mut security_schemes = Map::new();
446 let mut security: Vec<Value> = Vec::new();
447 for (name, scheme) in umbral_rest::registered_security_schemes() {
448 security.push(json!({ name.clone(): [] }));
449 security_schemes.insert(name, scheme);
450 }
451 let mut components = Map::new();
452 components.insert("schemas".into(), Value::Object(schemas));
453 if !security_schemes.is_empty() {
454 components.insert("securitySchemes".into(), Value::Object(security_schemes));
455 }
456
457 let mut document = Map::new();
458 document.insert("openapi".into(), Value::String("3.0.3".into()));
459 document.insert("info".into(), Value::Object(info));
460 document.insert("paths".into(), Value::Object(paths));
461 document.insert("components".into(), Value::Object(components));
462 if !security.is_empty() {
463 document.insert("security".into(), Value::Array(security));
464 }
465 Value::Object(document)
466}
467
468fn action_path_item(a: &umbral_rest::ActionSchema) -> Value {
472 let mut op = Map::new();
473 op.insert(
474 "operationId".into(),
475 Value::String(format!("{}_{}", a.table, a.name)),
476 );
477 op.insert("tags".into(), json!([a.table]));
478 op.insert(
479 "summary".into(),
480 Value::String(format!("`{}` action on {}", a.name, a.table)),
481 );
482 if a.detail {
483 op.insert(
484 "parameters".into(),
485 json!([{
486 "name": "id", "in": "path", "required": true,
487 "schema": { "type": "string" },
488 "description": "Primary key of the target row"
489 }]),
490 );
491 }
492 if let Some(input) = &a.input_schema {
493 op.insert(
494 "requestBody".into(),
495 json!({ "required": true, "content": { "application/json": { "schema": input } } }),
496 );
497 }
498 let mut ok = Map::new();
499 ok.insert("description".into(), Value::String("Action result".into()));
500 if let Some(output) = &a.output_schema {
501 ok.insert(
502 "content".into(),
503 json!({ "application/json": { "schema": output } }),
504 );
505 }
506 op.insert("responses".into(), json!({ "200": Value::Object(ok) }));
507
508 let mut item = Map::new();
509 item.insert(a.method.to_lowercase(), Value::Object(op));
510 Value::Object(item)
511}
512
513fn model_schema(
514 model: &ModelMeta,
515 table_to_schema: &std::collections::HashMap<String, String>,
516) -> Value {
517 let mut properties = Map::new();
518 let mut required: Vec<Value> = Vec::new();
519 for col in &model.fields {
520 let write_only = umbral_rest::is_write_only(&model.table, &col.name);
531 if umbral_rest::is_hidden(&model.table, &col.name) && !write_only {
532 continue;
533 }
534 let mut schema = column_schema_with_refs(col, table_to_schema);
535 if write_only {
536 if let Some(obj) = schema.as_object_mut() {
537 obj.insert("writeOnly".to_string(), Value::Bool(true));
538 }
539 }
540 properties.insert(col.name.clone(), schema);
541 if umbral_rest::is_conditionally_visible(&model.table, &col.name) {
557 continue;
558 }
559 if !col.nullable && !col.primary_key && !col.auto_now && !col.auto_now_add && !col.noform {
560 required.push(Value::String(col.name.clone()));
561 }
562 }
563 for rel in &model.m2m_relations {
570 let target_schema = table_to_schema
571 .get(&rel.target_table)
572 .cloned()
573 .unwrap_or_else(|| pascal_case_from_ident(&rel.target_name));
574 let mut prop = serde_json::Map::new();
575 prop.insert("type".into(), Value::String("array".into()));
576 let (item_ty, item_fmt) = umbral::migrate::pk_meta_for_table(&rel.target_table)
579 .map(|(_, pk_ty)| openapi_type(pk_ty))
580 .unwrap_or(("integer", Some("int64")));
581 let items = match item_fmt {
582 Some(f) => json!({ "type": item_ty, "format": f }),
583 None => json!({ "type": item_ty }),
584 };
585 prop.insert("items".into(), items);
586 prop.insert(
587 "description".into(),
588 Value::String(format!(
589 "Many-to-many relation to {}. Send an array of child ids on \
590 create / update; the framework writes the junction table.",
591 target_schema,
592 )),
593 );
594 prop.insert("x-umbral-m2m".into(), Value::Bool(true));
597 prop.insert(
598 "x-umbral-m2m-target".into(),
599 Value::String(target_schema.clone()),
600 );
601 prop.insert(
602 "x-umbral-m2m-target-table".into(),
603 Value::String(rel.target_table.clone()),
604 );
605 if table_to_schema.contains_key(&rel.target_table) {
606 prop.insert(
607 "x-umbral-m2m-target-ref".into(),
608 Value::String(format!("#/components/schemas/{target_schema}")),
609 );
610 }
611 properties.insert(rel.field_name.clone(), Value::Object(prop));
612 }
613 let mut obj = Map::new();
614 obj.insert("type".into(), Value::String("object".into()));
615 obj.insert("properties".into(), Value::Object(properties));
616 if !required.is_empty() {
617 obj.insert("required".into(), Value::Array(required));
618 }
619 Value::Object(obj)
620}
621
622fn column_schema_with_refs(
626 col: &Column,
627 table_to_schema: &std::collections::HashMap<String, String>,
628) -> Value {
629 let mut value = column_schema(col);
630 if let Some(target_table) = &col.fk_target {
640 if let Some(schema_name) = table_to_schema.get(target_table) {
641 if let Some(obj) = value.as_object_mut() {
642 obj.insert(
643 "x-umbral-fk-ref".into(),
644 Value::String(format!("#/components/schemas/{schema_name}")),
645 );
646 }
647 }
648 }
649 value
650}
651
652fn column_schema(col: &Column) -> Value {
653 let (ty, format) = openapi_type(umbral::migrate::fk_effective_type(col));
654 let mut obj = Map::new();
655 obj.insert("type".into(), Value::String(ty.into()));
656 if let Some(f) = format {
657 obj.insert("format".into(), Value::String(f.into()));
658 }
659 if col.nullable {
660 obj.insert("nullable".into(), Value::Bool(true));
661 }
662 if !col.help.is_empty() {
666 obj.insert("description".into(), Value::String(col.help.clone()));
667 }
668 if !col.example.is_empty() {
672 obj.insert("example".into(), Value::String(col.example.clone()));
673 }
674 if let Some(min) = col.min {
677 obj.insert(
678 "minimum".into(),
679 Value::Number(serde_json::Number::from(min)),
680 );
681 }
682 if let Some(max) = col.max {
683 obj.insert(
684 "maximum".into(),
685 Value::Number(serde_json::Number::from(max)),
686 );
687 }
688 if let Some(fmt) = col.text_format.as_deref() {
692 match fmt {
693 "email" => {
694 obj.insert("format".into(), Value::String("email".into()));
695 }
696 "url" => {
697 obj.insert("format".into(), Value::String("uri".into()));
698 }
699 "slug" => {
700 obj.insert("pattern".into(), Value::String("^[A-Za-z0-9_-]+$".into()));
704 }
705 _ => {}
706 }
707 }
708 if !col.choices.is_empty() && !col.is_multichoice {
714 obj.insert(
715 "enum".into(),
716 Value::Array(col.choices.iter().cloned().map(Value::String).collect()),
717 );
718 }
719 if col.max_length > 0 {
720 obj.insert(
721 "maxLength".into(),
722 Value::Number(serde_json::Number::from(col.max_length)),
723 );
724 }
725 if !col.default.is_empty() {
726 obj.insert("default".into(), Value::String(col.default.clone()));
731 }
732 if col.is_multichoice {
733 obj.insert("x-umbral-multichoice".into(), Value::Bool(true));
734 obj.insert(
735 "x-umbral-choices".into(),
736 Value::Array(col.choices.iter().cloned().map(Value::String).collect()),
737 );
738 }
739 if !col.choice_labels.is_empty() {
740 obj.insert(
741 "x-umbral-choice-labels".into(),
742 Value::Array(
743 col.choice_labels
744 .iter()
745 .cloned()
746 .map(Value::String)
747 .collect(),
748 ),
749 );
750 }
751 if let Some(target) = &col.fk_target {
752 obj.insert("x-umbral-fk-target".into(), Value::String(target.clone()));
753 }
754 if col.is_string_repr {
758 obj.insert("x-umbral-string-repr".into(), Value::Bool(true));
759 }
760 if col.auto_now_add {
781 obj.insert("x-umbral-auto-now-add".into(), Value::Bool(true));
782 }
783 if col.auto_now {
784 obj.insert("x-umbral-auto-now".into(), Value::Bool(true));
785 }
786 if col.noform {
787 obj.insert("readOnly".into(), Value::Bool(true));
788 obj.insert("x-umbral-noform".into(), Value::Bool(true));
794 }
795 if col.noedit {
800 obj.insert("x-umbral-noedit".into(), Value::Bool(true));
801 }
802 Value::Object(obj)
803}
804
805fn openapi_type(ty: SqlType) -> (&'static str, Option<&'static str>) {
806 match ty {
807 SqlType::SmallInt => ("integer", Some("int32")),
808 SqlType::Integer => ("integer", Some("int32")),
809 SqlType::BigInt => ("integer", Some("int64")),
810 SqlType::Real => ("number", Some("float")),
811 SqlType::Double => ("number", Some("double")),
812 SqlType::Boolean => ("boolean", None),
813 SqlType::Text => ("string", None),
814 SqlType::Date => ("string", Some("date")),
815 SqlType::Time => ("string", Some("time")),
816 SqlType::Timestamptz => ("string", Some("date-time")),
817 SqlType::Uuid => ("string", Some("uuid")),
818 SqlType::Json => ("object", None),
823 SqlType::Array(_) => ("array", None),
830 SqlType::Inet | SqlType::Cidr | SqlType::MacAddr => ("string", None),
835 SqlType::FullText => ("string", None),
838 SqlType::Xml | SqlType::Ltree | SqlType::Bit => ("string", None),
841 SqlType::ForeignKey => ("integer", Some("int64")),
844 SqlType::Bytes => ("array", Some("byte")),
851 SqlType::Decimal => ("string", Some("decimal")),
857 }
858}
859
860fn search_parameter() -> Value {
871 json!({
872 "name": "search",
873 "in": "query",
874 "required": false,
875 "description": "Free-text search across every searchable column. \
876 Text columns match via case-insensitive substring; \
877 numeric / FK / Boolean columns match exactly when \
878 the term parses as that type. Multiple matches are \
879 ORed.",
880 "schema": { "type": "string" },
881 "x-umbral-search": true,
882 })
883}
884
885fn fields_parameter(model: &ModelMeta) -> Value {
896 let columns: Vec<Value> = model
899 .fields
900 .iter()
901 .filter(|c| !umbral_rest::is_hidden(&model.table, &c.name))
902 .map(|c| Value::String(c.name.clone()))
903 .collect();
904 json!({
905 "name": "fields",
906 "in": "query",
907 "required": false,
908 "description": "Comma-separated list of column names to include in the \
909 response. Unknown names are silently dropped; an empty \
910 value falls back to the full row (BUG-81). Composes \
911 with hide / transform / computed — hide always wins, \
912 the rest are returned iff in the list.",
913 "schema": { "type": "string" },
914 "x-umbral-fields": true,
915 "x-umbral-fields-columns": Value::Array(columns),
916 })
917}
918
919fn include_parameter(model: &ModelMeta) -> Value {
926 let fks: Vec<Value> = model
930 .fields
931 .iter()
932 .filter(|c| c.fk_target.is_some())
933 .filter(|c| !umbral_rest::is_hidden(&model.table, &c.name))
934 .map(|c| Value::String(c.name.clone()))
935 .collect();
936 json!({
937 "name": "include",
938 "in": "query",
939 "required": false,
940 "description": "Comma-separated list of foreign-key columns to expand \
941 in the response. Each named FK gets replaced with the \
942 full related-row JSON object (one batched IN(...) query \
943 per FK — no N+1). Unknown or non-FK names return a 400. \
944 Example: `?include=user,billing_address`.",
945 "schema": { "type": "string" },
946 "x-umbral-include": true,
947 "x-umbral-include-fks": Value::Array(fks),
948 })
949}
950
951fn pagination_parameters_for_style(style: umbral_rest::PaginationStyle) -> Vec<Value> {
960 match style {
961 umbral_rest::PaginationStyle::PageNumber => vec![
962 json!({
963 "name": "page",
964 "in": "query",
965 "required": false,
966 "description": "1-indexed page number. Defaults to 1 when omitted.",
967 "schema": { "type": "integer", "format": "int32", "minimum": 1, "default": 1 },
968 "x-umbral-pagination": "page",
969 }),
970 json!({
971 "name": "page_size",
972 "in": "query",
973 "required": false,
974 "description": "Rows per page. Capped at 100. Default 20.",
975 "schema": {
976 "type": "integer", "format": "int32",
977 "minimum": 1, "maximum": 100, "default": 20,
978 },
979 "x-umbral-pagination": "page_size",
980 }),
981 ],
982 umbral_rest::PaginationStyle::LimitOffset => vec![
983 json!({
984 "name": "limit",
985 "in": "query",
986 "required": false,
987 "description": "Maximum rows to return. Defaults to the configured page size.",
988 "schema": { "type": "integer", "format": "int32", "minimum": 1 },
989 "x-umbral-pagination": "limit",
990 }),
991 json!({
992 "name": "offset",
993 "in": "query",
994 "required": false,
995 "description": "Number of rows to skip from the start of the result set. Defaults to 0.",
996 "schema": { "type": "integer", "format": "int32", "minimum": 0, "default": 0 },
997 "x-umbral-pagination": "offset",
998 }),
999 ],
1000 umbral_rest::PaginationStyle::None | umbral_rest::PaginationStyle::Custom => vec![],
1001 }
1002}
1003
1004fn filter_parameters(model: &ModelMeta) -> Vec<Value> {
1013 let mut out: Vec<Value> = Vec::new();
1014 for col in &model.fields {
1015 if col.primary_key {
1016 continue;
1017 }
1018 let lookups = umbral_rest::filtering::applicable_lookups(col);
1019 for lookup in lookups {
1020 let name = if lookup == "eq" {
1021 col.name.clone()
1022 } else {
1023 format!("{}__{}", col.name, lookup)
1024 };
1025 out.push(filter_parameter(col, lookup, &name));
1026 }
1027 }
1028 out
1029}
1030
1031fn filter_parameter(col: &Column, lookup: &str, name: &str) -> Value {
1042 let (schema, description) = match lookup {
1043 "in" => (
1044 json!({ "type": "string" }),
1045 format!(
1046 "Comma-separated `{}` values; matches rows where the column is in the set.",
1047 col.name,
1048 ),
1049 ),
1050 "isnull" => (
1051 json!({ "type": "boolean" }),
1052 format!(
1053 "`true` matches rows where `{}` IS NULL; `false` matches IS NOT NULL.",
1054 col.name,
1055 ),
1056 ),
1057 "contains" | "icontains" | "startswith" => {
1058 let phrase = match lookup {
1059 "contains" => "case-sensitive substring",
1060 "icontains" => "case-insensitive substring",
1061 "startswith" => "case-sensitive prefix",
1062 _ => unreachable!(),
1063 };
1064 (
1065 json!({ "type": "string" }),
1066 format!(
1067 "Matches rows where `{}` contains the given {phrase}.",
1068 col.name
1069 ),
1070 )
1071 }
1072 _ => {
1074 let (ty, format) = openapi_type(umbral::migrate::fk_effective_type(col));
1075 let mut schema_obj = Map::new();
1076 schema_obj.insert("type".into(), Value::String(ty.into()));
1077 if let Some(f) = format {
1078 schema_obj.insert("format".into(), Value::String(f.into()));
1079 }
1080 let phrase = match lookup {
1081 "eq" => "equals the value",
1082 "ne" => "does not equal the value",
1083 "gte" => "is greater than or equal to the value",
1084 "lte" => "is less than or equal to the value",
1085 "gt" => "is greater than the value",
1086 "lt" => "is less than the value",
1087 _ => "matches the value",
1088 };
1089 (
1090 Value::Object(schema_obj),
1091 format!("Matches rows where `{}` {phrase}.", col.name),
1092 )
1093 }
1094 };
1095
1096 json!({
1097 "name": name,
1098 "in": "query",
1099 "required": false,
1100 "description": description,
1101 "schema": schema,
1102 "x-umbral-filter-field": col.name,
1103 "x-umbral-filter-lookup": lookup,
1104 })
1105}
1106
1107fn collection_paths(table: &str, schema_name: &str, filter_params: &[Value]) -> Value {
1108 use umbral_rest::Action;
1109 let mut item = Map::new();
1110
1111 if umbral_rest::action_exposed(table, &Action::List) {
1116 let mut get_op = Map::new();
1117 get_op.insert(
1118 "operationId".into(),
1119 Value::String(format!("list_{}", table)),
1120 );
1121 get_op.insert("tags".into(), json!([table]));
1122 if !filter_params.is_empty() {
1123 get_op.insert("parameters".into(), Value::Array(filter_params.to_vec()));
1124 }
1125 get_op.insert(
1126 "responses".into(),
1127 json!({
1128 "200": {
1129 "description": "List of rows",
1130 "content": {
1131 "application/json": {
1132 "schema": list_envelope(schema_name)
1133 }
1134 }
1135 }
1136 }),
1137 );
1138 item.insert("get".into(), Value::Object(get_op));
1139 }
1140
1141 if umbral_rest::action_exposed(table, &Action::Create) {
1144 item.insert(
1145 "post".into(),
1146 json!({
1147 "operationId": format!("create_{}", table),
1148 "tags": [table],
1149 "requestBody": {
1150 "required": true,
1151 "content": {
1152 "application/json": {
1153 "schema": schema_ref(schema_name)
1154 }
1155 }
1156 },
1157 "responses": {
1158 "201": {
1159 "description": "Row created",
1160 "content": {
1161 "application/json": {
1162 "schema": schema_ref(schema_name)
1163 }
1164 }
1165 },
1166 "400": { "description": "Invalid input" }
1167 }
1168 }),
1169 );
1170 }
1171
1172 Value::Object(item)
1173}
1174
1175fn item_paths(table: &str, schema_name: &str, retrieve_query_params: &[Value]) -> Value {
1176 use umbral_rest::Action;
1177 let id_param = json!({
1178 "name": "id",
1179 "in": "path",
1180 "required": true,
1181 "schema": { "type": "string" }
1182 });
1183 let mut item = Map::new();
1184 item.insert("parameters".into(), json!([id_param]));
1185
1186 if umbral_rest::action_exposed(table, &Action::Retrieve) {
1192 let mut get_op = Map::new();
1193 get_op.insert(
1194 "operationId".into(),
1195 Value::String(format!("retrieve_{}", table)),
1196 );
1197 get_op.insert("tags".into(), json!([table]));
1198 if !retrieve_query_params.is_empty() {
1199 get_op.insert(
1200 "parameters".into(),
1201 Value::Array(retrieve_query_params.to_vec()),
1202 );
1203 }
1204 get_op.insert(
1205 "responses".into(),
1206 json!({
1207 "200": {
1208 "description": "Row found",
1209 "content": {
1210 "application/json": {
1211 "schema": schema_ref(schema_name)
1212 }
1213 }
1214 },
1215 "404": { "description": "Not found" }
1216 }),
1217 );
1218 item.insert("get".into(), Value::Object(get_op));
1219 }
1220
1221 if umbral_rest::action_exposed(table, &Action::Update) {
1223 item.insert(
1224 "put".into(),
1225 json!({
1226 "operationId": format!("update_{}", table),
1227 "tags": [table],
1228 "requestBody": {
1229 "required": true,
1230 "content": {
1231 "application/json": {
1232 "schema": schema_ref(schema_name)
1233 }
1234 }
1235 },
1236 "responses": {
1237 "200": {
1238 "description": "Row updated",
1239 "content": {
1240 "application/json": {
1241 "schema": schema_ref(schema_name)
1242 }
1243 }
1244 },
1245 "404": { "description": "Not found" }
1246 }
1247 }),
1248 );
1249 item.insert(
1250 "patch".into(),
1251 json!({
1252 "operationId": format!("partial_update_{}", table),
1253 "tags": [table],
1254 "requestBody": {
1255 "required": true,
1256 "content": {
1257 "application/json": {
1258 "schema": schema_ref(schema_name)
1259 }
1260 }
1261 },
1262 "responses": {
1263 "200": {
1264 "description": "Row partially updated",
1265 "content": {
1266 "application/json": {
1267 "schema": schema_ref(schema_name)
1268 }
1269 }
1270 },
1271 "404": { "description": "Not found" }
1272 }
1273 }),
1274 );
1275 }
1276
1277 if umbral_rest::action_exposed(table, &Action::Delete) {
1279 item.insert(
1280 "delete".into(),
1281 json!({
1282 "operationId": format!("destroy_{}", table),
1283 "tags": [table],
1284 "responses": {
1285 "204": { "description": "Row deleted" },
1286 "404": { "description": "Not found" }
1287 }
1288 }),
1289 );
1290 }
1291
1292 Value::Object(item)
1293}
1294
1295fn schema_ref(name: &str) -> Value {
1296 json!({ "$ref": format!("#/components/schemas/{}", name) })
1297}
1298
1299fn has_operations(path_item: &Value) -> bool {
1304 const METHODS: [&str; 7] = ["get", "post", "put", "patch", "delete", "head", "options"];
1305 path_item
1306 .as_object()
1307 .is_some_and(|m| METHODS.iter().any(|verb| m.contains_key(*verb)))
1308}
1309
1310fn list_envelope(schema_name: &str) -> Value {
1311 json!({
1312 "type": "object",
1313 "properties": {
1314 "results": {
1315 "type": "array",
1316 "items": schema_ref(schema_name)
1317 },
1318 "count": { "type": "integer" }
1319 },
1320 "required": ["results", "count"]
1321 })
1322}
1323
1324#[doc(hidden)]
1328pub fn test_spec_url(p: &OpenApiPlugin) -> String {
1329 p.spec_url()
1330}
1331
1332#[doc(hidden)]
1333pub fn test_ui_route(p: &OpenApiPlugin) -> String {
1334 p.ui_route()
1335}
1336
1337#[derive(Debug, Default)]
1348struct GenClientCommand;
1349
1350#[async_trait::async_trait]
1351impl umbral::cli::PluginCommand for GenClientCommand {
1352 fn command(&self) -> clap::Command {
1353 clap::Command::new("gen-client")
1354 .about("Generate a typed client (client.js + client.d.ts) for the REST API")
1355 .arg(
1356 clap::Arg::new("out")
1357 .long("out")
1358 .value_name("DIR")
1359 .required(true)
1360 .help("Directory to write client.js and client.d.ts into"),
1361 )
1362 .arg(
1363 clap::Arg::new("lang")
1364 .long("lang")
1365 .value_name("LANG")
1366 .default_value("ts")
1367 .help("Target language (only `ts` is supported)"),
1368 )
1369 .arg(
1370 clap::Arg::new("check")
1371 .long("check")
1372 .action(clap::ArgAction::SetTrue)
1373 .help("Write nothing; exit non-zero if the files have drifted from the models"),
1374 )
1375 }
1376
1377 async fn run(&self, matches: &clap::ArgMatches) -> Result<(), umbral::cli::CliError> {
1378 let lang = matches
1379 .get_one::<String>("lang")
1380 .map(String::as_str)
1381 .unwrap_or("ts");
1382 if lang != "ts" {
1383 return Err(format!("gen-client: unsupported --lang `{lang}` (only `ts`)").into());
1384 }
1385 let dir = std::path::PathBuf::from(
1386 matches
1387 .get_one::<String>("out")
1388 .expect("--out is required by clap"),
1389 );
1390 let check = matches.get_flag("check");
1391
1392 let generated = client_gen::generate();
1393 let files = [("client.js", generated.js), ("client.d.ts", generated.dts)];
1394
1395 if check {
1396 let mut stale = Vec::new();
1397 for (name, want) in &files {
1398 let path = dir.join(name);
1399 let have = std::fs::read_to_string(&path).unwrap_or_default();
1401 if &have != want {
1402 stale.push(path.display().to_string());
1403 }
1404 }
1405 if stale.is_empty() {
1406 println!("{} is up to date.", dir.display());
1407 return Ok(());
1408 }
1409 return Err(format!(
1410 "gen-client: out of date with the models: {}. Regenerate:\n \
1411 cargo run -- gen-client --out {}",
1412 stale.join(", "),
1413 dir.display(),
1414 )
1415 .into());
1416 }
1417
1418 std::fs::create_dir_all(&dir)?;
1419 for (name, contents) in &files {
1420 std::fs::write(dir.join(name), contents)?;
1421 }
1422 println!(
1423 "Wrote {} and {}.",
1424 dir.join("client.js").display(),
1425 dir.join("client.d.ts").display(),
1426 );
1427 Ok(())
1428 }
1429}
1430
1431#[cfg(test)]
1432mod tests {
1433 use super::*;
1434 use umbral::migrate::Column;
1435 use umbral::orm::SqlType;
1436
1437 #[test]
1440 fn swagger_asset_base_is_pinned_and_configurable() {
1441 assert!(
1443 DEFAULT_SWAGGER_ASSET_BASE.contains("@5.17"),
1444 "default asset base must pin an exact version, got {DEFAULT_SWAGGER_ASSET_BASE}"
1445 );
1446 assert!(!SWAGGER_UI_HTML.contains("unpkg.com/swagger-ui-dist@5/"));
1447 assert!(SWAGGER_UI_HTML.contains("{ASSET_BASE}"));
1448 assert!(SWAGGER_UI_HTML.contains("crossorigin=\"anonymous\""));
1449
1450 let p = OpenApiPlugin::new().swagger_asset_base("/static/swagger");
1452 let rendered = SWAGGER_UI_HTML
1453 .replace("{ASSET_BASE}", &p.swagger_asset_base)
1454 .replace("{SPEC_URL}", "/openapi/openapi.json");
1455 assert!(rendered.contains("/static/swagger/swagger-ui-bundle.js"));
1456 assert!(!rendered.contains("{ASSET_BASE}"));
1457 }
1458
1459 fn base_col(name: &str, ty: SqlType) -> Column {
1460 Column {
1461 name: name.into(),
1462 ty,
1463 primary_key: false,
1464 nullable: false,
1465 fk_target: None,
1466 noform: false,
1467 privileged: false,
1468 private: false,
1469 secret: false,
1470 db_constraint: true,
1471 noedit: false,
1472 auto_user_add: false,
1473 auto_user: false,
1474 is_string_repr: false,
1475 max_length: 0,
1476 choices: Vec::new(),
1477 choice_labels: Vec::new(),
1478 default: String::new(),
1479 is_multichoice: false,
1480 unique: false,
1481 on_delete: ::umbral::orm::FkAction::NoAction,
1482 on_update: ::umbral::orm::FkAction::NoAction,
1483 index: false,
1484 auto_now_add: false,
1485 auto_now: false,
1486 trim: false,
1487 lowercase: false,
1488 case_insensitive: false,
1489 help: String::new(),
1490 example: String::new(),
1491 widget: None,
1492 supported_backends: Vec::new(),
1493 min: None,
1494 max: None,
1495 text_format: ::core::option::Option::None,
1496 slug_from: ::core::option::Option::None,
1497 }
1498 }
1499
1500 #[test]
1501 fn choices_render_as_openapi_enum_with_labels_extension() {
1502 let mut col = base_col("status", SqlType::Text);
1503 col.choices = vec!["draft".into(), "published".into(), "archived".into()];
1504 col.choice_labels = vec!["Draft".into(), "Published".into(), "Archived".into()];
1505 let schema = column_schema(&col);
1506 assert_eq!(schema["type"], "string");
1507 assert_eq!(
1508 schema["enum"],
1509 serde_json::json!(["draft", "published", "archived"])
1510 );
1511 assert_eq!(
1512 schema["x-umbral-choice-labels"],
1513 serde_json::json!(["Draft", "Published", "Archived"])
1514 );
1515 }
1516
1517 #[test]
1518 fn multichoice_skips_enum_and_uses_vendor_extension() {
1519 let mut col = base_col("tags", SqlType::Text);
1520 col.choices = vec!["rust".into(), "python".into()];
1521 col.is_multichoice = true;
1522 let schema = column_schema(&col);
1523 assert!(
1524 schema.get("enum").is_none(),
1525 "multichoice columns should not declare a flat enum (value is a CSV subset)"
1526 );
1527 assert_eq!(schema["x-umbral-multichoice"], true);
1528 assert_eq!(
1529 schema["x-umbral-choices"],
1530 serde_json::json!(["rust", "python"])
1531 );
1532 }
1533
1534 #[test]
1535 fn max_length_and_default_surface_as_standard_openapi_keys() {
1536 let mut col = base_col("title", SqlType::Text);
1537 col.max_length = 50;
1538 col.default = "untitled".into();
1539 let schema = column_schema(&col);
1540 assert_eq!(schema["maxLength"], 50);
1541 assert_eq!(schema["default"], "untitled");
1542 }
1543
1544 #[test]
1545 fn fk_target_emits_vendor_extension_for_playground_navigation() {
1546 let mut col = base_col("author_id", SqlType::ForeignKey);
1547 col.fk_target = Some("auth_user".into());
1548 let schema = column_schema(&col);
1549 assert_eq!(schema["type"], "integer");
1550 assert_eq!(schema["format"], "int64");
1551 assert_eq!(schema["x-umbral-fk-target"], "auth_user");
1552 }
1553
1554 #[test]
1555 fn noform_renders_as_read_only_and_carries_vendor_extension() {
1556 let mut col = base_col("internal_token", SqlType::Text);
1561 col.noform = true;
1562 let schema = column_schema(&col);
1563 assert_eq!(schema["readOnly"], true);
1564 assert_eq!(schema["x-umbral-noform"], true);
1565 }
1566
1567 #[test]
1568 fn noedit_does_NOT_render_as_read_only() {
1569 let mut col = base_col("email", SqlType::Text);
1575 col.noedit = true;
1576 let schema = column_schema(&col);
1577 assert!(
1578 schema.get("readOnly").is_none(),
1579 "noedit must NOT contaminate the API request-body contract; \
1580 got readOnly in schema: {schema:?}"
1581 );
1582 assert_eq!(schema["x-umbral-noedit"], true);
1585 }
1586
1587 #[test]
1588 fn plain_column_keeps_minimal_schema_no_extensions() {
1589 let col = base_col("body", SqlType::Text);
1590 let schema = column_schema(&col);
1591 let obj = schema.as_object().expect("object");
1592 assert_eq!(
1593 obj.len(),
1594 1,
1595 "plain column should only have `type`: {obj:?}"
1596 );
1597 assert_eq!(schema["type"], "string");
1598 }
1599
1600 #[test]
1605 fn help_attribute_flows_to_openapi_description() {
1606 let mut col = base_col("status", SqlType::Text);
1607 col.help = "Workflow step. Set by editors on Save.".to_string();
1608 let schema = column_schema(&col);
1609 assert_eq!(
1610 schema["description"], "Workflow step. Set by editors on Save.",
1611 "help should round-trip to OpenAPI description; got: {schema:?}",
1612 );
1613 }
1614
1615 #[test]
1616 fn empty_help_omits_description() {
1617 let col = base_col("body", SqlType::Text);
1618 let schema = column_schema(&col);
1619 assert!(
1620 schema.get("description").is_none(),
1621 "empty help should omit description; got: {schema:?}",
1622 );
1623 }
1624
1625 #[test]
1629 fn example_attribute_flows_to_openapi_example() {
1630 let mut col = base_col("status", SqlType::Text);
1631 col.example = "published".to_string();
1632 let schema = column_schema(&col);
1633 assert_eq!(
1634 schema["example"], "published",
1635 "example should round-trip; got: {schema:?}",
1636 );
1637 }
1638
1639 #[test]
1640 fn empty_example_omits_example() {
1641 let col = base_col("body", SqlType::Text);
1642 let schema = column_schema(&col);
1643 assert!(
1644 schema.get("example").is_none(),
1645 "empty example should omit example key; got: {schema:?}",
1646 );
1647 }
1648
1649 fn note_model() -> ModelMeta {
1654 let mut id = base_col("id", SqlType::BigInt);
1655 id.primary_key = true;
1656 let mut published_at = base_col("published_at", SqlType::Timestamptz);
1657 published_at.nullable = true;
1658 ModelMeta {
1659 view: None,
1660 materialized: false,
1661 name: "Note".to_string(),
1662 table: "note".to_string(),
1663 fields: vec![
1664 id,
1665 base_col("title", SqlType::Text),
1666 base_col("views", SqlType::Integer),
1667 published_at,
1668 ],
1669 display: "Note".to_string(),
1670 icon: "database".to_string(),
1671 database: None,
1672 singleton: false,
1673 unique_together: Vec::new(),
1674 indexes: Vec::new(),
1675 ordering: Vec::new(),
1676 m2m_relations: Vec::new(),
1677 soft_delete: false,
1678 audited: false,
1679 app_label: "app".to_string(),
1680 }
1681 }
1682
1683 #[test]
1684 fn filter_parameters_skips_primary_key() {
1685 let params = filter_parameters(¬e_model());
1686 let names: Vec<&str> = params.iter().map(|p| p["name"].as_str().unwrap()).collect();
1687 assert!(
1688 !names.iter().any(|n| *n == "id" || n.starts_with("id__")),
1689 "PK column should be skipped; got {names:?}",
1690 );
1691 }
1692
1693 #[test]
1694 fn filter_parameters_eq_uses_bare_column_name_no_suffix() {
1695 let params = filter_parameters(¬e_model());
1696 let bare_title = params
1697 .iter()
1698 .find(|p| p["name"] == "title")
1699 .expect("title eq parameter should be present");
1700 assert_eq!(bare_title["x-umbral-filter-lookup"], "eq");
1701 assert_eq!(bare_title["x-umbral-filter-field"], "title");
1702 assert_eq!(bare_title["schema"]["type"], "string");
1703 }
1704
1705 #[test]
1706 fn filter_parameters_in_is_string_typed_with_csv_description() {
1707 let params = filter_parameters(¬e_model());
1708 let title_in = params
1709 .iter()
1710 .find(|p| p["name"] == "title__in")
1711 .expect("title__in parameter should be present");
1712 assert_eq!(title_in["schema"]["type"], "string");
1713 assert!(
1714 title_in["description"]
1715 .as_str()
1716 .unwrap()
1717 .to_lowercase()
1718 .contains("comma"),
1719 "__in description should mention the comma-separated format",
1720 );
1721 }
1722
1723 #[test]
1724 fn filter_parameters_isnull_only_on_nullable_columns() {
1725 let params = filter_parameters(¬e_model());
1726 let isnull_params: Vec<&str> = params
1727 .iter()
1728 .filter_map(|p| p["name"].as_str())
1729 .filter(|n| n.ends_with("__isnull"))
1730 .collect();
1731 assert_eq!(
1732 isnull_params,
1733 vec!["published_at__isnull"],
1734 "isnull lookup should only appear for nullable columns; got {isnull_params:?}",
1735 );
1736 }
1737
1738 #[test]
1739 fn filter_parameters_range_lookups_only_on_numeric_or_temporal() {
1740 let params = filter_parameters(¬e_model());
1741 let has_gte = |field: &str| params.iter().any(|p| p["name"] == format!("{field}__gte"));
1742 assert!(has_gte("views"), "integer column gets gte");
1743 assert!(has_gte("published_at"), "timestamp column gets gte");
1744 assert!(
1745 !has_gte("title"),
1746 "text column must NOT get gte; got {params:?}",
1747 );
1748 }
1749
1750 #[test]
1751 fn filter_parameters_string_lookups_only_on_text() {
1752 let params = filter_parameters(¬e_model());
1753 let has_contains = |field: &str| {
1754 params
1755 .iter()
1756 .any(|p| p["name"] == format!("{field}__contains"))
1757 };
1758 assert!(has_contains("title"), "text column gets contains");
1759 assert!(
1760 !has_contains("views"),
1761 "integer column must NOT get contains; got {params:?}",
1762 );
1763 }
1764
1765 #[test]
1766 fn collection_paths_omits_parameters_array_when_no_filters() {
1767 let value = collection_paths("note", "Note", &[]);
1768 let get_op = &value["get"];
1769 assert!(
1770 get_op.get("parameters").is_none(),
1771 "no filters → no parameters key; got {get_op:?}",
1772 );
1773 }
1774
1775 #[test]
1776 fn collection_paths_includes_parameters_when_filters_present() {
1777 let filter_params = filter_parameters(¬e_model());
1778 let value = collection_paths("note", "Note", &filter_params);
1779 let params = value["get"]["parameters"]
1780 .as_array()
1781 .expect("parameters array should be present when filters land");
1782 assert!(!params.is_empty());
1783 assert!(
1784 params.iter().all(|p| p["in"] == "query"),
1785 "every filter parameter is in: query",
1786 );
1787 }
1788
1789 #[test]
1794 fn fields_parameter_lists_model_columns() {
1795 let param = fields_parameter(¬e_model());
1796 assert_eq!(param["name"], "fields");
1797 assert_eq!(param["in"], "query");
1798 assert_eq!(param["x-umbral-fields"], true);
1799 let cols = param["x-umbral-fields-columns"]
1800 .as_array()
1801 .expect("x-umbral-fields-columns should be a list");
1802 let names: Vec<&str> = cols.iter().filter_map(|v| v.as_str()).collect();
1803 assert!(names.contains(&"title"));
1804 assert!(names.contains(&"views"));
1805 assert!(
1806 !names.is_empty(),
1807 "every column should land in the enum so the playground can offer it",
1808 );
1809 }
1810
1811 #[test]
1814 fn item_paths_advertises_fields_query_param_on_retrieve() {
1815 let value = item_paths("note", "Note", &[fields_parameter(¬e_model())]);
1816 let get_params = value["get"]["parameters"]
1817 .as_array()
1818 .expect("retrieve op should carry its query parameters");
1819 assert!(
1820 get_params.iter().any(|p| p["name"] == "fields"),
1821 "fields parameter should be on the retrieve op; got {get_params:?}",
1822 );
1823 }
1824
1825 #[test]
1830 fn fk_column_emits_schema_ref_when_target_known() {
1831 let mut col = base_col("author", SqlType::ForeignKey);
1832 col.fk_target = Some("auth_user".into());
1833 let mut map = std::collections::HashMap::new();
1834 map.insert("auth_user".to_string(), "AuthUser".to_string());
1835 let schema = column_schema_with_refs(&col, &map);
1836 assert_eq!(
1837 schema["x-umbral-fk-target"], "auth_user",
1838 "the table-name vendor extension stays for backward compat",
1839 );
1840 assert_eq!(
1841 schema["x-umbral-fk-ref"], "#/components/schemas/AuthUser",
1842 "the JSON pointer to the target schema should be emitted",
1843 );
1844 }
1845
1846 #[test]
1847 fn fk_column_without_known_target_omits_schema_ref() {
1848 let mut col = base_col("author", SqlType::ForeignKey);
1849 col.fk_target = Some("unknown_table".into());
1850 let map = std::collections::HashMap::new();
1851 let schema = column_schema_with_refs(&col, &map);
1852 assert!(
1853 schema.get("x-umbral-fk-ref").is_none(),
1854 "unknown FK target → no ref emitted; got: {schema:?}",
1855 );
1856 }
1857
1858 #[test]
1864 fn m2m_relation_lands_in_model_schema_with_target_extension() {
1865 let mut model = note_model();
1866 model.m2m_relations.push(umbral::migrate::M2MRelation {
1867 field_name: "tags".to_string(),
1868 target_table: "tag".to_string(),
1869 target_name: "Tag".to_string(),
1870 });
1871 let mut tts = std::collections::HashMap::new();
1875 tts.insert("tag".to_string(), "Tag".to_string());
1876 let schema = model_schema(&model, &tts);
1877 let tags_prop = &schema["properties"]["tags"];
1878 assert_eq!(tags_prop["type"], "array");
1879 assert_eq!(tags_prop["items"]["type"], "integer");
1880 assert_eq!(tags_prop["x-umbral-m2m"], true);
1881 assert_eq!(tags_prop["x-umbral-m2m-target"], "Tag");
1882 assert_eq!(tags_prop["x-umbral-m2m-target-table"], "tag");
1883 assert_eq!(
1884 tags_prop["x-umbral-m2m-target-ref"],
1885 "#/components/schemas/Tag",
1886 );
1887 let required = schema["required"].as_array();
1889 if let Some(req) = required {
1890 assert!(!req.iter().any(|v| v == "tags"));
1891 }
1892 }
1893
1894 #[test]
1902 fn auto_now_columns_are_optional_in_the_request_schema() {
1903 let mut model = note_model();
1904 let mut created = base_col("created_at", SqlType::Timestamptz);
1905 created.auto_now_add = true;
1906 let mut updated = base_col("updated_at", SqlType::Timestamptz);
1907 updated.auto_now = true;
1908 model.fields.push(created);
1909 model.fields.push(updated);
1910
1911 let schema = model_schema(&model, &std::collections::HashMap::new());
1912
1913 assert_eq!(
1917 schema["properties"]["created_at"]["x-umbral-auto-now-add"],
1918 true
1919 );
1920 assert_eq!(
1921 schema["properties"]["updated_at"]["x-umbral-auto-now"],
1922 true
1923 );
1924
1925 assert!(
1929 schema["properties"]["created_at"].get("readOnly").is_none(),
1930 "auto_now_add must not be readOnly; got {}",
1931 schema["properties"]["created_at"],
1932 );
1933 assert!(
1934 schema["properties"]["updated_at"].get("readOnly").is_none(),
1935 "auto_now must not be readOnly; got {}",
1936 schema["properties"]["updated_at"],
1937 );
1938
1939 let required = schema["required"].as_array().expect("required array");
1942 let names: Vec<&str> = required.iter().filter_map(|v| v.as_str()).collect();
1943 assert!(
1944 !names.contains(&"created_at"),
1945 "auto_now_add should drop out of required; got {names:?}",
1946 );
1947 assert!(
1948 !names.contains(&"updated_at"),
1949 "auto_now should drop out of required; got {names:?}",
1950 );
1951 }
1952
1953 #[test]
1956 fn pagination_parameters_per_style() {
1957 use umbral_rest::PaginationStyle;
1958
1959 let none_params = pagination_parameters_for_style(PaginationStyle::None);
1961 assert!(
1962 none_params.is_empty(),
1963 "NoPagination should emit no pagination params; got {none_params:?}"
1964 );
1965
1966 let custom_params = pagination_parameters_for_style(PaginationStyle::Custom);
1968 assert!(
1969 custom_params.is_empty(),
1970 "Custom pagination should emit no params; got {custom_params:?}"
1971 );
1972
1973 let page_params = pagination_parameters_for_style(PaginationStyle::PageNumber);
1975 assert_eq!(page_params.len(), 2, "PageNumber should emit 2 params");
1976 assert_eq!(page_params[0]["name"], "page");
1977 assert_eq!(page_params[0]["in"], "query");
1978 assert_eq!(page_params[0]["schema"]["type"], "integer");
1979 assert_eq!(page_params[0]["schema"]["minimum"], 1);
1980 assert_eq!(page_params[0]["schema"]["default"], 1);
1981 assert_eq!(page_params[0]["x-umbral-pagination"], "page");
1982 assert_eq!(page_params[1]["name"], "page_size");
1983 assert_eq!(page_params[1]["schema"]["maximum"], 100);
1984 assert_eq!(page_params[1]["x-umbral-pagination"], "page_size");
1985
1986 let lo_params = pagination_parameters_for_style(PaginationStyle::LimitOffset);
1988 assert_eq!(lo_params.len(), 2, "LimitOffset should emit 2 params");
1989 assert_eq!(lo_params[0]["name"], "limit");
1990 assert_eq!(lo_params[0]["x-umbral-pagination"], "limit");
1991 assert_eq!(lo_params[1]["name"], "offset");
1992 assert_eq!(lo_params[1]["x-umbral-pagination"], "offset");
1993 assert_eq!(lo_params[1]["schema"]["minimum"], 0);
1994 }
1995}