New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

fuse

Package Overview
Dependencies
Maintainers
2
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fuse

The magical GraphQL framework

  • 0.7.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4.1K
decreased by-5.44%
Maintainers
2
Weekly downloads
 
Created
Source

Fuse.js

Fuse.js: End-to-end typesafe data fetching for frontend teams at scale

Getting Started

Before you begin

Before you start using Fuse.js, you need to have:

  • Familiarity with TypeScript
  • A Next.js app*

*Note that a Fuse.js data layer can also be developed and deployed outside of Next.js. However, our current focus is on making the experience with Next.js great, so expect rough edges elsewhere.

Setting up your Fuse data layer

Install the npm packages

npm install --save fuse graphql
npm install --save-dev @graphql-typed-document-node/core

Add the Next.js plugin to your next.config.js

const { nextFusePlugin } = require('fuse/next/plugin')

/** @type {import('next').NextConfig} */
const nextConfig = nextFusePlugin()({
  // Your Next.js config here
})

module.exports = nextConfig

Create the /api/fuse API route

This API route will serve as the entrypoint to the GraphQL API that Fuse.js creates. If you are using Next.js’s app router, add a file at app/api/fuse/route.ts and copy the below code to it:

import { createAPIRouteHandler } from 'fuse/next'

// NOTE: This makes Fuse.js automatically pick up every type in the /types folder
// Alternatively, you can manually import each type in the /types folder and remove this snippet
// @ts-expect-error
const files = require.context('../../../types', true, /\.ts$/)
files
  .keys()
  .filter((path: string) => path.includes('types/'))
  .forEach(files)

const handler = createAPIRouteHandler()

export const GET = handler
export const POST = handler

Add 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
  avatarUrl: string
}

// "Nodes" are the core abstraction of Fuse.js. 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'),
    // 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}`,
    avatarUrl: `https://i.pravatar.cc/300?u=${id}`,
  }))
}

That’s it! Fuse.js will now serve a GraphQL API at /api/fuse.

Querying your data layer

import { graphql } from '@/fuse'
import { execute } from '@/fuse/server'

const UserQuery = graphql(`
  query User($id: ID!) {
    user(id: $id) {
      id
      name
      firstName
      avatarUrl
    }
  }
`)

export default async function Page() {
  const result = await execute({
    query: UserQuery,
    variables: { id: '1' },
  })
}

Adding in-line hints and validation

You can use @0no-co/graphqlsp to get inline hints while authoring GraphQL documents, you can do so by installing it 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"
}

FAQs

Package last updated on 06 Dec 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc