npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@graphql-directive/core

v1.0.2

Published

GraphQL directive core functions

Downloads

149

Readme

GraphQL Directive Core Functions

Node.js CI Coverage Status

Provides reusable functions for adding directive functionality to a GraphQL schema using schema transformation. It contains basic building blocks that can be used by other packages to easily incorporate directive functionality into their own GraphQL schemas. With this library, developers can easily define custom directives with specific functionality, such as authorization or caching, and seamlessly integrate them into their GraphQL schema. This library is designed to streamline the process of working with GraphQL directives, making it easier for developers to add powerful functionality to their GraphQL APIs.

Extending Validation Logic

To create a custom validation directive, you need to provide two things: The plugin that is your own validation implementations to extend the validation core, and the directive schema.

The plugins are a list of functions that will be used to validate the field value. It's important to note that the plugins don't need to provide the logic to traverse through the object fields because the core validator takes care of that. Instead, each plugin is responsible for validating a specific field or argument.

The directive schema, on the other hand, is used to define the custom validation directive itself. This includes specifying the directive name, its arguments, and the locations where it can be used. By defining the directive schema, you can ensure that your custom validation directive is integrated properly into your GraphQL schema.

Example

As an example, let's create a custom validation directive that leverage the functionality of the Validator.js library. In this example, we'll create a @validate directive with two methods: EMAIL and LENGTH.

The EMAIL method will validate that a given field value is a valid email address, while the LENGTH method will validate that a given field value is a string with a length between a minimum and maximum value.

import val from "validator"
import { createValidatorTransformer, Plugins } from "@graphql-directive/core"

// plugins, the logic to validate field
const plugins:Plugins = {
    EMAIL: (str, { directiveArgs: args }) => val.isEmail(str)
        || args.message
        || `Must be a valid email address`,

    LENGTH: (str, { directiveArgs: args }) => val.isLength(str, ctx.directiveArgs)
        || args.message
        || `Must be a string or array between ${args?.min ?? 0} and ${args?.max}`,
} 

// the validation directive schema
const typeDefs = `
    enum ValidationMethod {
        EMAIL, LENGTH
    }
    directive @validate(
        method: ValidationMethod!, 
        message: String,
        validator: String,
        min:Int,
        max:Int
    ) repeatable on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
`

// transformer function that will glue the directive with the validation logic
const transform = createValidatorTransformer({ plugins, directive: "validate" })

The plugins are a key-value object consisting of plugin method names and their validation logic

{
    METHOD: (value, ctx) => isValid(value) 
        || ctx.directiveArgs.message 
        || "The error message"
}

args : Is the argument passed from the @validate directive, for example @validate(method: LENGTH, min: 1, max: 150), the args parameter will contains { min: 1, max: 150 }.

option: Is the transformer options, contains some useful information such as list of plugins, directive name (for custom directive name), and list of custom functions.

Validator is a function with signature like above with below parameters:

  • value: Is the value that will be validate

  • ctx: Is the validation context, it contains more detail information required for custom validation.

    • options : Contains options values of transformer
    • path : The location of where validator applied from the root path through the GraphQL fields
    • contextValue : An object shared across all resolvers that are executing for a particular operation. Use this to share per-operation state, including authentication information, dataloader instances, and anything else to track across resolvers.
    • parent : The return value of the resolver for this field's parent (i.e., the previous resolver in the resolver chain).
    • args : An object that contains all GraphQL arguments provided for this field.
    • info : Contains information about the operation's execution state, including the field name, the path to the field from the root, and more.
    • directiveArgs : Contains argument passed by the @validate directive. For example @validate(method: LENGTH, min: 1, max: 150), the args parameter will contains { min: 1, max: 150 }.

The return value is true | string

The directive schema should reflect the plugin functionalities such as the method name and its parameters. Like example above we providing the enum for the method and list of supported parameters.

enum ValidationMethod {
    CUSTOM, EMAIL, LENGTH
}
directive @validate(
    # the method name
    method: ValidationMethod!, 
    # the custom validator
    validator: String,
    # for custom message
    message: String,
    # list of all plugin parameters
    min:Int,
    max:Int
) repeatable on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION

The last step is creating the transform function by calling the createValidatorTransformer. The first parameter is the plugins and the last parameter is the name of the directive in this case is validate.

IMPORTANT

  • CUSTOM on ValidationMethod is required
  • Top 3 parameters (method, validator, message) are required to add.