Closed
Description
Christoph Strobl opened DATAMONGO-1849 and commented
Use the information from MongoPersistentEntity
and MongoPersistentProperty
to generate JSON Schema for a given type using annotations like @Nullable
to distinguish between required and optional fields.
MongoJsonSchema fromType(Class<?> domainType) {
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(domainType);
MongoJsonSchemaBuilder builder = MongoJsonSchema.builder();
entity.doWithProperties((SimplePropertyHandler) persistentProperty -> {
// if property is constructor arg or not @Nullable make it required
if(entity.isConstructorArgument(persistentProperty) || persistentProperty.findAnnotation(Nullable.class) == null) {
builder.required(persistentProperty.getName());
}
// append a collection type property
if(persistentProperty.isArray() || persistentProperty.isCollectionLike()) {
ArrayJsonSchemaProperty arrayProperty = JsonSchemaProperty.array(persistentProperty.getName()); //
if(ClassUtils.isAssignable(Set.class, persistentProperty.getActualType())) {
arrayProperty = arrayProperty.uniqueItems(true);
}
builder.property(arrayProperty);
}
if(persistentProperty.isEntity()) {
// .... and so on
Reference URL: https://stackoverflow.com/questions/50169457/define-mongo-schema-validation-using-spring
Issue Links:
-
DATACMNS-1513 Expose nullability requirements for PersistentProperty and PreferredConstructor arguments
-
DATAMONGO-1322 Add support for validator when creating collection
-
DATAMONGO-1835 Add support for $jsonSchema to Criteria API
Referenced from: pull request #733
2 votes, 2 watchers