Giter VIP home page Giter VIP logo

graphql / graphiql Goto Github PK

View Code? Open in Web Editor NEW
15.7K 15.7K 1.7K 26.18 MB

GraphiQL & the GraphQL LSP Reference Ecosystem for building browser & IDE tools.

License: MIT License

JavaScript 4.97% Shell 0.31% TypeScript 89.82% CSS 4.07% EJS 0.13% HTML 0.47% Vue 0.04% PHP 0.04% Python 0.06% Scala 0.01% Svelte 0.01% Ruby 0.04% Reason 0.02%
codemirror graphiql graphql lsp-mode lsp-server monaco-editor vscode

graphiql's Introduction

GraphQL

GraphQL Logo

The GraphQL specification is edited in the markdown files found in /spec the latest release of which is published at https://graphql.github.io/graphql-spec/.

The latest draft specification can be found at https://graphql.github.io/graphql-spec/draft/ which tracks the latest commit to the main branch in this repository.

Previous releases of the GraphQL specification can be found at permalinks that match their release tag. For example, https://graphql.github.io/graphql-spec/October2016/. If you are linking directly to the GraphQL specification, it's best to link to a tagged permalink for the particular referenced version.

Overview

This is a Working Draft of the Specification for GraphQL, a query language for APIs created by Facebook.

The target audience for this specification is not the client developer, but those who have, or are actively interested in, building their own GraphQL implementations and tools.

In order to be broadly adopted, GraphQL will have to target a wide variety of backend environments, frameworks, and languages, which will necessitate a collaborative effort across projects and organizations. This specification serves as a point of coordination for this effort.

Looking for help? Find resources from the community.

Getting Started

GraphQL consists of a type system, query language and execution semantics, static validation, and type introspection, each outlined below. To guide you through each of these components, we've written an example designed to illustrate the various pieces of GraphQL.

This example is not comprehensive, but it is designed to quickly introduce the core concepts of GraphQL, to provide some context before diving into the more detailed specification or the GraphQL.js reference implementation.

The premise of the example is that we want to use GraphQL to query for information about characters and locations in the original Star Wars trilogy.

Type System

At the heart of any GraphQL implementation is a description of what types of objects it can return, described in a GraphQL type system and returned in the GraphQL Schema.

For our Star Wars example, the starWarsSchema.ts file in GraphQL.js defines this type system.

The most basic type in the system will be Human, representing characters like Luke, Leia, and Han. All humans in our type system will have a name, so we define the Human type to have a field called "name". This returns a String, and we know that it is not null (since all Humans have a name), so we will define the "name" field to be a non-nullable String. Using a shorthand notation that we will use throughout the spec and documentation, we would describe the human type as:

type Human {
  name: String
}

This shorthand is convenient for describing the basic shape of a type system; the JavaScript implementation is more full-featured, and allows types and fields to be documented. It also sets up the mapping between the type system and the underlying data; for a test case in GraphQL.js, the underlying data is a set of JavaScript objects, but in most cases the backing data will be accessed through some service, and this type system layer will be responsible for mapping from types and fields to that service.

A common pattern in many APIs, and indeed in GraphQL is to give objects an ID that can be used to refetch the object. So let's add that to our Human type. We'll also add a string for their home planet.

type Human {
  id: String
  name: String
  homePlanet: String
}

Since we're talking about the Star Wars trilogy, it would be useful to describe the episodes in which each character appears. To do so, we'll first define an enum, which lists the three episodes in the trilogy:

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

Now we want to add a field to Human describing what episodes they were in. This will return a list of Episodes:

type Human {
  id: String
  name: String
  appearsIn: [Episode]
  homePlanet: String
}

Now, let's introduce another type, Droid:

type Droid {
  id: String
  name: String
  appearsIn: [Episode]
  primaryFunction: String
}

Now we have two types! Let's add a way of going between them: humans and droids both have friends. But humans can be friends with both humans and droids. How do we refer to either a human or a droid?

If we look, we note that there's common functionality between humans and droids; they both have IDs, names, and episodes in which they appear. So we'll add an interface, Character, and make both Human and Droid implement it. Once we have that, we can add the friends field, that returns a list of Characters.

Our type system so far is:

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

interface Character {
  id: String
  name: String
  friends: [Character]
  appearsIn: [Episode]
}

type Human implements Character {
  id: String
  name: String
  friends: [Character]
  appearsIn: [Episode]
  homePlanet: String
}

type Droid implements Character {
  id: String
  name: String
  friends: [Character]
  appearsIn: [Episode]
  primaryFunction: String
}

One question we might ask, though, is whether any of those fields can return null. By default, null is a permitted value for any type in GraphQL, since fetching data to fulfill a GraphQL query often requires talking to different services that may or may not be available. However, if the type system can guarantee that a type is never null, then we can mark it as Non Null in the type system. We indicate that in our shorthand by adding an "!" after the type. We can update our type system to note that the id is never null.

