Setting up Fuse manually
These steps are the same as what create-fuse-app
does under the hood, we'll
go over them so you know what the command does.
Setup
Install the npm packages
npm install --save fuse graphql
npm install --save-dev @graphql-typed-document-node/core
Adding your first type
Create a types
folder at the root of your Next.js app and add a file at types/User.ts
that contains the following code:
import { node } from 'fuse'
type UserSource = {
id: string
name: string
avatar_url: string
}
// "Nodes" are the core abstraction of Fuse. Each node represents
// a resource/entity with multiple fields and has to define two things:
// 1. load(): How to fetch from the underlying data source
// 2. fields: What fields should be exposed and added for clients
export const UserNode = node<UserSource>({
name: 'User',
load: async (ids) => getUsers(ids),
fields: (t) => ({
name: t.exposeString('name'),
// rename to camel-case
avatarUrl: t.exposeString('avatar_url'),
// Add an additional firstName field
firstName: t.string({
resolve: (user) => user.name.split(' ')[0],
}),
}),
})
// Fake function to fetch users. In real applications, this would
// talk to an underlying REST API/gRPC service/third-party API/…
async function getUsers(ids: string[]): Promise<UserSource[]> {
return ids.map((id) => ({
id,
name: `Peter #${id}`,
avatar_url: `https://i.pravatar.cc/300?u=${id}`,
}))
}
Note how the only code you had to write was the translation from the underlying data source to the shape of the data that you need. Fuse takes care of everything else for you.
Set up GraphQLSP to get IDE autocomplete
You can use @0no-co/graphqlsp
to get inline hints while authoring GraphQL documents, you can do so by installing it
with npm i --save-dev @0no-co/graphqlsp
and using the following in your tsconfig.json
:
{
"name": "@0no-co/graphqlsp",
"schema": "./schema.graphql",
"disableTypegen": true,
"templateIsCallExpression": true,
"template": "graphql"
}
When using .vscode
you will need to use the workspace version of TypeScript, to do so you can easily do that by creating
.vscode/settings.json
with the following content
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}