J
J
J. Snow2020-07-08 09:53:41
JavaScript
J. Snow, 2020-07-08 09:53:41

How to type multipart/form-data?

Hi all!

I have a client-server application written in TypeScript + Kotlin.
In one place on the client, I collect the necessary data in the form of multipart / form-data and transfer it to the server.

Question:
How not to hardcode keys (names of multipart elements) and make everything type-safe?

Now everything looks something like this:

const formData = new FormData()
formData.append("name", "John")
formData.append("surname", "Snow")
formData.append("photo", blob)
axios.post("/backend/api", formData)

multipart.forEachPart { part ->
    when (part) {
        is PartData.FormItem -> {
            when (part.name) {
                "user" -> {}
                "surname" -> {}
            }
        }
        is PartData.FileItem -> {}
    }
}

Hardcode both on the client and on the backend.
How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2020-07-08
@Alex_Wells

Describe a DTO (stupidly a class with fields) and serialize on the front, deserialize (map) on the back.
On the back it might look like:

data class SomeRequestDTO(val name: String, val surname: String, val photo: Photo)

and some kind of mapper thread, which automatically maps everything where necessary.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question