Updated the update action, to set a null value for fields that came in the request as empty string

This commit is contained in:
2022-09-27 13:28:13 -05:00
parent 833b1f9643
commit 3587cc0676
2 changed files with 25 additions and 4 deletions

View File

@ -403,9 +403,21 @@ public class QJavalinImplementation
Map<?, ?> map = context.bodyAsClass(Map.class);
for(Map.Entry<?, ?> entry : map.entrySet())
{
if(StringUtils.hasContent(String.valueOf(entry.getValue())))
String fieldName = ValueUtils.getValueAsString(entry.getKey());
Object value = entry.getValue();
if(StringUtils.hasContent(String.valueOf(value)))
{
record.setValue(String.valueOf(entry.getKey()), (Serializable) entry.getValue());
record.setValue(fieldName, (Serializable) value);
}
else if("".equals(value))
{
///////////////////////////////////////////////////////////////////////////////////////////////////
// if frontend sent us an empty string - put a null in the record's value map. //
// this could potentially be changed to be type-specific (e.g., store an empty-string for STRING //
// fields, but null for INTEGER, etc) - but, who really wants empty-string in database anyway? //
///////////////////////////////////////////////////////////////////////////////////////////////////
record.setValue(fieldName, null);
}
}

View File

@ -338,7 +338,7 @@ class QJavalinImplementationTest extends QJavalinTestBase
{
Map<String, Serializable> body = new HashMap<>();
body.put("firstName", "Free");
//? body.put("id", 4);
body.put("birthDate", "");
HttpResponse<String> response = Unirest.patch(BASE_URL + "/data/person/4")
.header("Content-Type", "application/json")
@ -356,7 +356,16 @@ class QJavalinImplementationTest extends QJavalinTestBase
JSONObject values0 = record0.getJSONObject("values");
assertEquals(4, values0.getInt("id"));
assertEquals("Free", values0.getString("firstName"));
// mmm, whole record isn't loaded. should it be? assertEquals("Samples", values0.getString("lastName"));
///////////////////////////////////////////////////////////////////
// re-GET the record, and validate that birthDate was nulled out //
///////////////////////////////////////////////////////////////////
response = Unirest.get(BASE_URL + "/data/person/4").asString();
assertEquals(200, response.getStatus());
jsonObject = JsonUtils.toJSONObject(response.getBody());
assertTrue(jsonObject.has("values"));
JSONObject values = jsonObject.getJSONObject("values");
assertFalse(values.has("birthDate"));
}