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-schema-builder

v0.9.2

Published

GraphQL Schema Builder

Downloads

38

Readme

graphql-schema-builder

NPM version Build status Test coverage Downloads

Builds GraphQL types based on Mongoose-like schema and a resolver list thus separating type schema from resolvers. Simplifies defining mutation arguments based on schema types.

Type's fields can be used to build Mongoose schema by calling it with mongoose.Schema.Types or mechanically converted into any other schemas.

NB: All types are assumed to have an implicit id field.

Usage

yarn add graphql-schema-builder

or

npm install --save graphql-schema-builder
const graphql = require('graphql');

const {
  buildFields,
  buildTypes,
  getProjection,

  GraphQLJSON
} = require('graphql-schema-builder')(graphql);

function getSchema(resolvers, schema, { customerProvider }) {
  // build types based on existing domain schemas and resolvers
  const types = buildTypes({
    Asset,
    Customer,
    Sensor
  }, resolvers);

  const schemaStore = new Map;

  function buildSubType({ name, fields }) {
    const _name   = `${name}Input`;
    const newType = new GraphQLInputObjectType({ name: _name, fields });
    schemaStore.set(_name, newType);
    return newType;
  }

  function getExistingType(name) {
      return schemaStore.get(`${name}Input`);
  }

  return new GraphQLSchema({
    query: new GraphQLObjectType({
      name: 'RootQueryType',
      fields: {
        customer: {
          type: types.Customer,
          args: {
            id: {
              name: 'id',
              type: new GraphQLNonNull(GraphQLID)
            }
          },

          resolve(_0, { id }, _1, info) {
            const projection = getProjection(info);
            return customerProvider.findById(id, projection);
          }
        },
        customers: {
          type: new GraphQLList(types.Customer),

          resolve(_0, {}, _1, info) {
            const projection = getProjection(info);
            return customerProvider.findAll(projection);
          }
        }
      }
    }),

      mutation: new GraphQLObjectType({
        name: 'Mutation',
        fields: {
          createAsset: {
            type: types.Asset,
            // build arguments based on domain schemas instead of
            // specifying them manually
            args: buildFields(Asset.fields, {
              buildSubType,
              getExistingType
            }),

            resolve(obj, args, source, info) {
              // create asset
            }
          },

          /* more mutations, etc. */
        }
      })
  });
}

Schema example

fields can be either an object or a function accepting { Mixed, ObjectId }. See Mongoose Guide for more details about Schema definition.

const schema = {
  Asset: {
    name:        'Asset',
    description: 'An asset.',

    fields: ({ Mixed, ObjectId }) => ({
      customer: {
        description: 'Customer that this asset belongs to.',

        type:     ObjectId,
        ref:      'Customer',
        required: true
      },

      parent: {
        type:     ObjectId,
        ref:      'Asset',
        required: false
      },

      name: {
        type:     String,
        required: true
      }
    }),

    dynamicFields: ({ ObjectId }) => ({
      sensors: {
        type: [ObjectId],
        ref:  'Sensor'
      }
    })
  },

  Customer: {
    name:        'Customer',
    description: 'A customer.',

    fields: {
      name: {
        description: 'The name of the customer.',

        type:     String,
        required: true
      },

      // Will result in subtype
      metadata: {
        created: {
            type:     Date,
            required: true
        }
      }
    },

    dynamicFields: ({ Mixed, ObjectId }) => ({
      assets: {
        type: [ObjectId],
        ref:  'Asset'
      }
    })
  },

  Sensor: {
    name:        'Sensor',
    description: 'A sensor that must be connected to an asset.',

    fields: ({ Mixed, ObjectId }) => ({
      externalId: {
        type:     String,
        required: false
      },

      asset: {
        description: 'An asset that this sensor is connected to.',

        type:     ObjectId,
        ref:      'Asset',
        required: true
      },

      name: {
        type:     String,
        required: false
      }
    })
  }
}

Resolvers example

A resolver can be either a function or an object. If it's an object it must have a resolve() function and can have args field. args has the same format as a schema. Matching arguments will be passed into the args argument of a resolver.

See also:

const resolvers = {
  Asset: {
    customer(obj, {}, _, info) {
      const projection = getProjection(info);
      return customerProvider.findById(obj.customer, projection);
    },

    parent(obj, {}, _, info) {
      if (obj.parent != null)
          return null;

      const projection = getProjection(info);
      return assetProvider.findById(obj.parent, projection);
    },

    sensors(obj, {}, _, info) {
      const projection = getProjection(info);
      return sensorProvider.find({ asset: obj.id }, projection);
    },

    // resolver as an object
    measurements: {
      args: {
        resolution: {
          type:     String,
          required: true
        }
      },

      resolve(obj, { resolution }, _, info) {
        const projection = getProjection(info);
        return measurementProvider.find({ resolution }, projection);
      }
    }
  },

  Customer: {
    assets(obj, {}, _, info) {
      const projection = getProjection(info);
      return assetProvider.find({ customer: obj.id }, projection);
    }
  },

  Sensor: {
    asset(obj, {}, _, info) {
      const projection = getProjection(info);
      return assetProvider.findById(obj.parent, projection);
    }
  }
}

Supported schema types

  • Array of any of supported types
  • Boolean
  • Date
  • Mixed
  • Number
  • ObjectId
  • String
  • Custom GraphQL types passed to buildTypes through getExistingType argument

Examples

See GraphQL example in pubsub-store repository.

License

MIT