@@ -343,7 +343,7 @@ defmodule Schema.JsonSchema do
343343 end
344344
345345 defp encode_attribute ( _name , "string_t" , attr ) do
346- new_schema ( attr ) |> encode_string ( attr )
346+ new_schema ( attr ) |> encode_string ( attr ) |> put_string_constraints ( "string_t" )
347347 end
348348
349349 defp encode_attribute ( name , "object_t" , attr ) do
@@ -366,8 +366,9 @@ defmodule Schema.JsonSchema do
366366
367367 defp put_type ( schema , type ) do
368368 types = Map . get ( Schema . data_types ( ) , :attributes )
369+ type_key = String . to_atom ( type )
369370
370- case Map . get ( types , String . to_atom ( type ) ) do
371+ case Map . get ( types , type_key ) do
371372 nil ->
372373 schema
373374
@@ -380,14 +381,48 @@ defmodule Schema.JsonSchema do
380381 |> Map . put ( "type" , Types . encode_type ( base_type ) )
381382
382383 # add range from the type if available
383- case data [ :range ] do
384- [ min , max | _ ] ->
385- schema
386- |> Map . put ( "minimum" , min )
387- |> Map . put ( "maximum" , max )
388-
389- _ ->
390- schema
384+ schema =
385+ case data [ :range ] do
386+ [ min , max | _ ] ->
387+ schema
388+ |> Map . put ( "minimum" , min )
389+ |> Map . put ( "maximum" , max )
390+
391+ _ ->
392+ schema
393+ end
394+
395+ put_string_constraints ( schema , type )
396+ end
397+ end
398+
399+ # Applies max_len -> maxLength and regex -> pattern from the dictionary type
400+ # (or its supertype) onto the given schema map. Called for both string_t
401+ # attributes and subtype string-like attributes resolved through put_type/2.
402+ defp put_string_constraints ( schema , type ) do
403+ types = Map . get ( Schema . data_types ( ) , :attributes )
404+ type_key = String . to_atom ( type )
405+
406+ case Map . get ( types , type_key ) do
407+ nil ->
408+ schema
409+
410+ data ->
411+ super_data =
412+ case data [ :type ] do
413+ nil -> % { }
414+ super_type -> Map . get ( types , String . to_atom ( super_type ) , % { } )
415+ end
416+
417+ schema =
418+ case data [ :max_len ] || super_data [ :max_len ] do
419+ nil -> schema
420+ max_len -> Map . put ( schema , "maxLength" , max_len )
421+ end
422+
423+ case data [ :regex ] || super_data [ :regex ] do
424+ nil -> schema
425+ regex -> Map . put ( schema , "pattern" , regex )
391426 end
392427 end
393428 end
0 commit comments