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