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 its corresponding database integration.

After installing Drizzle, install @gqloom/drizzle:

npm i @gqloom/core @drizzle-orm@beta @gqloom/drizzle@beta

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. At the same time, we use the useSelectedColumns() function to know which columns are needed for the current GraphQL query:

resolver.ts
import { , ,  } from "@gqloom/core"
import {  } from "@gqloom/drizzle/context"
import { ,  } from "drizzle-orm"
import {  } from "drizzle-orm/libsql"
import * as  from "valibot"
import * as  from "./schema"
import { ,  } from "./schema"

const  = ({
  ,
  : { : ..! },
})

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

  : .(.()).(() => {
    return .(()).().()
  }),

  : 
    .(.())
    .("id")
    .(async () => {
      const  = await 
        .()
        .()
        .(
          (
            .,
            .(() => .)
          )
        )
      const  = new <number, (typeof .)[]>()

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

As shown in the code above, we can directly use the Drizzle Table wrapped by drizzleSilk in the resolver. Here, we use users as the parent type of resolver.of, and define two queries named user and users and a field named posts in the resolver. Among them:

  • The return type of user is users.$nullable(), indicating that user may be null;
  • 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 userList parameter in the load method. TypeScript will help us infer its type. The load method is a wrapper of DataLoader, allowing us to quickly define a DataLoader method and use it to batch fetch posts.

We also use the useSelectedColumns() function to determine which columns need to be selected for the current GraphQL query. This function requires enabling context.
For runtimes where the useSelectedColumns() function cannot be used, we can also use the getSelectedColumns() function to obtain the columns that need to be selected for the current query.

Derived Fields

Adding derived Fields to a database table is quite simple. However, it's important to use the field().derivedFrom() method to declare the columns on which the computed property depends, so that the useSelectedColumns method can correctly select these columns:

schema.ts
import { ,  } from "@gqloom/core"
import * as  from "valibot"
import {  } from "./schema"

export const  = .(, {
  : (.())
    .("title", "content")
    .(() => {
      return `${.} ${.?.(0, 60)}...`
    }),
})

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 { drizzleResolverFactory } from "@gqloom/drizzle"
import { drizzle } from "drizzle-orm/libsql"
import { users } from "./schema"

const db = drizzle({
  connection: { url: process.env.DB_FILE_NAME! },
})

const usersResolverFactory = drizzleResolverFactory(db, 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  = (, )

const  = ( 
  () =>
    new <
      { : number }, 
      (typeof .)[] 
    >(async () => { 
      const  = await  
        .() 
        .() 
        .( 
          ( 
            ., 
            .(() => .) 
          ) 
        ) 
      const  = new <number, (typeof .)[]>() 
      for (const  of ) { 
        const  = . 
        if ( == null) continue
        .(, [...(.() ?? []), ]) 
      } 
      return .(() => .(.) ?? []) 
    }) 
) 
 
export const  = .(, {
  : 
    .(.())
    .({ : .() })
    .(({  }) => {
      return .().().((., )).()
    }),

  : .(.()).(() => {
    return .().().()
  }),

  : .(.()) 
    .('id') 
    .(() => { 
      return ().() 
    }), 

  : .("posts"), 
})

Queries

The Drizzle resolver factory pre-defines 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.
  • countQuery: Count the number of records 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 Drizzle 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:

// Readonly Resolver
const  = .()

// Full Resolver
const  = .()

There are two functions for creating Resolvers:

  • usersResolverFactory.queriesResolver(): Creates a Resolver that only includes queries and relational fields.
  • usersResolverFactory.resolver(): Creates a Resolver that includes all queries, mutations, and relational fields.

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