Note that while in our current implementation, we can guarantee that more fields are non-null (since our current implementation has hard-coded data), we didn't mark them as non-null. One can imagine we would eventually replace our hardcoded data with a backend service, which might not be perfectly reliable; by leaving these fields as nullable, we allow ourselves the flexibility to eventually return null to indicate a backend error, while also telling the client that the error occurred.

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

interface Character {
  id: String!
  name: String
  friends: [Character]
  appearsIn: [Episode]
}

type Human implements Character {
  id: String!
  name: String
  friends: [Character]
  appearsIn: [Episode]
  homePlanet: String
}

type Droid implements Character {
  id: String!
  name: String
  friends: [Character]
  appearsIn: [Episode]
  primaryFunction: String
}

We're missing one last piece: an entry point into the type system.

When we define a schema, we define an object type that is the basis for all query operations. The name of this type is Query by convention, and it describes our public, top-level API. Our Query type for this example will look like this:

type Query {
  hero(episode: Episode): Character
  human(id: String!): Human
  droid(id: String!): Droid
}

In this example, there are three top-level operations that can be done on our schema:

  • hero returns the Character who is the hero of the Star Wars trilogy; it takes an optional argument that allows us to fetch the hero of a specific episode instead.
  • human accepts a non-null string as a query argument, a human's ID, and returns the human with that ID.
  • droid does the same for droids.

These fields demonstrate another feature of the type system, the ability for a field to specify arguments that configure their behavior.

When we package the whole type system together, defining the Query type above as our entry point for queries, this creates a GraphQL Schema.

This example just scratched the surface of the type system. The specification goes into more detail about this topic in the "Type System" section, and the type directory in GraphQL.js contains code implementing a specification-compliant GraphQL type system.

Query Syntax

GraphQL queries declaratively describe what data the issuer wishes to fetch from whoever is fulfilling the GraphQL query.

For our Star Wars example, the starWarsQueryTests.js file in the GraphQL.js repository contains a number of queries and responses. That file is a test file that uses the schema discussed above and a set of sample data, located in starWarsData.js. This test file can be run to exercise the reference implementation.

An example query on the above schema would be:

query HeroNameQuery {
  hero {
    name
  }
}

The initial line, query HeroNameQuery, defines a query with the operation name HeroNameQuery that starts with the schema's root query type; in this case, Query. As defined above, Query has a hero field that returns a Character, so we'll query for that. Character then has a name field that returns a String, so we query for that, completing our query. The result of this query would then be:

{
  "hero": {
    "name": "R2-D2"
  }
}

Specifying the query keyword and an operation name is only required when a GraphQL document defines multiple operations. We therefore could have written the previous query with the query shorthand:

{
  hero {
    name
  }
}

Assuming that the backing data for the GraphQL server identified R2-D2 as the hero. The response continues to vary based on the request; if we asked for R2-D2's ID and friends with this query:

query HeroNameAndFriendsQuery {
  hero {
    id
    name
    friends {
      id
      name
    }
  }
}

then we'll get back a response like this:

{
  "hero": {
    "id": "2001",
    "name": "R2-D2",
    "friends": [
      {
        "id": "1000",
        "name": "Luke Skywalker"
      },
      {
        "id": "1002",
        "name": "Han Solo"
      },
      {
        "id": "1003",
        "name": "Leia Organa"
      }
    ]
  }
}

One of the key aspects of GraphQL is its ability to nest queries. In the above query, we asked for R2-D2's friends, but we can ask for more information about each of those objects. So let's construct a query that asks for R2-D2's friends, gets their name and episode appearances, then asks for each of their friends.

query NestedQuery {
  hero {
    name
    friends {
      name
      appearsIn
      friends {
        name
      }
    }
  }
}

which will give us the nested response

{
  "hero": {
    "name": "R2-D2",
    "friends": [
      {
        "name": "Luke Skywalker",
        "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"],
        "friends": [
          { "name": "Han Solo" },
          { "name": "Leia Organa" },
          { "name": "C-3PO" },
          { "name": "R2-D2" }
        ]
      },
      {
        "name": "Han Solo",
        "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"],
        "friends": [
          { "name": "Luke Skywalker" },
          { "name": "Leia Organa" },
          { "name": "R2-D2" }
        ]
      },
      {
        "name": "Leia Organa",
        "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"],
        "friends": [
          { "name": "Luke Skywalker" },
          { "name": "Han Solo" },
          { "name": "C-3PO" },
          { "name": "R2-D2" }
        ]
      }
    ]
  }
}

The Query type above defined a way to fetch a human given their ID. We can use it by hard-coding the ID in the query:

query FetchLukeQuery {
  human(id: "1000") {
    name
  }
}

to get

{
  "human": {
    "name": "Luke Skywalker"
  }
}

