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 if umbral_rest::is_hidden(&model.table, &col.name) {
527 continue;
528 }
529 properties.insert(
530 col.name.clone(),
531 column_schema_with_refs(col, table_to_schema),
532 );
533 if !col.nullable && !col.primary_key && !col.auto_now && !col.auto_now_add && !col.noform {
543 required.push(Value::String(col.name.clone()));
544 }
545 }
546 for rel in &model.m2m_relations {
553 let target_schema = table_to_schema
554 .get(&rel.target_table)
555 .cloned()
556 .unwrap_or_else(|| pascal_case_from_ident(&rel.target_name));
557 let mut prop = serde_json::Map::new();
558 prop.insert("type".into(), Value::String("array".into()));
559 let (item_ty, item_fmt) = umbral::migrate::pk_meta_for_table(&rel.target_table)
562 .map(|(_, pk_ty)| openapi_type(pk_ty))
563 .unwrap_or(("integer", Some("int64")));
564 let items = match item_fmt {
565 Some(f) => json!({ "type": item_ty, "format": f }),
566 None => json!({ "type": item_ty }),
567 };
568 prop.insert("items".into(), items);
569 prop.insert(
570 "description".into(),
571 Value::String(format!(
572 "Many-to-many relation to {}. Send an array of child ids on \
573 create / update; the framework writes the junction table.",
574 target_schema,
575 )),
576 );
577 prop.insert("x-umbral-m2m".into(), Value::Bool(true));
580 prop.insert(
581 "x-umbral-m2m-target".into(),
582 Value::String(target_schema.clone()),
583 );
584 prop.insert(
585 "x-umbral-m2m-target-table".into(),
586 Value::String(rel.target_table.clone()),
587 );
588 if table_to_schema.contains_key(&rel.target_table) {
589 prop.insert(
590 "x-umbral-m2m-target-ref".into(),
591 Value::String(format!("#/components/schemas/{target_schema}")),
592 );
593 }
594 properties.insert(rel.field_name.clone(), Value::Object(prop));
595 }
596 let mut obj = Map::new();
597 obj.insert("type".into(), Value::String("object".into()));
598 obj.insert("properties".into(), Value::Object(properties));
599 if !required.is_empty() {
600 obj.insert("required".into(), Value::Array(required));
601 }
602 Value::Object(obj)
603}
604
605fn column_schema_with_refs(
609 col: &Column,
610 table_to_schema: &std::collections::HashMap<String, String>,
611) -> Value {
612 let mut value = column_schema(col);
613 if let Some(target_table) = &col.fk_target {
623 if let Some(schema_name) = table_to_schema.get(target_table) {
624 if let Some(obj) = value.as_object_mut() {
625 obj.insert(
626 "x-umbral-fk-ref".into(),
627 Value::String(format!("#/components/schemas/{schema_name}")),
628 );
629 }
630 }
631 }
632 value
633}
634
635fn column_schema(col: &Column) -> Value {
636 let (ty, format) = openapi_type(umbral::migrate::fk_effective_type(col));
637 let mut obj = Map::new();
638 obj.insert("type".into(), Value::String(ty.into()));
639 if let Some(f) = format {
640 obj.insert("format".into(), Value::String(f.into()));
641 }
642 if col.nullable {
643 obj.insert("nullable".into(), Value::Bool(true));
644 }
645 if !col.help.is_empty() {
649 obj.insert("description".into(), Value::String(col.help.clone()));
650 }
651 if !col.example.is_empty() {
655 obj.insert("example".into(), Value::String(col.example.clone()));
656 }
657 if let Some(min) = col.min {
660 obj.insert(
661 "minimum".into(),
662 Value::Number(serde_json::Number::from(min)),
663 );
664 }
665 if let Some(max) = col.max {
666 obj.insert(
667 "maximum".into(),
668 Value::Number(serde_json::Number::from(max)),
669 );
670 }
671 if let Some(fmt) = col.text_format.as_deref() {
675 match fmt {
676 "email" => {
677 obj.insert("format".into(), Value::String("email".into()));
678 }
679 "url" => {
680 obj.insert("format".into(), Value::String("uri".into()));
681 }
682 "slug" => {
683 obj.insert("pattern".into(), Value::String("^[A-Za-z0-9_-]+$".into()));
687 }
688 _ => {}
689 }
690 }
691 if !col.choices.is_empty() && !col.is_multichoice {
697 obj.insert(
698 "enum".into(),
699 Value::Array(col.choices.iter().cloned().map(Value::String).collect()),
700 );
701 }
702 if col.max_length > 0 {
703 obj.insert(
704 "maxLength".into(),
705 Value::Number(serde_json::Number::from(col.max_length)),
706 );
707 }
708 if !col.default.is_empty() {
709 obj.insert("default".into(), Value::String(col.default.clone()));
714 }
715 if col.is_multichoice {
716 obj.insert("x-umbral-multichoice".into(), Value::Bool(true));
717 obj.insert(
718 "x-umbral-choices".into(),
719 Value::Array(col.choices.iter().cloned().map(Value::String).collect()),
720 );
721 }
722 if !col.choice_labels.is_empty() {
723 obj.insert(
724 "x-umbral-choice-labels".into(),
725 Value::Array(
726 col.choice_labels
727 .iter()
728 .cloned()
729 .map(Value::String)
730 .collect(),
731 ),
732 );
733 }
734 if let Some(target) = &col.fk_target {
735 obj.insert("x-umbral-fk-target".into(), Value::String(target.clone()));
736 }
737 if col.is_string_repr {
741 obj.insert("x-umbral-string-repr".into(), Value::Bool(true));
742 }
743 if col.auto_now_add {
764 obj.insert("x-umbral-auto-now-add".into(), Value::Bool(true));
765 }
766 if col.auto_now {
767 obj.insert("x-umbral-auto-now".into(), Value::Bool(true));
768 }
769 if col.noform {
770 obj.insert("readOnly".into(), Value::Bool(true));
771 obj.insert("x-umbral-noform".into(), Value::Bool(true));
777 }
778 if col.noedit {
783 obj.insert("x-umbral-noedit".into(), Value::Bool(true));
784 }
785 Value::Object(obj)
786}
787
788fn openapi_type(ty: SqlType) -> (&'static str, Option<&'static str>) {
789 match ty {
790 SqlType::SmallInt => ("integer", Some("int32")),
791 SqlType::Integer => ("integer", Some("int32")),
792 SqlType::BigInt => ("integer", Some("int64")),
793 SqlType::Real => ("number", Some("float")),
794 SqlType::Double => ("number", Some("double")),
795 SqlType::Boolean => ("boolean", None),
796 SqlType::Text => ("string", None),
797 SqlType::Date => ("string", Some("date")),
798 SqlType::Time => ("string", Some("time")),
799 SqlType::Timestamptz => ("string", Some("date-time")),
800 SqlType::Uuid => ("string", Some("uuid")),
801 SqlType::Json => ("object", None),
806 SqlType::Array(_) => ("array", None),
813 SqlType::Inet | SqlType::Cidr | SqlType::MacAddr => ("string", None),
818 SqlType::FullText => ("string", None),
821 SqlType::Xml | SqlType::Ltree | SqlType::Bit => ("string", None),
824 SqlType::ForeignKey => ("integer", Some("int64")),
827 SqlType::Bytes => ("array", Some("byte")),
834 SqlType::Decimal => ("string", Some("decimal")),
840 }
841}
842
843fn search_parameter() -> Value {
854 json!({
855 "name": "search",
856 "in": "query",
857 "required": false,
858 "description": "Free-text search across every searchable column. \
859 Text columns match via case-insensitive substring; \
860 numeric / FK / Boolean columns match exactly when \
861 the term parses as that type. Multiple matches are \
862 ORed.",
863 "schema": { "type": "string" },
864 "x-umbral-search": true,
865 })
866}
867
868fn fields_parameter(model: &ModelMeta) -> Value {
879 let columns: Vec<Value> = model
882 .fields
883 .iter()
884 .filter(|c| !umbral_rest::is_hidden(&model.table, &c.name))
885 .map(|c| Value::String(c.name.clone()))
886 .collect();
887 json!({
888 "name": "fields",
889 "in": "query",
890 "required": false,
891 "description": "Comma-separated list of column names to include in the \
892 response. Unknown names are silently dropped; an empty \
893 value falls back to the full row (BUG-81). Composes \
894 with hide / transform / computed — hide always wins, \
895 the rest are returned iff in the list.",
896 "schema": { "type": "string" },
897 "x-umbral-fields": true,
898 "x-umbral-fields-columns": Value::Array(columns),
899 })
900}
901
902fn include_parameter(model: &ModelMeta) -> Value {
909 let fks: Vec<Value> = model
913 .fields
914 .iter()
915 .filter(|c| c.fk_target.is_some())
916 .filter(|c| !umbral_rest::is_hidden(&model.table, &c.name))
917 .map(|c| Value::String(c.name.clone()))
918 .collect();
919 json!({
920 "name": "include",
921 "in": "query",
922 "required": false,
923 "description": "Comma-separated list of foreign-key columns to expand \
924 in the response. Each named FK gets replaced with the \
925 full related-row JSON object (one batched IN(...) query \
926 per FK — no N+1). Unknown or non-FK names return a 400. \
927 Example: `?include=user,billing_address`.",
928 "schema": { "type": "string" },
929 "x-umbral-include": true,
930 "x-umbral-include-fks": Value::Array(fks),
931 })
932}
933
934fn pagination_parameters_for_style(style: umbral_rest::PaginationStyle) -> Vec<Value> {
943 match style {
944 umbral_rest::PaginationStyle::PageNumber => vec![
945 json!({
946 "name": "page",
947 "in": "query",
948 "required": false,
949 "description": "1-indexed page number. Defaults to 1 when omitted.",
950 "schema": { "type": "integer", "format": "int32", "minimum": 1, "default": 1 },
951 "x-umbral-pagination": "page",
952 }),
953 json!({
954 "name": "page_size",
955 "in": "query",
956 "required": false,
957 "description": "Rows per page. Capped at 100. Default 20.",
958 "schema": {
959 "type": "integer", "format": "int32",
960 "minimum": 1, "maximum": 100, "default": 20,
961 },
962 "x-umbral-pagination": "page_size",
963 }),
964 ],
965 umbral_rest::PaginationStyle::LimitOffset => vec![
966 json!({
967 "name": "limit",
968 "in": "query",
969 "required": false,
970 "description": "Maximum rows to return. Defaults to the configured page size.",
971 "schema": { "type": "integer", "format": "int32", "minimum": 1 },
972 "x-umbral-pagination": "limit",
973 }),
974 json!({
975 "name": "offset",
976 "in": "query",
977 "required": false,
978 "description": "Number of rows to skip from the start of the result set. Defaults to 0.",
979 "schema": { "type": "integer", "format": "int32", "minimum": 0, "default": 0 },
980 "x-umbral-pagination": "offset",
981 }),
982 ],
983 umbral_rest::PaginationStyle::None | umbral_rest::PaginationStyle::Custom => vec![],
984 }
985}
986
987fn filter_parameters(model: &ModelMeta) -> Vec<Value> {
996 let mut out: Vec<Value> = Vec::new();
997 for col in &model.fields {
998 if col.primary_key {
999 continue;
1000 }
1001 let lookups = umbral_rest::filtering::applicable_lookups(col);
1002 for lookup in lookups {
1003 let name = if lookup == "eq" {
1004 col.name.clone()
1005 } else {
1006 format!("{}__{}", col.name, lookup)
1007 };
1008 out.push(filter_parameter(col, lookup, &name));
1009 }
1010 }
1011 out
1012}
1013
1014fn filter_parameter(col: &Column, lookup: &str, name: &str) -> Value {
1025 let (schema, description) = match lookup {
1026 "in" => (
1027 json!({ "type": "string" }),
1028 format!(
1029 "Comma-separated `{}` values; matches rows where the column is in the set.",
1030 col.name,
1031 ),
1032 ),
1033 "isnull" => (
1034 json!({ "type": "boolean" }),
1035 format!(
1036 "`true` matches rows where `{}` IS NULL; `false` matches IS NOT NULL.",
1037 col.name,
1038 ),
1039 ),
1040 "contains" | "icontains" | "startswith" => {
1041 let phrase = match lookup {
1042 "contains" => "case-sensitive substring",
1043 "icontains" => "case-insensitive substring",
1044 "startswith" => "case-sensitive prefix",
1045 _ => unreachable!(),
1046 };
1047 (
1048 json!({ "type": "string" }),
1049 format!(
1050 "Matches rows where `{}` contains the given {phrase}.",
1051 col.name
1052 ),
1053 )
1054 }
1055 _ => {
1057 let (ty, format) = openapi_type(umbral::migrate::fk_effective_type(col));
1058 let mut schema_obj = Map::new();
1059 schema_obj.insert("type".into(), Value::String(ty.into()));
1060 if let Some(f) = format {
1061 schema_obj.insert("format".into(), Value::String(f.into()));
1062 }
1063 let phrase = match lookup {
1064 "eq" => "equals the value",
1065 "ne" => "does not equal the value",
1066 "gte" => "is greater than or equal to the value",
1067 "lte" => "is less than or equal to the value",
1068 "gt" => "is greater than the value",
1069 "lt" => "is less than the value",
1070 _ => "matches the value",
1071 };
1072 (
1073 Value::Object(schema_obj),
1074 format!("Matches rows where `{}` {phrase}.", col.name),
1075 )
1076 }
1077 };
1078
1079 json!({
1080 "name": name,
1081 "in": "query",
1082 "required": false,
1083 "description": description,
1084 "schema": schema,
1085 "x-umbral-filter-field": col.name,
1086 "x-umbral-filter-lookup": lookup,
1087 })
1088}
1089
1090fn collection_paths(table: &str, schema_name: &str, filter_params: &[Value]) -> Value {
1091 use umbral_rest::Action;
1092 let mut item = Map::new();
1093
1094 if umbral_rest::action_exposed(table, &Action::List) {
1099 let mut get_op = Map::new();
1100 get_op.insert(
1101 "operationId".into(),
1102 Value::String(format!("list_{}", table)),
1103 );
1104 get_op.insert("tags".into(), json!([table]));
1105 if !filter_params.is_empty() {
1106 get_op.insert("parameters".into(), Value::Array(filter_params.to_vec()));
1107 }
1108 get_op.insert(
1109 "responses".into(),
1110 json!({
1111 "200": {
1112 "description": "List of rows",
1113 "content": {
1114 "application/json": {
1115 "schema": list_envelope(schema_name)
1116 }
1117 }
1118 }
1119 }),
1120 );
1121 item.insert("get".into(), Value::Object(get_op));
1122 }
1123
1124 if umbral_rest::action_exposed(table, &Action::Create) {
1127 item.insert(
1128 "post".into(),
1129 json!({
1130 "operationId": format!("create_{}", table),
1131 "tags": [table],
1132 "requestBody": {
1133 "required": true,
1134 "content": {
1135 "application/json": {
1136 "schema": schema_ref(schema_name)
1137 }
1138 }
1139 },
1140 "responses": {
1141 "201": {
1142 "description": "Row created",
1143 "content": {
1144 "application/json": {
1145 "schema": schema_ref(schema_name)
1146 }
1147 }
1148 },
1149 "400": { "description": "Invalid input" }
1150 }
1151 }),
1152 );
1153 }
1154
1155 Value::Object(item)
1156}
1157
1158fn item_paths(table: &str, schema_name: &str, retrieve_query_params: &[Value]) -> Value {
1159 use umbral_rest::Action;
1160 let id_param = json!({
1161 "name": "id",
1162 "in": "path",
1163 "required": true,
1164 "schema": { "type": "string" }
1165 });
1166 let mut item = Map::new();
1167 item.insert("parameters".into(), json!([id_param]));
1168
1169 if umbral_rest::action_exposed(table, &Action::Retrieve) {
1175 let mut get_op = Map::new();
1176 get_op.insert(
1177 "operationId".into(),
1178 Value::String(format!("retrieve_{}", table)),
1179 );
1180 get_op.insert("tags".into(), json!([table]));
1181 if !retrieve_query_params.is_empty() {
1182 get_op.insert(
1183 "parameters".into(),
1184 Value::Array(retrieve_query_params.to_vec()),
1185 );
1186 }
1187 get_op.insert(
1188 "responses".into(),
1189 json!({
1190 "200": {
1191 "description": "Row found",
1192 "content": {
1193 "application/json": {
1194 "schema": schema_ref(schema_name)
1195 }
1196 }
1197 },
1198 "404": { "description": "Not found" }
1199 }),
1200 );
1201 item.insert("get".into(), Value::Object(get_op));
1202 }
1203
1204 if umbral_rest::action_exposed(table, &Action::Update) {
1206 item.insert(
1207 "put".into(),
1208 json!({
1209 "operationId": format!("update_{}", table),
1210 "tags": [table],
1211 "requestBody": {
1212 "required": true,
1213 "content": {
1214 "application/json": {
1215 "schema": schema_ref(schema_name)
1216 }
1217 }
1218 },
1219 "responses": {
1220 "200": {
1221 "description": "Row updated",
1222 "content": {
1223 "application/json": {
1224 "schema": schema_ref(schema_name)
1225 }
1226 }
1227 },
1228 "404": { "description": "Not found" }
1229 }
1230 }),
1231 );
1232 item.insert(
1233 "patch".into(),
1234 json!({
1235 "operationId": format!("partial_update_{}", table),
1236 "tags": [table],
1237 "requestBody": {
1238 "required": true,
1239 "content": {
1240 "application/json": {
1241 "schema": schema_ref(schema_name)
1242 }
1243 }
1244 },
1245 "responses": {
1246 "200": {
1247 "description": "Row partially updated",
1248 "content": {
1249 "application/json": {
1250 "schema": schema_ref(schema_name)
1251 }
1252 }
1253 },
1254 "404": { "description": "Not found" }
1255 }
1256 }),
1257 );
1258 }
1259
1260 if umbral_rest::action_exposed(table, &Action::Delete) {
1262 item.insert(
1263 "delete".into(),
1264 json!({
1265 "operationId": format!("destroy_{}", table),
1266 "tags": [table],
1267 "responses": {
1268 "204": { "description": "Row deleted" },
1269 "404": { "description": "Not found" }
1270 }
1271 }),
1272 );
1273 }
1274
1275 Value::Object(item)
1276}
1277
1278fn schema_ref(name: &str) -> Value {
1279 json!({ "$ref": format!("#/components/schemas/{}", name) })
1280}
1281
1282fn has_operations(path_item: &Value) -> bool {
1287 const METHODS: [&str; 7] = ["get", "post", "put", "patch", "delete", "head", "options"];
1288 path_item
1289 .as_object()
1290 .is_some_and(|m| METHODS.iter().any(|verb| m.contains_key(*verb)))
1291}
1292
1293fn list_envelope(schema_name: &str) -> Value {
1294 json!({
1295 "type": "object",
1296 "properties": {
1297 "results": {
1298 "type": "array",
1299 "items": schema_ref(schema_name)
1300 },
1301 "count": { "type": "integer" }
1302 },
1303 "required": ["results", "count"]
1304 })
1305}
1306
1307#[doc(hidden)]
1311pub fn test_spec_url(p: &OpenApiPlugin) -> String {
1312 p.spec_url()
1313}
1314
1315#[doc(hidden)]
1316pub fn test_ui_route(p: &OpenApiPlugin) -> String {
1317 p.ui_route()
1318}
1319
1320#[derive(Debug, Default)]
1331struct GenClientCommand;
1332
1333#[async_trait::async_trait]
1334impl umbral::cli::PluginCommand for GenClientCommand {
1335 fn command(&self) -> clap::Command {
1336 clap::Command::new("gen-client")
1337 .about("Generate a typed client (client.js + client.d.ts) for the REST API")
1338 .arg(
1339 clap::Arg::new("out")
1340 .long("out")
1341 .value_name("DIR")
1342 .required(true)
1343 .help("Directory to write client.js and client.d.ts into"),
1344 )
1345 .arg(
1346 clap::Arg::new("lang")
1347 .long("lang")
1348 .value_name("LANG")
1349 .default_value("ts")
1350 .help("Target language (only `ts` is supported)"),
1351 )
1352 .arg(
1353 clap::Arg::new("check")
1354 .long("check")
1355 .action(clap::ArgAction::SetTrue)
1356 .help("Write nothing; exit non-zero if the files have drifted from the models"),
1357 )
1358 }
1359
1360 async fn run(&self, matches: &clap::ArgMatches) -> Result<(), umbral::cli::CliError> {
1361 let lang = matches
1362 .get_one::<String>("lang")
1363 .map(String::as_str)
1364 .unwrap_or("ts");
1365 if lang != "ts" {
1366 return Err(format!("gen-client: unsupported --lang `{lang}` (only `ts`)").into());
1367 }
1368 let dir = std::path::PathBuf::from(
1369 matches
1370 .get_one::<String>("out")
1371 .expect("--out is required by clap"),
1372 );
1373 let check = matches.get_flag("check");
1374
1375 let generated = client_gen::generate();
1376 let files = [("client.js", generated.js), ("client.d.ts", generated.dts)];
1377
1378 if check {
1379 let mut stale = Vec::new();
1380 for (name, want) in &files {
1381 let path = dir.join(name);
1382 let have = std::fs::read_to_string(&path).unwrap_or_default();
1384 if &have != want {
1385 stale.push(path.display().to_string());
1386 }
1387 }
1388 if stale.is_empty() {
1389 println!("{} is up to date.", dir.display());
1390 return Ok(());
1391 }
1392 return Err(format!(
1393 "gen-client: out of date with the models: {}. Regenerate:\n \
1394 cargo run -- gen-client --out {}",
1395 stale.join(", "),
1396 dir.display(),
1397 )
1398 .into());
1399 }
1400
1401 std::fs::create_dir_all(&dir)?;
1402 for (name, contents) in &files {
1403 std::fs::write(dir.join(name), contents)?;
1404 }
1405 println!(
1406 "Wrote {} and {}.",
1407 dir.join("client.js").display(),
1408 dir.join("client.d.ts").display(),
1409 );
1410 Ok(())
1411 }
1412}
1413
1414#[cfg(test)]
1415mod tests {
1416 use super::*;
1417 use umbral::migrate::Column;
1418 use umbral::orm::SqlType;
1419
1420 #[test]
1423 fn swagger_asset_base_is_pinned_and_configurable() {
1424 assert!(
1426 DEFAULT_SWAGGER_ASSET_BASE.contains("@5.17"),
1427 "default asset base must pin an exact version, got {DEFAULT_SWAGGER_ASSET_BASE}"
1428 );
1429 assert!(!SWAGGER_UI_HTML.contains("unpkg.com/swagger-ui-dist@5/"));
1430 assert!(SWAGGER_UI_HTML.contains("{ASSET_BASE}"));
1431 assert!(SWAGGER_UI_HTML.contains("crossorigin=\"anonymous\""));
1432
1433 let p = OpenApiPlugin::new().swagger_asset_base("/static/swagger");
1435 let rendered = SWAGGER_UI_HTML
1436 .replace("{ASSET_BASE}", &p.swagger_asset_base)
1437 .replace("{SPEC_URL}", "/openapi/openapi.json");
1438 assert!(rendered.contains("/static/swagger/swagger-ui-bundle.js"));
1439 assert!(!rendered.contains("{ASSET_BASE}"));
1440 }
1441
1442 fn base_col(name: &str, ty: SqlType) -> Column {
1443 Column {
1444 name: name.into(),
1445 ty,
1446 primary_key: false,
1447 nullable: false,
1448 fk_target: None,
1449 noform: false,
1450 privileged: false,
1451 db_constraint: true,
1452 noedit: false,
1453 auto_user_add: false,
1454 auto_user: false,
1455 is_string_repr: false,
1456 max_length: 0,
1457 choices: Vec::new(),
1458 choice_labels: Vec::new(),
1459 default: String::new(),
1460 is_multichoice: false,
1461 unique: false,
1462 on_delete: ::umbral::orm::FkAction::NoAction,
1463 on_update: ::umbral::orm::FkAction::NoAction,
1464 index: false,
1465 auto_now_add: false,
1466 auto_now: false,
1467 trim: false,
1468 lowercase: false,
1469 case_insensitive: false,
1470 help: String::new(),
1471 example: String::new(),
1472 widget: None,
1473 supported_backends: Vec::new(),
1474 min: None,
1475 max: None,
1476 text_format: ::core::option::Option::None,
1477 slug_from: ::core::option::Option::None,
1478 }
1479 }
1480
1481 #[test]
1482 fn choices_render_as_openapi_enum_with_labels_extension() {
1483 let mut col = base_col("status", SqlType::Text);
1484 col.choices = vec!["draft".into(), "published".into(), "archived".into()];
1485 col.choice_labels = vec!["Draft".into(), "Published".into(), "Archived".into()];
1486 let schema = column_schema(&col);
1487 assert_eq!(schema["type"], "string");
1488 assert_eq!(
1489 schema["enum"],
1490 serde_json::json!(["draft", "published", "archived"])
1491 );
1492 assert_eq!(
1493 schema["x-umbral-choice-labels"],
1494 serde_json::json!(["Draft", "Published", "Archived"])
1495 );
1496 }
1497
1498 #[test]
1499 fn multichoice_skips_enum_and_uses_vendor_extension() {
1500 let mut col = base_col("tags", SqlType::Text);
1501 col.choices = vec!["rust".into(), "python".into()];
1502 col.is_multichoice = true;
1503 let schema = column_schema(&col);
1504 assert!(
1505 schema.get("enum").is_none(),
1506 "multichoice columns should not declare a flat enum (value is a CSV subset)"
1507 );
1508 assert_eq!(schema["x-umbral-multichoice"], true);
1509 assert_eq!(
1510 schema["x-umbral-choices"],
1511 serde_json::json!(["rust", "python"])
1512 );
1513 }
1514
1515 #[test]
1516 fn max_length_and_default_surface_as_standard_openapi_keys() {
1517 let mut col = base_col("title", SqlType::Text);
1518 col.max_length = 50;
1519 col.default = "untitled".into();
1520 let schema = column_schema(&col);
1521 assert_eq!(schema["maxLength"], 50);
1522 assert_eq!(schema["default"], "untitled");
1523 }
1524
1525 #[test]
1526 fn fk_target_emits_vendor_extension_for_playground_navigation() {
1527 let mut col = base_col("author_id", SqlType::ForeignKey);
1528 col.fk_target = Some("auth_user".into());
1529 let schema = column_schema(&col);
1530 assert_eq!(schema["type"], "integer");
1531 assert_eq!(schema["format"], "int64");
1532 assert_eq!(schema["x-umbral-fk-target"], "auth_user");
1533 }
1534
1535 #[test]
1536 fn noform_renders_as_read_only_and_carries_vendor_extension() {
1537 let mut col = base_col("internal_token", SqlType::Text);
1542 col.noform = true;
1543 let schema = column_schema(&col);
1544 assert_eq!(schema["readOnly"], true);
1545 assert_eq!(schema["x-umbral-noform"], true);
1546 }
1547
1548 #[test]
1549 fn noedit_does_NOT_render_as_read_only() {
1550 let mut col = base_col("email", SqlType::Text);
1556 col.noedit = true;
1557 let schema = column_schema(&col);
1558 assert!(
1559 schema.get("readOnly").is_none(),
1560 "noedit must NOT contaminate the API request-body contract; \
1561 got readOnly in schema: {schema:?}"
1562 );
1563 assert_eq!(schema["x-umbral-noedit"], true);
1566 }
1567
1568 #[test]
1569 fn plain_column_keeps_minimal_schema_no_extensions() {
1570 let col = base_col("body", SqlType::Text);
1571 let schema = column_schema(&col);
1572 let obj = schema.as_object().expect("object");
1573 assert_eq!(
1574 obj.len(),
1575 1,
1576 "plain column should only have `type`: {obj:?}"
1577 );
1578 assert_eq!(schema["type"], "string");
1579 }
1580
1581 #[test]
1586 fn help_attribute_flows_to_openapi_description() {
1587 let mut col = base_col("status", SqlType::Text);
1588 col.help = "Workflow step. Set by editors on Save.".to_string();
1589 let schema = column_schema(&col);
1590 assert_eq!(
1591 schema["description"], "Workflow step. Set by editors on Save.",
1592 "help should round-trip to OpenAPI description; got: {schema:?}",
1593 );
1594 }
1595
1596 #[test]
1597 fn empty_help_omits_description() {
1598 let col = base_col("body", SqlType::Text);
1599 let schema = column_schema(&col);
1600 assert!(
1601 schema.get("description").is_none(),
1602 "empty help should omit description; got: {schema:?}",
1603 );
1604 }
1605
1606 #[test]
1610 fn example_attribute_flows_to_openapi_example() {
1611 let mut col = base_col("status", SqlType::Text);
1612 col.example = "published".to_string();
1613 let schema = column_schema(&col);
1614 assert_eq!(
1615 schema["example"], "published",
1616 "example should round-trip; got: {schema:?}",
1617 );
1618 }
1619
1620 #[test]
1621 fn empty_example_omits_example() {
1622 let col = base_col("body", SqlType::Text);
1623 let schema = column_schema(&col);
1624 assert!(
1625 schema.get("example").is_none(),
1626 "empty example should omit example key; got: {schema:?}",
1627 );
1628 }
1629
1630 fn note_model() -> ModelMeta {
1635 let mut id = base_col("id", SqlType::BigInt);
1636 id.primary_key = true;
1637 let mut published_at = base_col("published_at", SqlType::Timestamptz);
1638 published_at.nullable = true;
1639 ModelMeta {
1640 view: None,
1641 materialized: false,
1642 name: "Note".to_string(),
1643 table: "note".to_string(),
1644 fields: vec![
1645 id,
1646 base_col("title", SqlType::Text),
1647 base_col("views", SqlType::Integer),
1648 published_at,
1649 ],
1650 display: "Note".to_string(),
1651 icon: "database".to_string(),
1652 database: None,
1653 singleton: false,
1654 unique_together: Vec::new(),
1655 indexes: Vec::new(),
1656 ordering: Vec::new(),
1657 m2m_relations: Vec::new(),
1658 soft_delete: false,
1659 audited: false,
1660 app_label: "app".to_string(),
1661 }
1662 }
1663
1664 #[test]
1665 fn filter_parameters_skips_primary_key() {
1666 let params = filter_parameters(¬e_model());
1667 let names: Vec<&str> = params.iter().map(|p| p["name"].as_str().unwrap()).collect();
1668 assert!(
1669 !names.iter().any(|n| *n == "id" || n.starts_with("id__")),
1670 "PK column should be skipped; got {names:?}",
1671 );
1672 }
1673
1674 #[test]
1675 fn filter_parameters_eq_uses_bare_column_name_no_suffix() {
1676 let params = filter_parameters(¬e_model());
1677 let bare_title = params
1678 .iter()
1679 .find(|p| p["name"] == "title")
1680 .expect("title eq parameter should be present");
1681 assert_eq!(bare_title["x-umbral-filter-lookup"], "eq");
1682 assert_eq!(bare_title["x-umbral-filter-field"], "title");
1683 assert_eq!(bare_title["schema"]["type"], "string");
1684 }
1685
1686 #[test]
1687 fn filter_parameters_in_is_string_typed_with_csv_description() {
1688 let params = filter_parameters(¬e_model());
1689 let title_in = params
1690 .iter()
1691 .find(|p| p["name"] == "title__in")
1692 .expect("title__in parameter should be present");
1693 assert_eq!(title_in["schema"]["type"], "string");
1694 assert!(
1695 title_in["description"]
1696 .as_str()
1697 .unwrap()
1698 .to_lowercase()
1699 .contains("comma"),
1700 "__in description should mention the comma-separated format",
1701 );
1702 }
1703
1704 #[test]
1705 fn filter_parameters_isnull_only_on_nullable_columns() {
1706 let params = filter_parameters(¬e_model());
1707 let isnull_params: Vec<&str> = params
1708 .iter()
1709 .filter_map(|p| p["name"].as_str())
1710 .filter(|n| n.ends_with("__isnull"))
1711 .collect();
1712 assert_eq!(
1713 isnull_params,
1714 vec!["published_at__isnull"],
1715 "isnull lookup should only appear for nullable columns; got {isnull_params:?}",
1716 );
1717 }
1718
1719 #[test]
1720 fn filter_parameters_range_lookups_only_on_numeric_or_temporal() {
1721 let params = filter_parameters(¬e_model());
1722 let has_gte = |field: &str| params.iter().any(|p| p["name"] == format!("{field}__gte"));
1723 assert!(has_gte("views"), "integer column gets gte");
1724 assert!(has_gte("published_at"), "timestamp column gets gte");
1725 assert!(
1726 !has_gte("title"),
1727 "text column must NOT get gte; got {params:?}",
1728 );
1729 }
1730
1731 #[test]
1732 fn filter_parameters_string_lookups_only_on_text() {
1733 let params = filter_parameters(¬e_model());
1734 let has_contains = |field: &str| {
1735 params
1736 .iter()
1737 .any(|p| p["name"] == format!("{field}__contains"))
1738 };
1739 assert!(has_contains("title"), "text column gets contains");
1740 assert!(
1741 !has_contains("views"),
1742 "integer column must NOT get contains; got {params:?}",
1743 );
1744 }
1745
1746 #[test]
1747 fn collection_paths_omits_parameters_array_when_no_filters() {
1748 let value = collection_paths("note", "Note", &[]);
1749 let get_op = &value["get"];
1750 assert!(
1751 get_op.get("parameters").is_none(),
1752 "no filters → no parameters key; got {get_op:?}",
1753 );
1754 }
1755
1756 #[test]
1757 fn collection_paths_includes_parameters_when_filters_present() {
1758 let filter_params = filter_parameters(¬e_model());
1759 let value = collection_paths("note", "Note", &filter_params);
1760 let params = value["get"]["parameters"]
1761 .as_array()
1762 .expect("parameters array should be present when filters land");
1763 assert!(!params.is_empty());
1764 assert!(
1765 params.iter().all(|p| p["in"] == "query"),
1766 "every filter parameter is in: query",
1767 );
1768 }
1769
1770 #[test]
1775 fn fields_parameter_lists_model_columns() {
1776 let param = fields_parameter(¬e_model());
1777 assert_eq!(param["name"], "fields");
1778 assert_eq!(param["in"], "query");
1779 assert_eq!(param["x-umbral-fields"], true);
1780 let cols = param["x-umbral-fields-columns"]
1781 .as_array()
1782 .expect("x-umbral-fields-columns should be a list");
1783 let names: Vec<&str> = cols.iter().filter_map(|v| v.as_str()).collect();
1784 assert!(names.contains(&"title"));
1785 assert!(names.contains(&"views"));
1786 assert!(
1787 !names.is_empty(),
1788 "every column should land in the enum so the playground can offer it",
1789 );
1790 }
1791
1792 #[test]
1795 fn item_paths_advertises_fields_query_param_on_retrieve() {
1796 let value = item_paths("note", "Note", &[fields_parameter(¬e_model())]);
1797 let get_params = value["get"]["parameters"]
1798 .as_array()
1799 .expect("retrieve op should carry its query parameters");
1800 assert!(
1801 get_params.iter().any(|p| p["name"] == "fields"),
1802 "fields parameter should be on the retrieve op; got {get_params:?}",
1803 );
1804 }
1805
1806 #[test]
1811 fn fk_column_emits_schema_ref_when_target_known() {
1812 let mut col = base_col("author", SqlType::ForeignKey);
1813 col.fk_target = Some("auth_user".into());
1814 let mut map = std::collections::HashMap::new();
1815 map.insert("auth_user".to_string(), "AuthUser".to_string());
1816 let schema = column_schema_with_refs(&col, &map);
1817 assert_eq!(
1818 schema["x-umbral-fk-target"], "auth_user",
1819 "the table-name vendor extension stays for backward compat",
1820 );
1821 assert_eq!(
1822 schema["x-umbral-fk-ref"], "#/components/schemas/AuthUser",
1823 "the JSON pointer to the target schema should be emitted",
1824 );
1825 }
1826
1827 #[test]
1828 fn fk_column_without_known_target_omits_schema_ref() {
1829 let mut col = base_col("author", SqlType::ForeignKey);
1830 col.fk_target = Some("unknown_table".into());
1831 let map = std::collections::HashMap::new();
1832 let schema = column_schema_with_refs(&col, &map);
1833 assert!(
1834 schema.get("x-umbral-fk-ref").is_none(),
1835 "unknown FK target → no ref emitted; got: {schema:?}",
1836 );
1837 }
1838
1839 #[test]
1845 fn m2m_relation_lands_in_model_schema_with_target_extension() {
1846 let mut model = note_model();
1847 model.m2m_relations.push(umbral::migrate::M2MRelation {
1848 field_name: "tags".to_string(),
1849 target_table: "tag".to_string(),
1850 target_name: "Tag".to_string(),
1851 });
1852 let mut tts = std::collections::HashMap::new();
1856 tts.insert("tag".to_string(), "Tag".to_string());
1857 let schema = model_schema(&model, &tts);
1858 let tags_prop = &schema["properties"]["tags"];
1859 assert_eq!(tags_prop["type"], "array");
1860 assert_eq!(tags_prop["items"]["type"], "integer");
1861 assert_eq!(tags_prop["x-umbral-m2m"], true);
1862 assert_eq!(tags_prop["x-umbral-m2m-target"], "Tag");
1863 assert_eq!(tags_prop["x-umbral-m2m-target-table"], "tag");
1864 assert_eq!(
1865 tags_prop["x-umbral-m2m-target-ref"],
1866 "#/components/schemas/Tag",
1867 );
1868 let required = schema["required"].as_array();
1870 if let Some(req) = required {
1871 assert!(!req.iter().any(|v| v == "tags"));
1872 }
1873 }
1874
1875 #[test]
1883 fn auto_now_columns_are_optional_in_the_request_schema() {
1884 let mut model = note_model();
1885 let mut created = base_col("created_at", SqlType::Timestamptz);
1886 created.auto_now_add = true;
1887 let mut updated = base_col("updated_at", SqlType::Timestamptz);
1888 updated.auto_now = true;
1889 model.fields.push(created);
1890 model.fields.push(updated);
1891
1892 let schema = model_schema(&model, &std::collections::HashMap::new());
1893
1894 assert_eq!(
1898 schema["properties"]["created_at"]["x-umbral-auto-now-add"],
1899 true
1900 );
1901 assert_eq!(
1902 schema["properties"]["updated_at"]["x-umbral-auto-now"],
1903 true
1904 );
1905
1906 assert!(
1910 schema["properties"]["created_at"].get("readOnly").is_none(),
1911 "auto_now_add must not be readOnly; got {}",
1912 schema["properties"]["created_at"],
1913 );
1914 assert!(
1915 schema["properties"]["updated_at"].get("readOnly").is_none(),
1916 "auto_now must not be readOnly; got {}",
1917 schema["properties"]["updated_at"],
1918 );
1919
1920 let required = schema["required"].as_array().expect("required array");
1923 let names: Vec<&str> = required.iter().filter_map(|v| v.as_str()).collect();
1924 assert!(
1925 !names.contains(&"created_at"),
1926 "auto_now_add should drop out of required; got {names:?}",
1927 );
1928 assert!(
1929 !names.contains(&"updated_at"),
1930 "auto_now should drop out of required; got {names:?}",
1931 );
1932 }
1933
1934 #[test]
1937 fn pagination_parameters_per_style() {
1938 use umbral_rest::PaginationStyle;
1939
1940 let none_params = pagination_parameters_for_style(PaginationStyle::None);
1942 assert!(
1943 none_params.is_empty(),
1944 "NoPagination should emit no pagination params; got {none_params:?}"
1945 );
1946
1947 let custom_params = pagination_parameters_for_style(PaginationStyle::Custom);
1949 assert!(
1950 custom_params.is_empty(),
1951 "Custom pagination should emit no params; got {custom_params:?}"
1952 );
1953
1954 let page_params = pagination_parameters_for_style(PaginationStyle::PageNumber);
1956 assert_eq!(page_params.len(), 2, "PageNumber should emit 2 params");
1957 assert_eq!(page_params[0]["name"], "page");
1958 assert_eq!(page_params[0]["in"], "query");
1959 assert_eq!(page_params[0]["schema"]["type"], "integer");
1960 assert_eq!(page_params[0]["schema"]["minimum"], 1);
1961 assert_eq!(page_params[0]["schema"]["default"], 1);
1962 assert_eq!(page_params[0]["x-umbral-pagination"], "page");
1963 assert_eq!(page_params[1]["name"], "page_size");
1964 assert_eq!(page_params[1]["schema"]["maximum"], 100);
1965 assert_eq!(page_params[1]["x-umbral-pagination"], "page_size");
1966
1967 let lo_params = pagination_parameters_for_style(PaginationStyle::LimitOffset);
1969 assert_eq!(lo_params.len(), 2, "LimitOffset should emit 2 params");
1970 assert_eq!(lo_params[0]["name"], "limit");
1971 assert_eq!(lo_params[0]["x-umbral-pagination"], "limit");
1972 assert_eq!(lo_params[1]["name"], "offset");
1973 assert_eq!(lo_params[1]["x-umbral-pagination"], "offset");
1974 assert_eq!(lo_params[1]["schema"]["minimum"], 0);
1975 }
1976}