spences10 / sveltekit-with-urql

An example of using URQL with SvelteKit
https://sveltekit-with-urql.vercel.app/
8 stars 2 forks source link

URQL for mutations? #106

Open chornbec opened 1 year ago

chornbec commented 1 year ago

Hello! This example repo is helpful in understanding how to execute GraphQL queries using urql in a Sveltekit project, but for the life of me I can't find an example of executing GraphQL mutations. It seems like the @urql/svelte library assumes you'll only be executing client-side mutations instead of server-side (i.e. within +page.server.js files). If you want to submit a form, for example, Sveltekit highly recommends Form Actions, which require using *.server.js files. However, server files don't have access to Context, which urql mutations use; I get an error when calling getContextClient from @urql/svelte within a +page.server.js, which makes sense.

Any ideas on using urql mutationStore in server files? Am I missing something?

spences10 commented 1 year ago

Hey @chornbec, great question! It looks like you're right in your presumption here as well.

URQL is a client (browser) side package, if you want to do server side maybe take a look at KitQL

chornbec commented 1 year ago

URQL also has Node bindings. Would it make sense to use those bindings in *.server.js files with Sveltekit? I got the code snippet below to work, but wouldn't it create a new Context instance for each Vite server request? I can imagine that'd be costly.

import { createClient } from '@urql/svelte';
import * as gql from "$lib/generated/graphql"

interface UpdateBuildingFormData {
  data: gql.BuildingUpdateInput,
  where: gql.BuildingWhereUniqueInput,
}

const client = createClient({
  url: "http://localhost:4000/graphql"
})

/** @type {import('./$types').Actions} */
export const actions = {
  // Take form data and process GraphQL mutation.
  default: async ({ cookies, request, url }: any) => {
    let output;
    let data = await request.formData()

    client.mutation(gql.UpdateBuildingDocument, {data: {street_address_1: {set: "hello"}}, where: {id: "eb52a6bb-fa8f-4994-8fbe-1dd76e4369d7"}})
      .toPromise()
      .then((result) => {
        console.log("result: ", result)
      })
  }
}
spences10 commented 1 year ago

🤔

Maybe you could check if the client is already instantiated before creating a new one, or use hooks.server.js to do something similar??