Skip to content

Commit ae51eb2

Browse files
committed
✨ Add string trimming validator
1 parent 7e6f3e4 commit ae51eb2

File tree

2 files changed

+26
-7
lines changed
  • packages/models-library/src/models_library/utils
  • services/api-server/src/simcore_service_api_server/models/schemas

2 files changed

+26
-7
lines changed

packages/models-library/src/models_library/utils/common_validators.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" Reusable validators
1+
"""Reusable validators
22
33
Example:
44
@@ -22,10 +22,19 @@ class MyModel(BaseModel):
2222

2323
from common_library.json_serialization import json_loads
2424
from orjson import JSONDecodeError
25-
from pydantic import BaseModel
25+
from pydantic import BaseModel, BeforeValidator
2626
from pydantic.alias_generators import to_camel
2727

2828

29+
def trim_string_before(max_length: int) -> BeforeValidator:
30+
def _trim(value: str):
31+
if isinstance(value, str):
32+
return value[:max_length]
33+
return value
34+
35+
return BeforeValidator(_trim)
36+
37+
2938
def empty_str_to_none_pre_validator(value: Any):
3039
if isinstance(value, str) and value.strip() == "":
3140
return None

services/api-server/src/simcore_service_api_server/models/schemas/_base.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import packaging.version
55
from models_library.utils.change_case import camel_to_snake
6+
from models_library.utils.common_validators import trim_string_before
67
from pydantic import BaseModel, ConfigDict, Field, HttpUrl, StringConstraints
78

89
from ...models._utils_pydantic import UriSchema
@@ -28,22 +29,31 @@ class ApiServerInputSchema(BaseModel):
2829

2930

3031
class BaseService(BaseModel):
31-
id: Annotated[str, Field(..., description="Resource identifier")]
32+
id: Annotated[
33+
str,
34+
Field(description="Resource identifier"),
35+
]
3236
version: Annotated[
33-
VersionStr, Field(..., description="Semantic version number of the resource")
37+
VersionStr,
38+
Field(description="Semantic version number of the resource"),
3439
]
3540
title: Annotated[
3641
str,
42+
trim_string_before(max_length=100),
3743
StringConstraints(max_length=100),
38-
Field(..., description="Human readable name"),
44+
Field(description="Human readable name"),
3945
]
4046
description: Annotated[
4147
str | None,
42-
StringConstraints(max_length=500),
48+
trim_string_before(max_length=1000),
49+
StringConstraints(max_length=1000),
4350
Field(default=None, description="Description of the resource"),
4451
]
52+
4553
url: Annotated[
46-
HttpUrl | None, UriSchema(), Field(..., description="Link to get this resource")
54+
HttpUrl | None,
55+
UriSchema(),
56+
Field(description="Link to get this resource"),
4757
]
4858

4959
@property

0 commit comments

Comments
 (0)