Skip to content

Commit 12e400a

Browse files
committed
dataType json now handles large payloads.
1 parent cef4fe9 commit 12e400a

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1515

1616
- The rarely used `update` function is removed. Use `form` instead, which now has an option for not tainting the affected fields.
1717

18+
### Fixed
19+
20+
- `dataType: 'json'` now handles large (+1Mb) payloads.
21+
1822
### Added
1923

2024
- Added `validate` to `superForm`, which can be used to validate any field, at any time.

src/lib/client/index.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1394,7 +1394,11 @@ function formEnhance<T extends AnyZodObject, M>(
13941394
setTimeout(() => validationResponse({ result }), 0);
13951395
} else if (options.dataType === 'json') {
13961396
const postData = get(data);
1397-
submit.data.set('__superform_json', stringify(postData));
1397+
const chunks = chunkSubstr(stringify(postData), 500000);
1398+
1399+
for (const chunk of chunks) {
1400+
submit.data.append('__superform_json', chunk);
1401+
}
13981402

13991403
// Clear post data to reduce transfer size,
14001404
// since $form should be serialized and sent as json.
@@ -1408,6 +1412,18 @@ function formEnhance<T extends AnyZodObject, M>(
14081412
}
14091413
}
14101414

1415+
// Thanks to https://stackoverflow.com/a/29202760/70894
1416+
function chunkSubstr(str: string, size: number) {
1417+
const numChunks = Math.ceil(str.length / size);
1418+
const chunks = new Array(numChunks);
1419+
1420+
for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
1421+
chunks[i] = str.substring(o, o + size);
1422+
}
1423+
1424+
return chunks;
1425+
}
1426+
14111427
async function validationResponse(event: ValidationResponse) {
14121428
const result = event.result;
14131429

src/lib/validate.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -299,9 +299,7 @@ export async function superValidate<
299299
function tryParseSuperJson(data: FormData) {
300300
if (data.has('__superform_json')) {
301301
try {
302-
const output = parse(
303-
data.get('__superform_json')?.toString() ?? ''
304-
);
302+
const output = parse(data.getAll('__superform_json').join() ?? '');
305303
if (typeof output === 'object') {
306304
return output as Record<string, unknown>;
307305
}

0 commit comments

Comments
 (0)