Skip to content

Commit

Permalink
fix: handle Date when coverting to formData
Browse files Browse the repository at this point in the history
before the fix it converted to empty objects
  • Loading branch information
wojtek-krysiak committed Oct 14, 2020
1 parent 3dd1747 commit 5cdd80d
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 2 deletions.
1 change: 0 additions & 1 deletion src/backend/adapters/record/base-record.ts
@@ -1,4 +1,3 @@
import _ from 'lodash'
import { flat } from '../../../utils/flat'
import { ParamsType } from './params.type'
import BaseResource from '../resource/base-resource'
Expand Down
9 changes: 9 additions & 0 deletions src/frontend/hooks/use-record/record-to-form-data.spec.ts
Expand Up @@ -31,4 +31,13 @@ describe('recordToFormData', function () {

expect(recordToFormData(record).get(propertyKey)).to.equal(FORM_VALUE_EMPTY_ARRAY)
})

it('does not convert date to empty object', async () => {
const date = new Date()
const record = await factory.build<RecordJSON>('RecordJSON', { params: {
[propertyKey]: date,
} })

expect(recordToFormData(record).get(propertyKey)).to.equal(date.toString())
})
})
9 changes: 8 additions & 1 deletion src/frontend/hooks/use-record/record-to-form-data.ts
Expand Up @@ -4,6 +4,12 @@ export const FORM_VALUE_NULL = '__FORM_VALUE_NULL__'
export const FORM_VALUE_EMPTY_OBJECT = '__FORM_VALUE_EMPTY_OBJECT__'
export const FORM_VALUE_EMPTY_ARRAY = '__FORM_VALUE_EMPTY_ARRAY__'

const isObjectOrArray = (value: any): boolean => (
typeof value === 'object'
&& (value as object).constructor !== File
&& !(value instanceof Date)
)

/**
* Changes RecordJSON that it can be send as a FormData to the backend.
*
Expand All @@ -19,14 +25,15 @@ export const FORM_VALUE_EMPTY_ARRAY = '__FORM_VALUE_EMPTY_ARRAY__'
export default function recordToFormData(record: RecordJSON): FormData {
const formData = new FormData()

// Assume that record.params are flatted
Object.entries(record.params).forEach(([key, value]) => {
// {@link updateRecord} does not change empty objects "{}" - so in order to prevent having
// them changed to "[object Object]" we have to set them to empty strings.
if (value === null) {
return formData.set(key, FORM_VALUE_NULL)
}
// File objects has to go through because they are handled by FormData
if (typeof value === 'object' && (value as object).constructor !== File) {
if (isObjectOrArray(value)) {
if (Array.isArray(value)) {
return formData.set(key, FORM_VALUE_EMPTY_ARRAY)
}
Expand Down
1 change: 1 addition & 0 deletions src/utils/flat/flat.types.ts
Expand Up @@ -7,6 +7,7 @@
export type FlattenValue = 'string' |
'boolean' |
'number' |
Date |
null |
[] |
{} |
Expand Down

0 comments on commit 5cdd80d

Please sign in to comment.