Alternately, we could have defined the query to have a query parameter:

query FetchSomeIDQuery($someId: String!) {
  human(id: $someId) {
    name
  }
}

This query is now parameterized by $someId; to run it, we must provide that ID. If we ran it with $someId set to "1000", we would get Luke; set to "1002", we would get Han. If we passed an invalid ID here, we would get null back for the human, indicating that no such object exists.

Notice that the key in the response is the name of the field, by default. It is sometimes useful to change this key, for clarity or to avoid key collisions when fetching the same field with different arguments.

We can do that with field aliases, as demonstrated in this query:

query FetchLukeAliased {
  luke: human(id: "1000") {
    name
  }
}

We aliased the result of the human field to the key luke. Now the response is:

{
  "luke": {
    "name": "Luke Skywalker"
  }
}

Notice the key is "luke" and not "human", as it was in our previous example where we did not use the alias.

This is particularly useful if we want to use the same field twice with different arguments, as in the following query:

query FetchLukeAndLeiaAliased {
  luke: human(id: "1000") {
    name
  }
  leia: human(id: "1003") {
    name
  }
}

We aliased the result of the first human field to the key luke, and the second to leia. So the result will be:

{
  "luke": {
    "name": "Luke Skywalker"
  },
  "leia": {
    "name": "Leia Organa"
  }
}

Now imagine we wanted to ask for Luke and Leia's home planets. We could do so with this query:

query DuplicateFields {
  luke: human(id: "1000") {
    name
    homePlanet
  }
  leia: human(id: "1003") {
    name
    homePlanet
  }
}

but we can already see that this could get unwieldy, since we have to add new fields to both parts of the query. Instead, we can extract out the common fields into a fragment, and include the fragment in the query, like this:

query UseFragment {
  luke: human(id: "1000") {
    ...HumanFragment
  }
  leia: human(id: "1003") {
    ...HumanFragment
  }
}

fragment HumanFragment on Human {
  name
  homePlanet
}

Both of those queries give this result:

{
  "luke": {
    "name": "Luke Skywalker",
    "homePlanet": "Tatooine"
  },
  "leia": {
    "name": "Leia Organa",
    "homePlanet": "Alderaan"
  }
}

The UseFragment and DuplicateFields queries will both get the same result, but UseFragment is less verbose; if we wanted to add more fields, we could add it to the common fragment rather than copying it into multiple places.

We defined the type system above, so we know the type of each object in the output; the query can ask for that type using the special field __typename, defined on every object.

query CheckTypeOfR2 {
  hero {
    __typename
    name
  }
}

Since R2-D2 is a droid, this will return

{
  "hero": {
    "__typename": "Droid",
    "name": "R2-D2"
  }
}

This was particularly useful because hero was defined to return a Character, which is an interface; we might want to know what concrete type was actually returned. If we instead asked for the hero of Episode V:

query CheckTypeOfLuke {
  hero(episode: EMPIRE) {
    __typename
    name
  }
}

We would find that it was Luke, who is a Human:

{
  "hero": {
    "__typename": "Human",
    "name": "Luke Skywalker"
  }
}

As with the type system, this example just scratched the surface of the query language. The specification goes into more detail about this topic in the "Language" section, and the language directory in GraphQL.js contains code implementing a specification-compliant GraphQL query language parser and lexer.

Validation

By using the type system, it can be predetermined whether a GraphQL query is valid or not. This allows servers and clients to effectively inform developers when an invalid query has been created, without having to rely on runtime checks.

For our Star Wars example, the file starWarsValidationTests.js contains a number of demonstrations of invalid operations, and is a test file that can be run to exercise the reference implementation's validator.

To start, let's take a complex valid query. This is the NestedQuery example from the above section, but with the duplicated fields factored out into a fragment:

query NestedQueryWithFragment {
  hero {
    ...NameAndAppearances
    friends {
      ...NameAndAppearances
      friends {
        ...NameAndAppearances
      }
    }
  }
}

fragment NameAndAppearances on Character {
  name
  appearsIn
}

And this query is valid. Let's take a look at some invalid queries!

When we query for fields, we have to query for a field that exists on the given type. So as hero returns a Character, we have to query for a field on Character. That type does not have a favoriteSpaceship field, so this query:

# INVALID: favoriteSpaceship does not exist on Character
query HeroSpaceshipQuery {
  hero {
    favoriteSpaceship
  }
}

is invalid.

Whenever we query for a field and it returns something other than a scalar or an enum, we need to specify what data we want to get back from the field. Hero returns a Character, and we've been requesting fields like name and appearsIn on it; if we omit that, the query will not be valid:

# INVALID: hero is not a scalar, so fields are needed
query HeroNoFieldsQuery {
  hero
}

Similarly, if a field is a scalar, it doesn't make sense to query for additional fields on it, and doing so will make the query invalid:

