Hook for initialization?
See original GitHub issueIs your feature request related to a problem? Please describe. It should be pretty common for a svelt kit app to utilize external services that you need to initialize clients to talk to them. The doc demonstrates such use case:
import db from '$lib/database';
export async function get({ params }) {
const { slug } = params;
const article = await db.get(slug);
// ...
}
One issue with this code is that it assumes db
can be initialized in the module itself either synchronously (which is not always the case) or via top-level await
(which svelte kit doesn’t seem to support).
Describe the solution you’d like
Offer a hook like async func init() {}
that only runs once when it starts?
Describe alternatives you’ve considered
How important is this feature to you? Very, since it’s pretty awkward to workaround when the initialization is async (e.g., force initialization to be synchronous and only call the async part when actually talk to external services).
Additional context
Issue Analytics
- State:
- Created 2 years ago
- Reactions:14
- Comments:25 (21 by maintainers)
Top GitHub Comments
Here’s an approach I just thought of.
Create a store in a separate module, say
urqlclient.ts
. It would look like this:Then when you need an URQL client, get it from the store via
$urqlclient
. The first time any piece of your code subscribes to this store, thereadable
’s initialization function will be called. Since it callsset
before returning, the first subscriber will receive a non-null value. If that first subscriber unsubscribes before a second subscriber asks for a client, the initialization function will be called again, but the second time it will simply return the cached value ofclient
and not callinitClient
a second time.This will allow the rest of your code to just do
import { urqlclient } from '$lib/urqlclient.ts'
and then use$urqlclient
knowing that that value will be a properly-configured client.Top-level await was broken in Vite at the time of https://github.com/sveltejs/kit/issues/1538#issue-899375025, but is since fixed, which means this problem is very easily solved — you can do your setup work in
hooks.js
……or if that feels weird you can do it in a module that’s imported by any endpoints that need it:
The latter technique also applies to clients that are needed by pages, like Urql. Demo here.
Given all this, is a dedicated initialization hook necessary?