How to use graphql - 10 common examples

To help you get started, we’ve selected a few graphql examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kamilkisiela / graphql-inspector / packages / core / __tests__ / diff / enum.ts View on Github external
test('description changed', () => {
    const a = buildSchema(/* GraphQL */ `
      type Query {
        fieldA: String
      }

      """
      Old Description
      """
      enum enumA {
        A
        B
      }
    `);

    const b = buildSchema(/* GraphQL */ `
      type Query {
        fieldA: String
      }

      """
      New Description
      """
      enum enumA {
        A
        B
      }
    `);

    const changes = diff(a, b);
    const change = findFirstChangeByPath(changes, 'enumA');
github kamilkisiela / graphql-inspector / packages / core / __tests__ / diff / interface.ts View on Github external
test('added', async () => {
      const a = buildSchema(/* GraphQL */ `
        interface Foo {
          a: String!
          b: String!
        }
      `);
      const b = buildSchema(/* GraphQL */ `
        interface Foo {
          a: String!
          b: String!
          c: String!
        }
      `);

      const change = findFirstChangeByPath(await diff(a, b), 'Foo.c');

      expect(change.criticality.level).toEqual(CriticalityLevel.NonBreaking);
github tjmehta / primus-graphql / test-browser / fixtures / graphql-schema.js View on Github external
var debug = require('debug')('primus-graphql:fixtures:graphql-schema')
var GraphQL = require('graphql')
var Relay = require('graphql-relay')

var db = require('./mem-db.js') // In memory database
var GraphQLRelaySubscription = require('graphql-relay-subscription')
var UserChangesIterator = require('./user-changes-iterator')
require('../../src/shared/subscription-dispose.js')

var relaySubscription = GraphQLRelaySubscription.subscriptionWithClientId
var GraphQLInputObjectType = GraphQL.GraphQLInputObjectType
var GraphQLSchema = GraphQL.GraphQLSchema
var GraphQLString = GraphQL.GraphQLString
var GraphQLNonNull = GraphQL.GraphQLNonNull
var GraphQLObjectType = GraphQL.GraphQLObjectType

// GraphQL types

var UserType = new GraphQLObjectType({
  name: 'User',
  description: 'user',
  fields: {
    id: { type: GraphQLString },
    name: { type: GraphQLString },
    idAndName: {
      type: GraphQLString,
      resolve: function (user) {
        return user.id + ':' + user.name
      }
github excitement-engineer / graphql-iso-date / examples / localDate / input.js View on Github external
// The date parameter is a Javascript Date object
          return date
        }
      }
    }
  })
})

graphql(schema, `{ input(date: "2016-02-01") }`)
    .then(result => {
      console.log(`Example query { input(date: "2016-02-01") }: Input a valid date and output the same date`)
      console.log(result)
    })
    .catch(console.error)

graphql(schema, `{ input(date: "2015-02-29") }`)
    .then(result => {
      console.log(`Example query { input(date: "2015-02-29") }: Output an error when an invalid date is passed as input (29 Feb 2015 doesn't exist)`)
      console.log(result)
    })
    .catch(console.error)
github aerogear / graphback / packages / graphql-migrations / src / abstract / generateAbstractDatabase.ts View on Github external
console.warn(`Couldn't create foreign field ${foreignKey} on type ${fieldType.name} on field ${field.name}. See above messages.`)
        return null
      }
      type = descriptor.type
      args = descriptor.args
      foreign = {
        type: foreignType.name,
        field: foreignField.name,
        tableName: null,
        columnName: null,
      }

      // List
    } else if (isListType(fieldType) && this.currentTable) {
      let ofType = fieldType.ofType
      ofType = isNonNullType(ofType) ? ofType.ofType : ofType
      if (isObjectType(ofType)) {
        // Foreign Type
        const onSameType = this.currentType === ofType.name
        const foreignType = this.typeMap[ofType.name]
        if (!foreignType) {
          console.warn(`Foreign type ${ofType.name} not found on field ${this.currentType}.${field.name}.`)
          return null
        }
        if (!isObjectType(foreignType)) {
          console.warn(`Foreign type ${ofType.name} is not Object type on field ${this.currentType}.${field.name}.`)
          return null
        }

        // Foreign Field
        const foreignKey = onSameType ? field.name : annotations.manyToMany || this.currentTable.name
        const foreignField = foreignType.getFields()[foreignKey]
github artsy / reaction / tslint / relayOperationGenericsRule.js View on Github external
function getOperationName(taggedTemplate) {
  const template = taggedTemplate.template.getFullText()
  // Strip backticks
  const source = template.substring(1, template.length - 1)

  const ast = parse(source)
  let queryName = null
  visit(ast, {
    OperationDefinition(node) {
      queryName = node.name.value
      return BREAK
    },
  })

  return queryName
}
github gridsome / gridsome / gridsome / lib / graphql / utils / parsePageQuery.js View on Github external
Field (fieldNode) {
      return visit(fieldNode, {
        Directive (node, key, parent, path, ancestors) {
          if (node.name.value === 'paginate') {
            if (result.paginate.typeName) {
              return BREAK
            }

            const parentNode = ancestors.slice().pop()
            const perPageArg = parentNode.arguments.find(node => node.name.value === 'perPage')

            // guess content type by converting root field value into a camel cased string
            result.paginate.typeName = upperFirst(trimStart(fieldNode.name.value, 'all'))

            if (perPageArg) {
              result.paginate.perPage = Number(perPageArg.value.value)
            }
github CDThomas / graphql-usage / src / getFieldInfo.ts View on Github external
function visitFields(
  node: OperationDefinitionNode | FragmentDefinitionNode,
  graphQLTag: GraphQLTag,
  typeInfo: TypeInfo,
  cb: (fieldInfo: FieldInfo) => void
) {
  if (!node.name) {
    throw new Error(
      "visitFields expects OperationDefinitions and FragmentDefinitions to be named"
    );
  }

  const { filePath, sourceLocationOffset, template } = graphQLTag;
  const operationOrFragmentName = node.name.value;

  visit(
    node,
    visitWithTypeInfo(typeInfo, {
      Field(graphqlNode) {
        // Discard client only fields, but don't throw an error
        if (isClientOnlyField(graphqlNode)) return;

        const parentType = typeInfo.getParentType();
        const nodeType = typeInfo.getType();
        const nodeName = graphqlNode.name.value;

        if (!parentType) {
          throw new Error(
            `visitFields expects fields to have a parent type. No parent type for ${nodeName}`
          );
        }
github lifeomic / json-schema-to-graphql-types / bin / convert-json-schemas-to-graphql-types.js View on Github external
// The directory comes from the command line argument
  // eslint-disable-next-line security/detect-non-literal-fs-filename
  const files = await validators.validatePathName(dir); // If valid, will return an array of file names
  const schemas = [];

  for (const file of files) {
    const schemaContents = await validators.validateJSONSyntax(file, dir); // If valid, will return parsed JSON-schema from file
    if (Array.isArray(schemaContents)) {
      schemaContents.forEach(oneSchema => schemas.push(oneSchema));
    } else {
      schemas.push(schemaContents);
    }
  }

  const schema = jsonSchemasToGraphqlSchema(schemas);
  const printed = printSchema(schema);

  // Strip out the Query type because it's not needed
  const withoutQuery = printed.replace(/^type Query {[^}]*}/m, '');
  const withoutMutation = withoutQuery.replace(/^type Mutation {[^}]*}/m, '');

  if (asJs) {
    console.log(`'use strict';\nmodule.exports = \`\n${withoutMutation}\`;\n`);
  } else {
    console.log(withoutQuery);
  }
}
github Asymmetrik / graphql-fhir / src / resources / 1_0_2 / inputs / signature.input.js View on Github external
type: new GraphQLNonNull(UriScalar),
			description:
				'A reference to an application-usable description of the person that signed the certificate (e.g. the signature used their private key).',
		},
		whoReference: {
			type: new GraphQLNonNull(GraphQLString),
			description:
				'A reference to an application-usable description of the person that signed the certificate (e.g. the signature used their private key).',
		},
		_contentType: {
			type: require('./element.input.js'),
			description:
				'A mime type that indicates the technical format of the signature. Important mime types are application/signature+xml for X ML DigSig, application/jwt for JWT, and image/* for a graphical image of a signature.',
		},
		contentType: {
			type: new GraphQLNonNull(CodeScalar),
			description:
				'A mime type that indicates the technical format of the signature. Important mime types are application/signature+xml for X ML DigSig, application/jwt for JWT, and image/* for a graphical image of a signature.',
		},
		_blob: {
			type: require('./element.input.js'),
			description: 'The base64 encoding of the Signature content.',
		},
		blob: {
			type: new GraphQLNonNull(Base64BinaryScalar),
			description: 'The base64 encoding of the Signature content.',
		},
	}),
});