ciscoheat / sveltekit-superforms

Making SvelteKit forms a pleasure to use!
https://superforms.rocks
MIT License
2.12k stars 62 forks source link

How to construct a schema dynamically? #453

Closed sheldonbaker closed 3 weeks ago

sheldonbaker commented 1 month ago

I'd like to have a schema with validations that are dependent on a remote data source, but schemas must be defined outside a load function for caching purposes.

const minLength = 17 // I'd instead like to define this in the load function based on the results of an async api call

// Define outside the load function so the adapter can be cached
const schema = z.object({
  name: z.string().default('Hello world!').min(minLength),
  email: z.string().email()
});

export const load = (async (event) => {
  const properMinLength = await getMinLengthAllowanceForUser(event)

  const form = await superValidate(zod(schema)); // can't pass `properMinLength` to an already defined schema

  // Always return { form } in load functions
  return { form };
});

What's the best way to accomplish this use case? Would it just be to have another schema that extends from the main schema and I additionally superValidate that in my form action?

ciscoheat commented 1 month ago

Try it without caching first, i.e. create the schema dynamically in the load function, most likely the difference in speed in negligible.

If you need caching, you can cache the schemas yourself, for example with a lru-cache or ttl-cache. As long as it stays in memory, it will be re-used by the memoize function when the adapter is created.