GQLoom

Middleware

Middleware is a function that intervenes in the processing flow of a parsed function. It provides a way to insert logic into the request and response flow to execute code before a response is sent or before a request is processed. GQLoom's middleware follows the onion middleware pattern of Koa.

Define Middleware

Middleware is a function that will be injected with an options object as a parameter when called. The options object contains the following fields:

  • outputSilk: output silk, which includes the output type of the field currently being parsed;
  • parent: the parent node of the current field, equivalent to useResolverPayload().root;
  • parseInput: a function used to obtain the input of the current field;
  • type: the type of the current field, whose value can be query, mutation, subscription, or field;
  • next: a function used to call the next middleware;

The options object can also be directly used as the next function.

Additionally, we can use useContext() and useResolverPayload() to get the context and more information of the current resolver function.

A minimal middleware function is as follows:

import {  } from '@gqloom/core';
 
const :  = async () => {
  return await ();
}

Next, we'll introduce some common types of middleware.

Error catching

When using Valibot or Zod libraries for input validation, we can catch validation errors in the middleware and return customized error messages.

import { type  } from "@gqloom/core"
import {  } from "valibot"
import {  } from "graphql"
 
export const :  = async () => {
  try {
    return await ()
  } catch () {
    if ( instanceof ) {
      const { ,  } = 
      throw new (, { : {  } })
    }
    throw 
  }
}

Validate output

In GQLoom, validation of parser output is not performed by default. However, we can validate the output of parser functions through middleware.

import { , type  } from "@gqloom/core"
 
export const :  = async ({ ,  }) => {
  const  = await ()
  return await .(, )
}

Let's try to use this middleware:

import { , , ,  } from "@gqloom/valibot"
import * as  from "valibot"
import {  } from "node:http"
import {  } from "graphql-yoga"
import { ,  } from "./middlewares"
 
const  = ({
  : (.(.(), .(10)))
    .({ : .() })
    .() 
    .(({  }) => `Hello, ${}`),
})
 
export const  = (, , ) 
 
const  = ({  })
().(4000, () => {
  // eslint-disable-next-line no-console
  .("Server is running on http://localhost:4000/graphql")
})

In the code above, we added the v.minLength(10) requirement to the output of the hello query and added the outputValidator middleware to the parser function. We also added a global middleware ValibotExceptionFilter to weave.

When we make the following query:

GraphQL Query
{
  hello(name: "W")
}

A result similar to the following will be given:

If we adjust the input so that the returned string is the required length:

GraphQL Query
{
  hello(name: "World")
}

It will get a response with no exceptions:

{
  "data": {
    "hello": "Hello, World"
  }
}

Authentication

Checking a user's permissions is a common requirement that we can easily implement with middleware.

Consider that our user has the roles “admin” and “editor”, and we want the administrator and editor to have access to their own actions, respectively. First, we implement an authGuard middleware that checks the user's role:

import { type  } from "@gqloom/core"
import {  } from "./context"
import {  } from "graphql"
 
export function (: "admin" | "editor"):  {
  return async () => {
    const  = await ()
    if ( == null) throw new ("Not authenticated")
    if (!..()) throw new ("Not authorized")
    return ()
  }
}

In the code above, we declare an authGuard middleware that takes a role parameter and returns a middleware function. The middleware function checks that the user is authenticated and has the specified role, and throws a GraphQLError exception if the requirements are not satisfied.

We can apply different middleware for different resolvers:

import { ,  } from "@gqloom/core"
import * as  from "valibot"
import {  } from "./middlewares"
 
const  = (
  {
    : (.(), () => true),
  },
  {
    : [("admin")], 
  }
)
 
const  = (
  {
    : (.(), () => true),
 
    : (.(), () => true),
  },
  { : [("editor")] } 
)

In the code above, we have applied the authGuard middleware to AdminResolver and EditorResolver and assigned different roles to them. In this way, only users with the corresponding roles can access the actions within the corresponding resolvers.

Logging

We can also implement logging functionality through middleware. For example, we can create a logger middleware to log the execution time of each field parsing function:

import { type ,  } from "@gqloom/core"
 
export const :  = async () => {
  const  = ()!.
 
  const  = .()
  const  = await ()
  const  = .() - 
 
  .(`${..}.${.} [${} ms]`)
  return 
}

Using middleware

GQLoom is able to apply middleware in a variety of scopes, including resolver functions, resolver local middleware, and global middleware.

Resolve function middleware

We can use middleware directly in the resolve function by simply passing the middlewares field in the second argument of the operation constructor, for example:

import { ,  } from "@gqloom/core"
import * as  from "valibot"
import {  } from "./middlewares"
 
const  = ({
  : (.(.(), .(10)))
    .({ : .() })
    .() 
    .(({  }) => `Hello, ${}`),
})

Resolver-scoped middleware

We can also apply middleware at the resolver level, which will take effect for all operations within the resolver. Simply pass the middlewares field in the last argument of the resolver constructor, for example:

import { ,  } from "@gqloom/core"
import * as  from "valibot"
import {  } from "./middlewares"
 
const  = (
  {
    : (.(), () => true),
  },
  {
    : [("admin")], 
  }
)
 
const  = (
  {
    : (.(), () => true),
 
    : (.(), () => true),
  },
  { : [("editor")] } 
)

Global middleware

In order to apply global middleware, we need to pass in the middleware fields in the weave function, for example:

import { weave } from "@gqloom/core"
import { exceptionFilter } from "./middlewares"
 
export const schema = weave(helloResolver, exceptionFilter) 

On this page