Giter Club home page Giter Club logo

graph.ql's Introduction

img

graph.ql

Faster and simpler technique for creating and querying GraphQL schemas.

Video Course

If you're interested in diving deeper into GraphQL, I've created a video course called Building Better APIs with GraphQL.

Features

  • Support for queries, mutations, and subscriptions
  • Input type support
  • Variable support

Installation

npm install graph.ql

Example

var Schema = require('graph.ql')

// an object of promises that fetch actual data
var loaders = require('./loaders')

// create the schema
var schema = Schema(`
  scalar Date

  type Person {
    name: String
    films: [Film]
  }

  type Film {
    title: String,
    producers(): [String]
    characters(limit: Int): [Person]
    release_date: Date
  }

  type Query {
    film(id: Int): Film
    person(id: Int): Person
  }
`, {
  Date: {
    serialize(date) {
      return new Date(date)
    }
  },
  Person: {
    films(person) {
      return loaders.film.loadMany(person.films)
    }
  },
  Film: {
    producers(film) {
      return film.producer.split(',')
    },
    characters(film, args) {
      var characters = args.limit
        ? film.characters.slice(0, args.limit)
        : film.characters

      return loaders.person.loadMany(characters)
    }
  },
  Query: {
    film(query, args) {
      return loaders.film.load(args.id)
    },
    person(query, args) {
      return loaders.person.load(args.id)
    }
  },
})

// use the schema
schema(`
  query fetch_film($id: Int) {
    film(id: $id) {
      title
      producers
      release_date
      characters {
        name
        films {
          title
        }
      }
    }
  }
`, {
  id: 1
}).then(res => console.log(res.data))

graphql-js vs graph.ql

Say we want to create a GraphQL schema that looks like this:

type Film {
  title: String
}

type Query {
  film(id: Int): Film
}

With the official graphql-js library, it would look like this:

var graphql = require('graphql')

var Film = new graphql.GraphQLObjectType({
  name: 'Film',
  fields: {
    title: {
      type: graphql.GraphQLString
    }
  }
})

var schema = new graphql.GraphQLSchema({
  query: new graphql.GraphQLObjectType({
    name: 'Query'
    fields: {
      film: {
        type: Film,
        args: {
          id: {
            description: 'Fetch the film by id',
            type: graphql.GraphQLInt
          }
        },
        resolve: (root, args) => load_film(args.id)
      }
    }
  })
})

With graph.ql, we just need to do this:

var schema = Schema(`
  type Film {
    title: String
  }

  type Query {
    # Fetch the film by id
    film(id: Int): Film
  }
`, {
  Query: {
    film(root, args) {
      return load_film(args.id)
    }
  }
})

FAQ

How do I add descriptions?

  • You can add descriptions by placing a comment directly above the field or type. The following shows a comment on a type as well as a comment on a field.
# Query methods
type Query {
  # Fetch the film by id
  film (id: Int): Film
}

Credits

Thanks to ForbesLindesay for his initial work on graphql-schema-gen which laid the groundwork for this module.

Thanks to the GraphQL team for an incredible spec as well as their kitchen sink documents to quickly test against the entire spec.

Run Tests

npm install

License

MIT

graph.ql's People

Contributors

leebyron avatar matthewmueller avatar nl0 avatar tgriesser avatar theghoul21 avatar zuhair-naqvi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

graph.ql's Issues

add comment for query arguments

Can we add comment in query argument?

L270

if (arg.kind === 'Comment') return;
args[arg.name.value] = {
   type: getInputType(arg.type),
   defaultValue: arg.defaultValue ? getRawValue(arg.defaultValue) : undefined
};

support passing arrays as a parameter

need to check if this is valid/supported in graphql-js, but right now this throws:

person(name: String, phone: String, colors: [String]): Person

because colors is an array of strings

Add example for loaders?

@matthewmueller can you add simple example for data fetching?

// an object of promises that fetch actual data
var loaders = require('./loaders')
...
Person: {
    films(person) {
      return loaders.film.loadMany(person.films)
    }
  },

How should look like loader? Should method loadMany return the usual promise?

Package Name

You should consider changing the name of this amazing project. It is nearly impossible to find in any kind of search on net or github. Maybe fastql or mattql or eminemql or something. graph.ql gets searched same as graphql in any context.

Keep up the good work!

Send post request using postman

How do I send post request using postman in graphql.?

app.post('/mutation',(req,res)=>{
_mutationSchema(
mutation create($post:PostInput){ post:create_post(post:$post){ title } }
).then((result)=>{
res.send(result);
})
});

I am getting this error on postman

{
"data": {
"post": null
},
"errors": [
{
"message": "Cannot read property 'title' of undefined",
"originalError": {}
}
]
}

Question: is it possible to include the graphql type in the scalar "serialize" function

In the graphql-relay-js library they have a function to declare a GlobalID for a type.

export function globalIdField(
typeName?: ?string,
idFetcher?: (object: any, info: GraphQLResolveInfo) => string
): GraphQLFieldConfig {
return {
name: 'id',
description: 'The ID of an object',
type: new GraphQLNonNull(GraphQLID),
resolve: (obj, args, info) => toGlobalId(
typeName != null ? typeName : info.parentType.name,
idFetcher ? idFetcher(obj, info) : obj.id
)
};
}

