#How to initialise a database client for it to be accessible throughout the app?

4 messages · Page 1 of 1 (latest)

keen ferry
#

I have been trying to initialise a database client and from what I can tell, it has to be done either in the root index or a layout.tsx that wraps where the database will be accessed. I've chosen to do so in layout.tsx.

// layout.tsx
export const getDBClient = routeLoader$(async ({ platform }) => {
  let instance: DBClient | undefined = undefined;

  if (instance) return instance;

  instance = noSerialize(
    await new DBClient({
      apiKey: platform?.env?.DB_API_KEY
    })
  );
});

export default component$(() => <><Slot/></>);

and then in a component that will be within layout.tsx:

export default component$(async () => {
  const res = await getDBClient().value.getSomeValue();
  return <p>{res}</p>
})

From what I can tell, this seems to work, but TypeScript isn't happy about it, giving the following error:

Argument of type '() => Promise<JSX.Element>' is not assignable to parameter of type 'OnRenderFn<{}>'.
  Type 'Promise<Element>' is missing the following properties from type 'JSXNode<any>': type, props, immutableProps, children, and 2 more.ts(2345)

Is there a way to fix this error? I'm looking at this page in the docs (https://qwik.builder.io/docs/advanced/eslint/) and there are multiple examples showing component$ wrapping an async function, so I'm not sure what I'm doing wrong.

keen ferry
#

So I tried deploying the existing code to Cloudflare and it the component$ wrapping the async function doesn't actually work. So how else can I initialise a database client in a way that is accessible throughout the app?

#

How to initialise a database client for it to be accessible throughout the app?

hallow lily
#

Probably it's not important, but generally it's a convention to name variables as use* on routeLouders.
https://qwik.builder.io/docs/route-loader/#routeloader

However, your code of getDBClient is just not correct.
Try

export const useDBClient = routeLoader$(async ({ platform }) => {
  return noSerialize(
    await new DBClient({
      apiKey: platform?.env?.DB_API_KEY
    })
  );
});