added support for loading a serialized json payload as part of multipart/form-data request

This commit is contained in:
Gani Georgiev
2024-01-14 22:20:46 +02:00
parent cdb539dcc8
commit 28fc186f5c
6 changed files with 192 additions and 16 deletions
+12 -2
View File
@@ -165,7 +165,7 @@ func (form *RecordUpsert) extractMultipartFormData(
data := map[string]any{}
filesToUpload := map[string][]*filesystem.File{}
arrayValueSupportTypes := schema.ArraybleFieldTypes()
arraybleFieldTypes := schema.ArraybleFieldTypes()
for fullKey, values := range r.PostForm {
key := fullKey
@@ -178,8 +178,18 @@ func (form *RecordUpsert) extractMultipartFormData(
continue
}
// special case for multipart json encoded fields
if key == rest.MultipartJsonKey {
for _, v := range values {
if err := json.Unmarshal([]byte(v), &data); err != nil {
form.app.Logger().Debug("Failed to decode @json value into the data map", "error", err, "value", v)
}
}
continue
}
field := form.record.Collection().Schema.GetFieldByName(key)
if field != nil && list.ExistInSlice(field.Type, arrayValueSupportTypes) {
if field != nil && list.ExistInSlice(field.Type, arraybleFieldTypes) {
data[key] = values
} else {
data[key] = values[0]
+18 -3
View File
@@ -22,6 +22,7 @@ import (
"github.com/pocketbase/pocketbase/tests"
"github.com/pocketbase/pocketbase/tools/filesystem"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/rest"
"github.com/pocketbase/pocketbase/tools/types"
)
@@ -150,9 +151,10 @@ func TestRecordUpsertLoadRequestMultipart(t *testing.T) {
}
formData, mp, err := tests.MockMultipartData(map[string]string{
"a.b.id": "test_id",
"a.b.text": "test123",
"a.b.unknown": "test456",
"a.b.id": "test_id",
"a.b.text": "test123",
"a.b.unknown": "test456",
"a.b." + rest.MultipartJsonKey: `{"json":["a","b"],"email":"test3@example.com"}`,
// file fields unset/delete
"a.b.file_one-": "test_d61b33QdDU.txt", // delete with modifier
"a.b.file_many.0": "", // delete by index
@@ -184,6 +186,19 @@ func TestRecordUpsertLoadRequestMultipart(t *testing.T) {
t.Fatalf("Didn't expect unknown field to be set, got %v", v)
}
if v, ok := form.Data()["email"]; !ok || v != "test3@example.com" {
t.Fatalf("Expect email field to be %q, got %q", "test3@example.com", v)
}
rawJsonValue, ok := form.Data()["json"].(types.JsonRaw)
if !ok {
t.Fatal("Expect json field to be set")
}
expectedJsonValue := `["a","b"]`
if rawJsonValue.String() != expectedJsonValue {
t.Fatalf("Expect json field %v, got %v", expectedJsonValue, rawJsonValue)
}
fileOne, ok := form.Data()["file_one"]
if !ok {
t.Fatal("Expect file_one field to be set")