# INVALID: name is a scalar, so fields are not permitted
query HeroFieldsOnScalarQuery {
  hero {
    name {
      firstCharacterOfName
    }
  }
}

Earlier, it was noted that a query can only query for fields on the type in question; when we query for hero which returns a Character, we can only query for fields that exist on Character. What happens if we want to query for R2-D2s primary function, though?

# INVALID: primaryFunction does not exist on Character
query DroidFieldOnCharacter {
  hero {
    name
    primaryFunction
  }
}

That query is invalid, because primaryFunction is not a field on Character. We want some way of indicating that we wish to fetch primaryFunction if the Character is a Droid, and to ignore that field otherwise. We can use the fragments we introduced earlier to do this. By setting up a fragment defined on Droid and including it, we ensure that we only query for primaryFunction where it is defined.

query DroidFieldInFragment {
  hero {
    name
    ...DroidFields
  }
}

fragment DroidFields on Droid {
  primaryFunction
}

This query is valid, but it's a bit verbose; named fragments were valuable above when we used them multiple times, but we're only using this one once. Instead of using a named fragment, we can use an inline fragment; this still allows us to indicate the type we are querying on, but without naming a separate fragment:

query DroidFieldInInlineFragment {
  hero {
    name
    ... on Droid {
      primaryFunction
    }
  }
}

This has just scratched the surface of the validation system; there are a number of validation rules in place to ensure that a GraphQL query is semantically meaningful. The specification goes into more detail about this topic in the "Validation" section, and the validation directory in GraphQL.js contains code implementing a specification-compliant GraphQL validator.

Introspection

It's often useful to ask a GraphQL schema for information about what queries it supports. GraphQL allows us to do so using the introspection system!

For our Star Wars example, the file starWarsIntrospectionTests.js contains a number of queries demonstrating the introspection system, and is a test file that can be run to exercise the reference implementation's introspection system.

We designed the type system, so we know what types are available, but if we didn't, we can ask GraphQL, by querying the __schema field, always available on the root type of a Query. Let's do so now, and ask what types are available.

query IntrospectionTypeQuery {
  __schema {
    types {
      name
    }
  }
}

and we get back:

{
  "__schema": {
    "types": [
      {
        "name": "Query"
      },
      {
        "name": "Character"
      },
      {
        "name": "Human"
      },
      {
        "name": "String"
      },
      {
        "name": "Episode"
      },
      {
        "name": "Droid"
      },
      {
        "name": "__Schema"
      },
      {
        "name": "__Type"
      },
      {
        "name": "__TypeKind"
      },
      {
        "name": "Boolean"
      },
      {
        "name": "__Field"
      },
      {
        "name": "__InputValue"
      },
      {
        "name": "__EnumValue"
      },
      {
        "name": "__Directive"
      }
    ]
  }
}

Wow, that's a lot of types! What are they? Let's group them:

  • Query, Character, Human, Episode, Droid - These are the ones that we defined in our type system.
  • String, Boolean - These are built-in scalars that the type system provided.
  • __Schema, __Type, __TypeKind, __Field, __InputValue, __EnumValue, __Directive - These all are preceded with a double underscore, indicating that they are part of the introspection system.

Now, let's try and figure out a good place to start exploring what queries are available. When we designed our type system, we specified what type all queries would start at; let's ask the introspection system about that!

query IntrospectionQueryTypeQuery {
  __schema {
    queryType {
      name
    }
  }
}

and we get back:

{
  "__schema": {
    "queryType": {
      "name": "Query"
    }
  }
}

And that matches what we said in the type system section, that the Query type is where we will start! Note that the naming here was just by convention; we could have named our Query type anything else, and it still would have been returned here if we had specified it as the starting type for queries. Naming it Query, though, is a useful convention.

It is often useful to examine one specific type. Let's take a look at the Droid type:

query IntrospectionDroidTypeQuery {
  __type(name: "Droid") {
    name
  }
}

and we get back:

{
  "__type": {
    "name": "Droid"
  }
}

What if we want to know more about Droid, though? For example, is it an interface or an object?

query IntrospectionDroidKindQuery {
  __type(name: "Droid") {
    name
    kind
  }
}

and we get back:

{
  "__type": {
    "name": "Droid",
    "kind": "OBJECT"
  }
}

kind returns a __TypeKind enum, one of whose values is OBJECT. If we asked about Character instead:

query IntrospectionCharacterKindQuery {
  __type(name: "Character") {
    name
    kind
  }
}

and we get back:

{
  "__type": {
    "name": "Character",
    "kind": "INTERFACE"
  }
}

We'd find that it is an interface.

It's useful for an object to know what fields are available, so let's ask the introspection system about Droid:

query IntrospectionDroidFieldsQuery {
  __type(name: "Droid") {
    name
    fields {
      name
      type {
        name
        kind
      }
    }
  }
}

and we get back:

