GQLoom

Drizzle

Drizzle is a modern, type-safe TypeScript ORM designed for Node.js. It offers a concise and easy-to-use API, supports databases such as PostgreSQL, MySQL, and SQLite, and has powerful query builders, transaction processing, and database migration capabilities. At the same time, it remains lightweight and has no external dependencies, making it very suitable for database operation scenarios that require high performance and type safety.

@gqloom/drizzle provides the integration of GQLoom and Drizzle:

  • Use Drizzle Table as Silk;
  • Use the resolver factory to quickly create CRUD operations from Drizzle.

Installation

Please refer to Drizzle's Getting Started Guide to install Drizzle and the corresponding database integration.

After completing the installation of Drizzle, install @gqloom/drizzle:

npm i @gqloom/core @gqloom/drizzle

Using Silk

We can easily use Drizzle Schemas as Silk by simply wrapping them with drizzleSilk.

schema.ts
import {  } from "@gqloom/drizzle"
import {  } from "drizzle-orm"
import * as  from "drizzle-orm/sqlite-core"
 
export const  = (
  .("users", {
    : .().({ : true }),
    : .().(),
    : .(),
    : .(),
    : .(),
  })
)
 
export const  = (, ({  }) => ({
  : (),
}))
 
export const  = (
  .("posts", {
    : .().({ : true }),
    : .().(),
    : .(),
    : .().(() => ., { : "cascade" }),
  })
)
 
export const  = (, ({  }) => ({
  : (, {
    : [.],
    : [.],
  }),
}))

Let's use them in the resolver:

resolver.ts
import {
  ,
  ,
  ,
  ,
  ,
} from "@gqloom/core"
import { ,  } from "drizzle-orm"
import {  } from "drizzle-orm/libsql"
import * as  from "valibot"
import * as  from "./schema"
import { ,  } from "./schema"
 
const  = ({
  ,
  : { : ..! },
})
 
const  = (
  () =>
    new <
      typeof .,
      (typeof .)[]
    >(async () => {
      const  = await 
        .()
        .()
        .(
          (
            .,
            .(() => .)
          )
        )
      const  = new <number, (typeof .)[]>()
 
      for (const  of ) {
        const  = .
        if ( == null) continue
        .(, [...(.() ?? []), ])
      }
      return .(() => .(.) ?? [])
    })
)
 
export const  = .(, {
  : 
    .(.())
    .({ : .() })
    .(({  }) => {
      return .().().((., )).()
    }),
 
  : .(.()).(() => {
    return .().().()
  }),
 
  : .(.()).(() => {
    return ().()
  }),
})

As shown in the above code, we can directly use the Drizzle Schemas wrapped by drizzleSilk in the resolver. Here we use users as the parent type of resolver.of, and define two queries user and users and a field named posts in the resolver. The return type of user is users.$nullable(), indicating that user may be empty; the return type of users is users.$list(), indicating that users will return a list of users; the return type of the posts field is posts.$list(). In the posts field, we use the user parameter, and TypeScript will help us infer its type. We pass user to usePostsLoader().load() to batch fetch posts.

Hiding Fields

Sometimes we don't want to expose all fields of the database table to the client. Consider that we have a users table containing a password field, where the password field is an encrypted password, and we don't want to expose it to the client:

schema.ts
import {  } from "@gqloom/drizzle"
import * as  from "drizzle-orm/sqlite-core"
 
export const  = (
  .("users", {
    : .().({ : true }),
    : .().(),
    : .(),
    : .(),
    : .(),
  })
)

We can use field.hidden in the resolver to hide the password field:

resolver.ts
import { ,  } from "@gqloom/core"
import {  } from "./schema"
 
export const  = .(, {
  : .,
})

Resolver Factory

gqloom/drizzle provides a resolver factory DrizzleResolverFactory to easily create CRUD resolvers from Drizzle, and it also supports custom parameters and adding middleware.

resolver.ts
import {  } from "@gqloom/drizzle"
import {  } from "drizzle-orm/libsql"
import * as  from "./schema"
 
const  = ({
  ,
  : { : ..! },
})
 
const  = (, "users")

Relationship Fields

In Drizzle Table, we can easily create relationships. We can use the relationField method of the resolver factory to create corresponding GraphQL fields for relationships.

resolver.ts
import { ,  } from "@gqloom/core"
import {  } from "@gqloom/drizzle"
import { ,  } from "drizzle-orm"
import {  } from "drizzle-orm/libsql"
import * as  from "valibot"
import * as  from "./schema"
import {  } from "./schema"
 
