Skip to content

Commit

Permalink
fix: 🐛 simplify isObject to better handle svelte 5 $state
Browse files Browse the repository at this point in the history
  • Loading branch information
beynar committed Mar 27, 2024
1 parent 57cd0cc commit 946439f
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 19 deletions.
9 changes: 7 additions & 2 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createRPCHandle, procedure, stream } from '$lib/server.js';
import type { Router } from '$lib/types.js';
import { sequence } from '@sveltejs/kit/hooks';
import { date, object, string } from 'valibot';
import { date, object, string, array } from 'valibot';
import OpenAI from 'openai';
import { PRIVATE_OPEN_API_KEY } from '$env/static/private';
import { z } from 'zod';
Expand Down Expand Up @@ -69,8 +69,13 @@ const router = {
.handle(async () => {
return { result: undefined };
}),
test2: procedure()
object: procedure()
.input(object({ test: string(), image: date() }))
.handle(async () => {
return { data: true };
}),
array: procedure()
.input(array(object({ test: string(), image: date() })))
.handle(async () => {
return { data: true };
})
Expand Down
1 change: 1 addition & 0 deletions src/lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ export class Handler<
);
}
} else if (isVali(this.#schema)) {
console.log(formDataToObject(data));
const { output, issues } = this.#schema._parse(formDataToObject(data));
if (issues) {
error(
Expand Down
23 changes: 8 additions & 15 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
const isSvelteState = (value: unknown) =>
Object.getOwnPropertySymbols(value).some((s) => s.toString() === 'Symbol($state)');
const isObject = (value: unknown) =>
value &&
typeof value === 'object' &&
value.constructor === Object &&
!Array.isArray(value) &&
typeof value !== 'function' &&
!(value instanceof Date);

const isArray = (value: unknown): value is Array<unknown> => Array.isArray(value);
const isBlob = (value: unknown): value is Blob => value instanceof Blob;
const isFile = (value: unknown): value is File => value instanceof File;
Expand Down Expand Up @@ -38,10 +34,6 @@ const TYPES_MAP = new Map<string, string>(
const REVERSE_TYPES_MAP = new Map<string, string>([...TYPES_MAP].map(([a, b]) => [b, a]));

const processFormData = (value: any, formData: FormData, parent?: string) => {
if (isSvelteState(value)) {
value = Object.assign({}, value);
}

const processedKey = parent || '';
const type = isDate(value)
? 'date'
Expand All @@ -64,12 +56,15 @@ const processFormData = (value: any, formData: FormData, parent?: string) => {
: isNumber(value)
? 'number'
: undefined;

console.log({ type });
if (type) {
const typeIndex = TYPES_MAP.get(type);
if (type === 'string' || type === 'number' || type === 'boolean') {
formData.append(`${typeIndex}:${processedKey}`, String(value));
} else if (type === 'object') {
const entries = Object.entries(value);
console.log({ entries });
if (entries.length === 0) {
formData.append(`${typeIndex}:${processedKey}`, '{}');
} else {
Expand All @@ -95,13 +90,11 @@ const processFormData = (value: any, formData: FormData, parent?: string) => {
}
};

export const objectToFormData = (payload: object, formData: FormData = new FormData()) => {
if (payload === undefined) return formData;

processFormData(
!isObject(payload) && !isSvelteState(payload) ? { '######ROOT######': payload } : payload,
formData
);
export const objectToFormData = (data: unknown, formData: FormData = new FormData()) => {
// const isSvelte5State = isSvelteState(data);
// console.log({ isSvelte5State }, isArray(data[stateSymbol(data)].t), data[stateSymbol(data)].t);
if (data === undefined) return formData;
processFormData(!isObject(data) ? { '######ROOT######': data } : data, formData);
return formData;
};

Expand Down
26 changes: 24 additions & 2 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,17 @@
image: new Date(),
test: 'st'
});
let array = $state([
{
image: new Date(),
test: 'st'
}
]);
const test = async () => {
type ReturnType = InferRPCReturnType<'route'>;
type Payload = InferRPCInput<'test.test2'>;
const res = await api.test.test(st).then((res) => {
const res = await api.test.test2(object).then((res) => {
console.log(res);
return res;
});
Expand All @@ -25,7 +31,23 @@
};
</script>

<button on:click={test}> test </button>
{object.test}
<button
on:click={async () => {
const res = await api.test.object(object);
console.log(res);
}}
>
object
</button>
<button
on:click={async () => {
const res = await api.test.array(array);
console.log(res);
}}
>
array
</button>
<button on:click={testError}> testError </button>
<h1>Welcome to your library project</h1>
<p>Create your package using @sveltejs/package and preview/showcase your work with SvelteKit</p>
Expand Down

0 comments on commit 946439f

Please # to comment.