{
  "__type": {
    "name": "Droid",
    "fields": [
      {
        "name": "id",
        "type": {
          "name": null,
          "kind": "NON_NULL"
        }
      },
      {
        "name": "name",
        "type": {
          "name": "String",
          "kind": "SCALAR"
        }
      },
      {
        "name": "friends",
        "type": {
          "name": null,
          "kind": "LIST"
        }
      },
      {
        "name": "appearsIn",
        "type": {
          "name": null,
          "kind": "LIST"
        }
      },
      {
        "name": "primaryFunction",
        "type": {
          "name": "String",
          "kind": "SCALAR"
        }
      }
    ]
  }
}

Those are our fields that we defined on Droid!

id looks a bit weird there, it has no name for the type. That's because it's a "wrapper" type of kind NON_NULL. If we queried for ofType on that field's type, we would find the String type there, telling us that this is a non-null String.

Similarly, both friends and appearsIn have no name, since they are the LIST wrapper type. We can query for ofType on those types, which will tell us what these are lists of.

query IntrospectionDroidWrappedFieldsQuery {
  __type(name: "Droid") {
    name
    fields {
      name
      type {
        name
        kind
        ofType {
          name
          kind
        }
      }
    }
  }
}

and we get back:

{
  "__type": {
    "name": "Droid",
    "fields": [
      {
        "name": "id",
        "type": {
          "name": null,
          "kind": "NON_NULL",
          "ofType": {
            "name": "String",
            "kind": "SCALAR"
          }
        }
      },
      {
        "name": "name",
        "type": {
          "name": "String",
          "kind": "SCALAR",
          "ofType": null
        }
      },
      {
        "name": "friends",
        "type": {
          "name": null,
          "kind": "LIST",
          "ofType": {
            "name": "Character",
            "kind": "INTERFACE"
          }
        }
      },
      {
        "name": "appearsIn",
        "type": {
          "name": null,
          "kind": "LIST",
          "ofType": {
            "name": "Episode",
            "kind": "ENUM"
          }
        }
      },
      {
        "name": "primaryFunction",
        "type": {
          "name": "String",
          "kind": "SCALAR",
          "ofType": null
        }
      }
    ]
  }
}

Let's end with a feature of the introspection system particularly useful for tooling; let's ask the system for documentation!

query IntrospectionDroidDescriptionQuery {
  __type(name: "Droid") {
    name
    description
  }
}

yields

{
  "__type": {
    "name": "Droid",
    "description": "A mechanical creature in the Star Wars universe."
  }
}

So we can access the documentation about the type system using introspection, and create documentation browsers, or rich IDE experiences.

This has just scratched the surface of the introspection system; we can query for enum values, what interfaces a type implements, and more. We can even introspect on the introspection system itself. The specification goes into more detail about this topic in the "Introspection" section, and the introspection file in GraphQL.js contains code implementing a specification-compliant GraphQL query introspection system.

Additional Content

This README walked through the GraphQL.js reference implementation's type system, query execution, validation, and introspection systems. There's more in both GraphQL.js and specification, including a description and implementation for executing queries, how to format a response, explaining how a type system maps to an underlying implementation, and how to format a GraphQL response, as well as the grammar for GraphQL.

Contributing to this repo

