fabian-hiller / decode-formdata

Decodes complex FormData into a JavaScript object
MIT License
241 stars 7 forks source link

Cannot decode date if timestamp is a string #6

Closed sacrosanctic closed 1 year ago

sacrosanctic commented 1 year ago

Formdata content is always stored as a string. So if I am sending a Timestamp to the server it will be converted to a string and fail.

Repro

const formData = new FormData()
formData.append('createdDate', new Date().getTime())
const data = decode(formData, { dates:['createdDate'] })
console.log(data)

Demo

Expected

{
  createdDate: 2020-02-20T00:00:00.000Z
}

Actual

{
  createdDate: Invalid Date
}

Suggestion

Addtional Info

btw, your package is awesome.

fabian-hiller commented 1 year ago

Just remove createdDate from dates if you want the value as a string instead of a date.

fabian-hiller commented 1 year ago

Or do you want a Date object and the problem is Invalid Date?

sacrosanctic commented 1 year ago

I want a date object

fabian-hiller commented 1 year ago

Have you tried to remove .getTime()?

sacrosanctic commented 1 year ago

The code above is demonstrating a scenario where the incoming date is a Timestamp.

Since new Date(new Date().getTime()) will work.

Is parsing Timestamp as date outside the scope of this package?

fabian-hiller commented 1 year ago

Isn't Date converted to a string when send to the server via FormData? What should work is new Date().toISOString().

sacrosanctic commented 1 year ago

This was the solution is found for myself as well, I just thought maybe the case where a user uses .getTime() should be handled for better DX.

fabian-hiller commented 1 year ago

Yes, we can add this use case. Do you want to create a PR or should I take care of it? That's the file: https://github.com/fabian-hiller/decode-formdata/blob/main/src/utils/getFieldDate/getFieldDate.ts

sacrosanctic commented 1 year ago

I can do it.