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-field-arguments-coercion

v1.1.1

Published

Implementation of the support of coerce function on GraphQL Input types

Downloads

61

Readme

graphql-field-arguments-coercion

npm version

Implementation of the support of coerce function on GraphQL Input types.

Used to implement directive-based validation and transformation of field arguments.

Originally developed by Alexandre Lacheze who was kind enough to transfer the repository and npm package for future development.

Install

npm install graphql-field-arguments-coercion -D

Usage

Use coerceFieldArgumentsValues(field, args, ...) to coerce the arguments of the given field. To coerce the arguments' values, it will recursively use the coerce property, a coercer function, hold by ArgumentDefinition, InputObject and InputObjectField.

A coercer function receives 4 arguments:

  • value: the value to be coerced.
  • context: the GraphQLContext of the current execution
  • inputCoerceInfo: an object holding info about the current argument, input or input field. See its type definition for more details.
  • fieldResolveInfo: the received GraphQLResolveInfo of the field being resolved.

A coercer function can return the coerced value, a promise resolving the coerced value or throw an error.

Example

Here's an implementation of a directive-based length validation @length(max: Int!):

First, we need to add the coercer to evey argument definition and input definition targeted by the directive. To do so, we use graphql-tools's SchemaDirectiveVisitor.

const directiveTypeDefs =  `
directive @length(max: Int!) on INPUT_FIELD_DEFINITION | ARGUMENT_DEFINITION
`;

class LengthDirective<TContext> extends SchemaDirectiveVisitor<{ max: number }, TContext> {
  visitInputFieldDefinition(field: CoercibleGraphQLInputField<string, TContext>) {
    this.installCoercer(field);
  }

  visitArgumentDefinition(argument: CoercibleGraphQLArgument<string, TContext>) {
    this.installCoercer(argument);
  }

  installCoercer(
    input: 
      CoercibleGraphQLInputField<string, TContext> |
      CoercibleGraphQLArgument<string, TContext>
    ) {
      const { coerce = defaultCoercer } = input;
      input.coerce = async (value, ...args) => {
        // call previous coercers if any
        if (coerce) value = await coerce(value, ...args);

        const { path } = args[1]; // inputCoerceInfo
        const { max } = this.args;
        assert.isAtMost(value.length, max, `${pathToArray(path).join('.')} length exceeds ${max}`);

        return value;
      }
  }
}

We define the schema as usual but add the directive:

const typeDefs = `
type Query {
  books: [Book]
}

type Book {
  title: String
}

type Mutation {
  createBook(book: BookInput): Book
}

input BookInput {
  title: String! @length(max: 50)
}`;

const schema = makeExecutableSchema({
  typeDefs: [directiveTypeDefs, typeDefs],
  resolvers: {
    Mutation: {
      createBook: (_, { book }) => book,
    }
  },
  schemaDirectives: {
    length: LengthDirective
  }
});

Now we'll wrap all fields' resolvers with a use of coerceFieldArgumentsValues so that we make sure the arguments are valid before calling the resolver — otherwise, we throw the appropriate error.

To do so, we'll use graphql-tools's visitSchema and SchemaVisitor:

class FieldResoverWrapperVisitor<TContext> extends SchemaVisitor {
  visitFieldDefinition(field: GraphQLField<any, TContext>) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async (parent, argumentValues, context, info) => {

      const coercionErrors: Error[] = [];
      const onCoercionError = e => coercionErrors.push(e);

      const coercedArgumentValues = await coerceFieldArgumentsValues(
        field,
        argumentValues,
        context,
        info,
        onCoercionError,
      );

      if (coercionErrors.length > 0) {
        throw new UserInputError(`Arguments are incorrect: ${coercionErrors.join(',')}`);
      }

      return resolve(parent, coercedArgumentValues, context, info);
    }
  }
}

visitSchema(schema, new FieldResoverWrapperVisitor);

The full example is runnable here.

Related