This repository is managed by EasyCLA. Project participants must sign the free (GraphQL Specification Membership agreement before making a contribution. You only need to do this one time, and it can be signed by individual contributors or their employers.

To initiate the signature process please open a PR against this repo. The EasyCLA bot will block the merge if we still need a membership agreement from you.

You can find detailed information here. If you have issues, please email [email protected].

If your company benefits from GraphQL and you would like to provide essential financial support for the systems and people that power our community, please also consider membership in the GraphQL Foundation.

graphiql's People

Contributors

aaronmoat avatar acao avatar ags- avatar asiandrummer avatar aumyf avatar benjie avatar cshaver avatar dependabot-preview[bot] avatar dependabot[bot] avatar dimamachina avatar github-actions[bot] avatar greenkeeper[bot] avatar greenkeeperio-bot avatar harshithpabbati avatar imolorhe avatar jonathanawesome avatar leebyron avatar lostplan avatar maraisr avatar n1ru4l avatar olegilyenko avatar orta avatar patrick91 avatar peteduncanson avatar skevy avatar tessalt avatar thomasheyenbrock avatar timsuchanek avatar wincent avatar yoshiakis 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  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

graphiql's Issues

codemirror widths and lefts are so large they push codemirror to right edge of browser

using babel and webpack-dev-server to bundle and serve the the rendered GraphiQL component. For some reason the margin-left and certain width style properties are set to almost the entire width of the screen so all i see is a blank space and then the first character of each code line up against the right side of the browser window

<div class="CodeMirror-sizer" style="margin-left: 1904px; margin-bottom: 0px; border-right-width: 30px; min-height: 675px; min-width: 619px; padding-right: 0px; padding-bottom: 0px;">
   <div ....>....
  </di>
</div>

screen shot 2015-09-15 at 11 03 30 pm

Results render before all promises resolved, do not update

with large (long running) queries, the results render before all of the promises have resolved and do not update once they have completed.

In my implementation, due to the concurrency of resolve methods, I hit many API # of connections limitations. so I delay 1second and reattempt for a set number of tries. According to my logs that part works great but the results returned in graphical do not show a good portion of the data returned.

Graphiql not working

Graphiql not working with the latest version of react.

Warning: React.findDOMNode is deprecated. Please use ReactDOM.findDOMNode from require('react-dom') instead.

Uncaught TypeError: Cannot read property 'length' of undefined.

Embedding GraphiQL + html overflow: hidden

I'm trying to embed GraphiQL in a site however the overflow: hidden at the top off app.css prevents the rest of my site from working (as a single page app everything shares a single css file):

html, body {
  height: 100%;
  margin: 0;
  overflow: hidden;
  width: 100%;
}

Would it be possible to extract the shared css into a file and move the html + body height fixes to a separate file for standalone GraphiQL setups?

Open source license

The license included in the LICENSE file for this project does not look like any standard open source license.

Facebook, Inc. (“Facebook”) owns all right, title and interest, including all
intellectual property and other proprietary rights, in and to the GraphiQL
software. Subject to your compliance with these terms, you are hereby granted a
non-exclusive, worldwide, royalty-free copyright license to ...

What license is this?

Is there a reason why this project could not be licensed with a normal OSI approved license like the BSD License used in GraphQL.js? I think this would ensure compatibility with open source licenses and that people using GraphQL can use GraphiQL without having to consult their lawyers about the custom license.

Render HTML responses

There's no real feedback if a server responds with something other than a 200 with correct query data.

It would be awesome if GraphiQL could either render the server response directly (using an iframe with HTML5 srcdoc), or provide a hook to do so manually.

React versions clash with Relay and Graphiql

When using graphiql in Relay app, getting following issue on npm install:

npm ERR! peerinvalid The package react does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react@~0.13.x || ~0.14.x
npm ERR! peerinvalid Peer [email protected] wants react@^0.14.0-beta3

package.json content:

"dependencies": {
    "classnames": "^2.1.3",
    "express": "^4.13.1",
    "express-graphql": "^0.3.0",
    "graphiql": "^0.1.0",
    "graphql": "^0.4.2",
    "graphql-relay": "^0.3.1",
    "isomorphic-fetch": "^2.1.1",
    "jade": "^1.11.0",
    "moment": "^2.10.6",
    "react": "^0.14.0-beta3",
    "react-relay": "^0.1.0",
    "react-router": "1.0.0-beta3",
    "relay-nested-routes": "^0.3.1",
    "require-dir": "^0.3.0"
  }

"graphql" being a devDependencies make it impossible to use in a dependent project

I have a project that depends on graphiql AND graphql, but I'm getting Error: Schema must be an instance of GraphQLSchema. Also ensure that there are not multiple versions of GraphQL installed in your node_modules directory.

and I actually have both node_modules/graphql and node_modules/graphiql/node_modules/graphql .

I don't think graphiql should devDep on graphql in the first place, because it's already a peerDep

Schema is undefined, even after successful introspection query

I'm trying to hook this up to an automatically generated Ruby backend, so I'm almost sure that the root cause is on my end, but I'm not sure what else to check :)

I've cloned the repo & built the example, then copied graphql.min.js, graphql.css, and index.html into my own project. I tweaked the fetcher a bit to point at my endpoint and include cookies.

At this point, when I load the page, GraphiQL makes its request for the schema, and I can see the expected result coming back:

image
(full dump)

However, I don't get any type hinting, and when I try to submit a query, I get an error:

image

I can see it's coming from here:

image

Which is here: https://github.com/graphql/graphql-js/blob/81a7d7add03adbb14dc852bbe45ab030c0601489/src/utilities/TypeInfo.js#L125-L127

So ... somehow that local variable schema is undefined. I know I'm a long way down a lonely road, but do you have any suggestion what I can check next? Do you think my endpoint is responding properly? Is there something else I can test?

Error with rendering when using alongside another version of React

When I include GraphiQL inside my application alongside Relay, I get the following error when trying to render the component:

Uncaught TypeError: Cannot read property 'firstChild' of undefined

I did some Googling, and it seems to suggest there may be 2 versions of React present. My package.json file looks like this:

  "dependencies": {
    "assets-webpack-plugin": "^2.2.0",
    "babel-loader": "^5.3.2",
    "babel-relay-plugin": "0.1.2",
    "babel-runtime": "^5.8.20",
    "basscss": "^7.0.3",
    "basscss-border-colors": "^1.1.1",
    "classnames": "^2.1.3",
    "css-loader": "^0.16.0",
    "cssnext-loader": "^1.0.1",
    "file-loader": "^0.8.4",
    "graphiql": "^0.1.0",
    "graphql": "^0.4.2",
    "graphql-relay": "^0.3.1",
    "react": "^0.14.0-beta3",
    "react-dom": "^0.14.0-beta3",
    "react-relay": "^0.1.1",
    "react-router": "^1.0.0-beta3",
    "relay-nested-routes": "^0.3.1",
    "style-loader": "^0.12.3",
    "url-loader": "^0.5.6",
    "webpack": "^1.11.0"
  }

If I go ahead and delete rm -rf node_modules/graphiql/node_modules/react, then rendering works a treat!

GraphiQL expects 200 status for errors

In order to render an error on the right panel, GraphiQL expects the response to have a 200 status. In case of a bad query, the server needs to respond with 200 in order the see the error in the UI.

We had a case where bad queries were send to the server e.g. asking for something that doesn't exists. Looking at the server logs wouldn't show the issue as everything was 200. So we changed our graphql server to return 422 on bad queries.

But now GraphiQL doesn't show anything on the right, as it expects 200.

So I am not sure about this, is this a graphql spec issue or should GraphiQL handle some errors and try to render the response?

Add response time and size

After each request, it'd be nice to see the response time + size of the response in KB somewhere. E.g. 251ms, 23.3kb

Ctrl+T (for opening a new tab) gets blocked

In OSS GraphiQL, if I have the cursor in the results section (e.g. I highlighted something to copy), ctrl+t seems to get blocked/captured, and it doesn't open a new tab. On Firefox/Ubuntu.

Looks like the editor traps any ctrl + key for the suggestion popup, might be causing the issue.

cannot get queryType of undefine

when recreating the query from the README verbatim I get the error in the title in Chome 45.0.2454.101 and Firefox 41.0.1 OSX 10.9.5

"prettify" query

my common usecase is to paste a query that was generated by Relay and see what it does.

However, the Relay queries are pretty obfuscated, it would be great to have a button that prettify the query textarea.

I was playing around with this code:

function blockIndent(editor, from, to) {
  editor.operation(function() {
    for (var i = from; i < to; ++i)
      editor.indentLine(i, "smart");
  });
}

but it just indents, it does not do the "return to new line" work.

Direct link to query

First off this is very cool! It'd be great to be able to share a link to a particular query, is this in the works?

Can't query for fields on a type

This query results in type.getFields is not a function.

query ShipTypeQuery {
  __type(name:"Starship") {
    fields
  }
}

Edit: s/Ship/Starship/

Saving queries/mutations?

I was wondering if it could possibly be a feature to maybe save queries/mutations written to local storage or something without complicating the UI too much. I'm not familiar exactly with the scope of what graphiql is meant to solve and what its not meant to solve, but that could possibly be a neat feature.

live demo does not work

The live demo seems to be faulted.
No matter the query input the response is always:
SyntaxError: Unexpected end of input

Example input query:

{
  allStarships{
    starships{
      name
    }
  }
}

but i have tested several other queries with the same result.

It seems like the parser expects some more characters, but the current error response does not allow for any really constructive examination of what is wrong.

Opt-in to accepting mutations on GET

Performing mutations on an http GET request is typically bad behavior. It's usually only presumed safe to do this if providing some single-use token to avoid CSRF attacks.

express-graphql should not execute mutations on GET requests unless some opt-in is provided.

example fails to run

I'm using node v5.1.0 and npm 3.3.12 which is probably the cause of this.

after having properly npm install (in example/),
when running npm start, the build.sh will fail:

 @ prestart /Users/gre/perso/graphiql/example
> npm run build


> @ build /Users/gre/perso/graphiql/example
> . build.sh

cp: node_modules/graphiql/graphiql.js: No such file or directory

Expose errors in building schema

As #16 encountered, if an introspection result causes issues with building a client schema today we just silently continue without a schema - instead we should present some error so the developer can quickly find and fix the issue.

Schema must be an instance of GraphQLSchema

Hello,
I get this error when hitting /graphql with browser:

{
  "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."
    }
  ]
}

