gProxy 是 SvelteKit 的 GraphSQL 客户端和缓存扩展包。
安装:
npm install --save @leveluptuts/g-query graphql-tag
初始化:
// src/lib/config/g.ts
export const g = new GFetch({
path: 'https://yourapiurl.com/graphql' //whatever your api url is here
// More config options coming, for now this is just path to your graphql api
});
添加代码生成器:
// svelte.config.js
import gQueryCodegen from '@leveluptuts/g-query/codegen'
...
vite: {
plugins: [
gQueryCodegen({
// Required
// schema: 'http://localhost:3001/graphql' // this can also be a url to a graphql api
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.
// Optional
debug: false // boolean, this adds logging for gq files deleted and on codegen
})
],
}
添加 GraphSQL 文件:
// UserQueries.graphql
query currentUser {
user {
_id
}
}
使用:
<script context="module" lang="ts">
// The generated function that fetches and caches
import { getCurrentUser } from './UserQueries.gq';
export async function load({ fetch }) {
// Runs the cache/fetch function populating $currentUser before use.
await getCurrentUser({
variables: { limit: 0 },
fetch // Don't forget to pass fetch for ssr
});
return {};
}
</script>
<script lang="ts">
// Cache becomes populated with data available for SSR
import { user } from './UserQueries.gq';
// $: console.log($user.user) //data available for ssr
</script>
评论