This is used by relay to ensure you don't expose raw database ids to the public, and also to determine a node type based on it's id (since the id is hashed along with it's type).

Is there anyway to check the graphql type for an object in the serialize function of a scalar definition, so that i can encode these ID with their appropriate type?

e.g
scalar GlobalID

GlobalID: {
serialize(id, nodeType) {
return toGlobalId(nodeType, id);
}
}

Thanks!

Is it possible to create one type at a time?

I currently have many types and want to incrementally convert them to graph.ql.
Does graph.ql support create one type at a time?

Also, does it support interface, enum, mutation, relay node connections?

Any example for Relay Node inheritance and Connections?

This is a great library, was wondering if there is implement types from Node which is required for graphql-relay and the connections.

var userType = new GraphQLObjectType({
name: 'User',
description: 'A person who uses our app',
fields: () => ({
id: globalIdField('User'),
firstName: {
type: GraphQLString,
description: "First Name of user"
},
lastName: {
type: GraphQLString,
description: "Last Name of user"
}
}),
interfaces: [nodeInterface],
});

//How to specify interfaces:[nodeInterface] ?

Possible to add resolveType function to type?

I'm trying to add a resolveType function to my union type but unsure how to do this or if it's even supported. The error I'm seeing is:

Error: Interface Type BulletNode does not provide a "resolveType" function and implementing Type TextNode does not provide a "isTypeOf" function. There is no way to resolve this implementing type during execution.

and here's my code

var Schema = require('graph.ql')

var schema = Schema(`
  interface BulletNode {
    text: String
  }

  type TextNode implements BulletNode {
    text: String
  }

  type LinkNode implements BulletNode {
    text: String
    url: String
    linkType: String
  }

  type BulletListItem {
    nodes: [BulletNode]
  }

  type BulletList {
    bullets: [BulletListItem]
  }

  type Article {
    id: String
    bulletList: [BulletList]
  }
`, {
  BulletListItem: {
    resolveType (value) {
      if (value.url) return LinkNode; //also, not sure how to accomplish this?
      return TextNode;
    }
  }
})

Relay support

When I try to implement Relay semantics, i.e. Nodes, edges, connections etc. the library is throwing the following exception:

[ 'Error: Expected "{" but got ":"',
     '',
     '    ',
     '        type User : Node {',
     '                 ^',
     '          id: ID!',

     '',
     '    at Parse.error (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:545:10)',
     '    at Parse.required (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:68:16)',
     '    at Parse.expect (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:77:8)',
     '    at Parse.object_type_definition (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:187:10)',
     '    at Parse.type_definition (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:167:15)',
     '    at Parse.list (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:140:44)',
     '    at Parse.document (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:119:26)',
     '    at new Parse (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:33:15)',
     '    at Parse (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/parse.js:28:40)',
     '    at Create (/Users/zuhairnaqvi/dev/project/project-graphql/node_modules/graph.ql/lib/index.js:26:20)' ] }

I thought this library was 100% compliant with GraphQL spec but looks like it doesn't support interfaces. Any ideas how to get around this?

I really like the simplicity of schema definition graph.ql provides but I also need to use Relay!

Notation like Typescript

I really like your notation of a schema. I thought first it's typescript. Do you think it would make sense to convert your notation completely to typescript notation? Then a typescript developer directly feels home xD

Interface implementations missing from schema with graphql-js 0.5.0

Hey.

First of all, thanks for this awesome library.

There's a breaking change in graphql-js v.0.5.0 that reads as follows:

  • Types which implement an interface but are otherwise not referenced as a field return type are no longer automatically added to the Schema

It appears that it's now possible to pass types to include explicitly in the constructor of graphql.GraphQLSchema in index.js:

function Create (schema, implementation) {

  // ....

  // create an array of all types
  var all_types = Object.keys(object_types).map(function(typeName) {
    return object_types[typeName];
  });

  var schema = new graphql.GraphQLSchema({
    query: object_types['Query'],
    mutation: object_types['Mutation'],
    subscription: object_types['Subscription'],
    // and pass them here to include them in v.0.5.0 of graphql-js
    types: all_types
  });

  // .....
}

Adding all_types to the schema fixed our use case. I'm not sure whether this should be the default behaviour though.

v2.0.2 doesn't install graphql as peer dependency

v2.0.1 did not install graphql dependency in node_modules if already a peer

install v2.0.2 will get the following error if graphql peer already installed
{"errors":[{"message":"Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory."}]}

publish updated package.json to npm

Could you please publish new package.json file? The current one still list "graphql":"^0.5.0" as dependencies. I'm use "graphql":"^0.7.1" in my package.json so there is two versions of graphql and I got this "Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory." error. I feel like it is related.

Add example for mutation?

Thank you for this great implementation. As .graphql schema should define everything, graphql-js should be as simple as this.

Now I want to mutate something which I could not find any example to do with graphql.js. I hope my random trail and error will hit bullseye.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.