any suggestion? My schema is an instance of GraphQLSchema...and graphql appears only once in package.json

thanks

Docs button doesn't work in 0.42 using Firefox

I'm attempting to use this example. Running:

node index.js

then hitting http://localhost:3000 in Firefox 42.0 with all addons disabled produces the following unhelpful error when I click Docs:


TypeError: e.split is not a function
error source line:


...o),t=i+1)}return r}:function(e){return e.split(/\r\n?|\n/)},es=window.getSelecti...


graphiql.min.js (line 9, col 824)

Seems to work fine in Chrome, but fails in Firefox 42.

Thanks.

Graphiql height is not 100%

When I open Graphiql it looks like this
screen shot 2016-02-03 at 11 35 53

It looks like that html and body tags need to have their height set to 100% so the layer #graphiql-container can expand too.

I've tried also opening in safari and in chrome on incognito window (without any extension running) and the same happens.

Cmd-Space key combination conflicts in OS X

In OS X, multilingual users use Cmd-Space key combination to switch between input methods. And Ctrl-Space is mapped to Spotlight shortcut key.

It would be better if some other key combination is added, like Option-Space. (Originally I was going to send a pull request, but didn't come up with the key combination that feels right 😞)

How to use Graphiql when /graphql protected by JWT token (authorization header)

My /graphql route is protected by JWT token, so every HTTP request needs to set:

 headers: {
      Authorization: 'Bearer ' + token
    }

To get through the authentication middleware and hit /graphql.

How to manage this authentication step when using graphiql ? graphiql is so convenient, it's a pity to not use it :(
thanks for any suggestion!

Error while running example

Issue

  • project assumes babel and browserify are installed globally

I cannot run: npm install simply because I don't have babel and browserify installed globally, and I think this would be most of the cases.

Possible solution

Quick hack would be to include graphiql.css and graphiql.min.js in the project, but that would increase the size of it.

Or just change the way the resources are being built.

Execute named operation under a cursor

When I'm working with GraphiQL, more often than not, I have several queries in the editor pane. A typical use-case is to have a mutation and query around in order to make changes and see their effects on different queries.

At the moment I need to comment out all of the queries except one I would like to execute. It can become tiresome after some time. That's because I would like to suggest an alternative approach: an ability to execute query under the cursor. As far as i saw, this is pretty common feature available in similar applications. For instance, I use this feature a lot in elasticsearch sense (which is now part of marvel plugin) and find it pretty useful.

So the idea would be to either have a separate context sensitive shortcut/button or make existing shortcut and "run" button context sensitive. If an editor cursor is positioned somewhere inside of some named query, then in addition to a query, GraphiQL will also send the operation name to a server.

Webjars support

Hi,

I'm trying to embed graphiql in my Play! app. In order to get the dependency in my project the most popular way (for js/css/html) is via webjars which packages npm modules (also bower packages) into jars to be included in JVM apps.

The problem is, when trying to deploy the latest version of graphiql to webjars, it fails to read the license with the following message:

Failed! No valid licenses found. Detected licenses: See LICENSE The acceptable licenses on BinTray are at: https://bintray.com/docs/api/#_footnote_1 License detection first uses the package metadata (e.g. package.json or bower.json) and falls back to looking for a LICENSE, LICENSE.txt, or LICENSE.md file in the master branch of the GitHub repo. Since these methods failed to detect a valid license you will need to work with the upstream project to add discoverable license metadata to a release or to the GitHub repo.

The problem seems to be that the license field in package.json is set to See LICENSE, instead of the name of the license. I really don't know if this is supposed to be like this, but I'm wondering if there is any other way we could specify the license that would make webjars work.

In order to reproduce the problem:

  1. go to http://www.webjars.org/npm,
  2. On the top right cornet click on Add a new NPM WebJar
  3. Type graphiql in the name
  4. Select 0.1.1 in the version
  5. Click Deploy!

Another issue could be that graphiql license is not compatible with WebJars. See full list in this footnote. I'm not sure about this either.

Thanks for your time.

HTML embedded in description field is not escaped

Steps to reproduce

  • Define a graphql type with a description field that contains markup. For example <input type="checkbox">
  • Inspect the type in docs panel in graphiql

Expected behaviour

  • The string <input type="checkbox"> is shown in docs panel

Actual behaviour

  • A checkbox is shown in the docs panel

screenshot 2015-12-19 02 39 57

As far as I can tell, it's just a matter of adding {sanitize: true} as a config option when calling the marked function.

Fallback introspection query never actually happens

Just starting messing with GraphiQL and the graphql-java implementation, which doesn't support subscriptionType yet. According to #55, this was fixed with a fallback query, but it seems to be implemented by catching the fetcher's result.

The thing is... it appears that the fetcher is not actually supposed to (and, at least in the example directory, does not) throw, at least in the case of a standard GraphQL error!

For reference, the result that is returned when introspection fails is this:

{
  "errors": [
    {
      "validationErrorType": "FieldUndefined",
      "message": "Validation error of type FieldUndefined: Field subscriptionType is undefined",
      "locations": [
        {
          "line": 6,
          "column": 7
        }
      ],
      "errorType": "ValidationError"
    }
  ],
  "data": null
}

I also tried manually throwing in the fetcher if the result contains errors; this works, but degrades the user experience as normal validation errors will not show up in the right-hand panel.

Keyboard shortcut to add all fields

There are times when I want to add all fields then remove some. I'd be fantastic l if there was a way to add all fields in a given navigation context using a keyboard shortcut.

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.