const  = ({
  ,
  : { : ..! },
})
 
const  = (, "users")
 
const  = ( 
  () =>
    new <
      typeof ., 
      (typeof .)[] 
    >(async () => { 
      const  = await  
        .() 
        .() 
        .( 
          ( 
            ., 
            .(() => .) 
          ) 
        ) 
      const  = new <number, (typeof .)[]>() 

      for (const  of ) { 
        const  = . 
        if ( == null) continue
        .(, [...(.() ?? []), ]) 
      } 
      return .(() => .(.) ?? []) 
    }) 
) 
 
export const  = .(, {
  : 
    .(.())
    .({ : .() })
    .(({  }) => {
      return .().().((., )).()
    }),
 
  : .(.()).(() => {
    return .().().()
  }),
 
  : .(.()).(() => { 
    return ().() 
  }), 
 
  : .("posts"), 
})

Queries

The Drizzle resolver factory predefines some commonly used queries:

  • selectArrayQuery: Find multiple records in the corresponding table according to the conditions.
  • selectSingleQuery: Find a single record in the corresponding table according to the conditions.

We can use the queries from the resolver factory in the resolver:

export const  = .(, {
  :  
    .(.()) 
    .({ : .() }) 
    .(({  }) => { 
      return .().().((., )).() 
    }), 
 
  : .(), 
 
  : .(.()).(() => { 
    return .().().() 
  }), 
 
  : .(), 
 
  : .("posts"), 
})

Mutations

The Drizzle resolver factory predefines some commonly used mutations:

  • insertArrayMutation: Insert multiple records.
  • insertSingleMutation: Insert a single record.
  • updateMutation: Update records.
  • deleteMutation: Delete records.

We can use the mutations from the resolver factory in the resolver:

export const  = .(, {
  : .(),
 
  : .(),
 
  : .(), 
 
  : .(), 
 
  : .("posts"),
})

Custom Input

The pre-defined queries and mutations of the resolver factory support custom input. You can define the input type through the input option:

export const  = .(, {
  : .({
    : .( 
      .({ : .() }), 
      .(({  }) => ({ : (., ) })) 
    ), 
  }), 
 
  : .(),
 
  : .("posts"),
})

In the above code, we use valibot to define the input type. v.object({ id: v.number() }) defines the type of the input object, and v.transform(({ id }) => ({ where: eq(users.id, id) })) converts the input parameters into Prisma query parameters.

Adding Middleware

The pre-defined queries, mutations, and fields of the resolver factory support adding middleware. You can define middleware through the middlewares option:

const  = .(, {
  : .({
    : [
      async () => {
        const  = await ()
        if ( == null) throw new ("Please login first")
        return ()
      },
    ],
  }),
 
  : .("author"),
 
  : .,
})

In the above code, we use the middlewares option to define middleware. async (next) => { ... } defines a middleware. useAuthedUser() is a custom function used to get the currently logged-in user. If the user is not logged in, an error is thrown; otherwise, next() is called to continue execution.

Complete Resolver

We can directly create a complete Resolver with the resolver factory:

const  = .()

In the above code, we use usersResolverFactory.resolver() to create a Resolver. This Resolver will include all queries, mutations, and fields in the factory.

Custom Type Mapping

To adapt to more Drizzle types, we can extend GQLoom to add more type mappings.

First, we use DrizzleWeaver.config to define the configuration of type mapping. Here we import GraphQLDateTime and GraphQLJSONObject from graphql-scalars. When encountering date and json types, we map them to the corresponding GraphQL scalars.

import { ,  } from "graphql-scalars"
import {  } from "@gqloom/drizzle"
 
const  = .({
  : () => {
    if (. === "date") {
      return 
    }
    if (. === "json") {
      return 
    }
  },
})

Pass the configuration to the weave function when weaving the GraphQL Schema:

import { weave } from "@gqloom/core"
 
export const schema = weave(drizzleWeaverConfig, usersResolver, postsResolver)

Default Type Mapping

The following table lists the default mapping relationships between Drizzle dataType and GraphQL types in GQLoom:

Drizzle dataTypeGraphQL Type
booleanGraphQLBoolean
numberGraphQLFloat
jsonGraphQLString
dateGraphQLString
bigintGraphQLString
stringGraphQLString
bufferGraphQLList
arrayGraphQLList

On this page