Documentation
Building your API (server)
Integrating data sources
Drizzle

Integrating Drizzle with Fuse

Drizzle ORM (opens in a new tab) is an option to access SQL databases in a type-safe way in Node.js. Fetching data from an SQL database with Drizzle in Fuse allows you to avoid having to type any underlying source type.

Getting the TypeScript types for a table

For example, given a drizzle schema with a users table:

import { drizzle } from 'drizzle-orm/postgres-js';
import { pgTable, text, varchar } from 'drizzle-orm/pg-core';
 
export const users = pgTable('users', {
  id: text('id').primaryKey(),
  name: varchar('name', { length: 256 }),
});
 
export const db = drizzle({})

We can create a UserNode without having to manually type the shape of the users table by using typeof users.$inferInsert:

import { node, NotFoundError, addQueryFields } from 'fuse'
import { inArray, sql } from 'drizzle-orm';
import { db, users } from './db'
 
// `typeof users.$inferInsert` gives us a TypeScript type that matches the underlying database schema
export const UserNode = node<typeof users.$inferInsert>({
  name: 'User',
  async load(ids) {
    // Query for the list of users with the `ids`
    const result = await db.select().from(users).where(inArray(users.id, ids))
    return ids.map((id) => result.find((x) => x.id === id) || new NotFoundError('Could not find user.'));
  },
  fields: (t) => ({
    name: t.exposeString('name'),
  }),
})

Paginated lists

Creating a paginated list with t.list requires returning both the list of nodes and the total count of nodes. Here is what that would look like with Drizzle;

addQueryFields((t) => ({
  users: t.list({
    type: UserNode,
    nullable: false,
    args: {
      offset: t.arg.int(),
      limit: t.arg.int(),
    },
    resolve: async (_, args) => {
      const offset = args.offset || 0
      const limit = args.limit || 10
 
      const [totalCount, paginatedUsers] = await Promise.all([
        // Get the total count of users as an int
        db.select({
          count: sql<number>`cast(count() as int)`,
        }).from(users),
        // Get the list of users based on the limit and offset
        db.select().from(users).limit(limit).offset(offset)
      ])
 
      return {
        nodes: paginatedUsers,
        totalCount: totalCount[0].count,
      }
    },
  }),
}))