gQuery/README.md

112 lines
2.3 KiB
Markdown
Raw Normal View History

2021-09-29 18:13:11 +00:00
![gQuery](./gQuery.png)
2021-09-29 17:02:01 +00:00
# qQuery
2021-09-29 17:11:21 +00:00
## Not like jQuery. A GraphQL Fetcher & Cache for Svelte Kit
### UnderConstruction.gif
More information in this space soon. API is very much in flux rn.
### Preview
2021-09-29 18:13:11 +00:00
### 1. Initialize G
```
export const g = new GFetch({
path: Environment.apiURL //whatever your api url is here
})
```
### 2. Add GraphQL Codegen Plugin
```
svelte.config.js
import gQueryCodegen from '@leveluptuts/g-query/codegen'
...
plugins: [
gQueryCodegen({
schema: './src/lib/graphql/schema.graphql', // path to schema, schema is required
output: './src/lib/graphql', // Where you want the general schema types to output
gPath: '$lib/config/g' //Path to g, created in step 1.
})
],
...
```
### 3. Add .graphql files
2021-09-29 18:13:11 +00:00
```
UserQueries.graphql
query user {
user {
_id
}
}
2021-09-29 18:13:11 +00:00
```
2021-09-29 18:13:11 +00:00
### 4. Use that thang
The code gen will find the file and spit out a file next to it. Named `FileName.gGenerated.ts`
Using the above code, it would output `UserQueries.gGenerated.ts`
This also gives us a `get` function for queries based on the query name. ie `getUser` for the above.
2021-10-22 15:34:45 +00:00
```javascript
2021-09-29 18:13:11 +00:00
<script context="module" lang="ts">
2021-09-30 16:19:53 +00:00
// The generated function that fetches and caches
2021-10-22 15:32:33 +00:00
import { getUser } from './UserQueries.gGenerated.graphql'
2021-09-29 18:13:11 +00:00
export async function load({fetch}) {
2021-09-30 16:19:53 +00:00
// Runs the cache/fetch function populating $gCache before use.
await getUser({
variables: { limit: 0 },
fetch
2021-09-29 18:13:11 +00:00
})
return {}
}
</script>
<script lang="ts">
2021-09-30 16:19:53 +00:00
// Cache becomes populated with data available for SSR
import { user } from './UserQueries.gGenerated.graphql'
2021-09-29 18:13:11 +00:00
// $: console.log($user) //data available for ssr
2021-09-29 18:13:11 +00:00
</script>
```
## FAQ / WTF
### Q? How tf do I update the cache?
It's a Svelte Writable Store. So after a mutation you can quickly and easily manually update the cache.
2021-10-22 15:32:33 +00:00
```
import { user, someMutation } from './UserQueries.gGenerated.graphql'
$user = null // clears the cache
$user = await someMutation({ variables }) // if this returns the correct data
```
2021-09-30 16:19:53 +00:00
### Q? Can't you update the cache magically for me after a mutation?
2021-09-29 18:13:11 +00:00
2021-10-22 15:32:33 +00:00
Maybe? If you want to be in charge of writing that bit, the door is open 😼. My idea for the api would look something like this.
```
import { user, someMutation } from './UserQueries.gGenerated.graphql'
await someMutation({ variables, store: user })
```
2021-09-30 16:19:53 +00:00
### Q? Why can't I use this yet?
2021-10-22 15:32:33 +00:00
IT'S GETTING CLOSER