Code Monkey home page Code Monkey logo

graphql-language-service'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.

graphql-language-service's People

Contributors

acao avatar ags- avatar ajhyndman avatar asiandrummer avatar benjie avatar danez avatar greenkeeper[bot] avatar greenkeeperio-bot avatar hansonw avatar jimkyndemeyer avatar leebyron avatar lostplan avatar mgadda avatar romanhotsiy avatar schickling avatar shashkambham avatar stephen avatar wincent avatar yan-j 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

graphql-language-service's Issues

Incompatible graphql-language-service-utils

In npm, the current version of graphql-language-service-utils is 1.2.1 which seems to have issues when resolved transitively by the other older components.

Forcing graphql-language-service-utils to 1.2.0 resolves our build issue.

Consider removing multi-app support in configs

According to .graphqlrc redesign proposal and my strongly feeling that multi-app is evil in this config file - I ask you to consider removing multi-app from graphql-language-service. Let try to implement your monorepo needs in some other way.

Current problems which I see now with graphql-language-service:

1. Problem with getConfigByFilePath, it may returns wrong config

Inspecting graphql-language-service I found that this code that may bring problems:

  getConfigByFilePath(filePath: Uri): ?GraphQLConfig {
    const name = this.getConfigNames().find(configName =>
      this.getConfig(configName).isFileInInputDirs(filePath),
    );
    return name ? this._configs[name] : null;
  }

It determines by filePath in input dirs app specific config and return it. So the problem may be if several apps will have the same file in input-dirs. You will get first config, but in reality may be needed another config.

2. CLI interface missing option

CLI may be pointed to multiapp config, so it should be somehow informed which config needs to take. In this case needed an additional option which will point to needed app name.

On the other hand, adding this option we complicate integration with IDE (it can not automatically choose the correct app, will need to provide some dialog window where a user chooses needed app). So as joke solution we may add one more dot-rc file.


So if we make restriction, that .graphqlrc contains only one app, all above problems disappears. Of course need to solve your monorepo problem. If you provide some real case, maybe we can find another solution together?

Local test runs busted

Seems like the recent refactoring to use Workspaces/Yarn/Lerna has broken the CI in a few different ways. For example, see #139 (about Flow errors).

Top-level yarn run testonly is dying locally and in CI with:

Error: Cannot find module 'graphql-language-service-utils'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/glh/code/graphql-language-service/packages/interface/src/__tests__/getAutocompleteSuggestions-test.js:17:1)
    ...

And you can't run the tests in the sub-dirs as they all have stubs like this defined:

    "test": "echo 'Please run `npm test` from the root of the repo' && exit 1",

Top-level build* scripts are also busted, so I am removing them in #144 — we can replace them with something else that actually works.

Seems like we're flying pretty blind at the moment with respect to tests, Flow etc. cc @asiandrummer for visibility.

GraphQL Language Service master task

TODO before the release

  • Complete test suites imported from codemirror-graphql and written for server/configuration/utils.
    • Improve test suites for the parser
  • Command-line interface improvement to support locating .graphqlrc
  • Better error Handling - find erroneous use cases that exits the server or sends a RPC message with 'error' type.

Nice-to-haves before/after the release

  • caching unsaved/edited file contents in GraphQLCache.
  • Custom validation rules
  • pretty-printed CLI outputs

Also, I'm not sure where this one fits but https://code.visualstudio.com/blogs/2016/06/27/common-language-protocol summarizes the architecture for implemented GraphQL server interface pretty well as a superset. It's probably worth mentioning and finding a place to collaborate with this protocol.

Please feel free to add/edit the items above.

GraphQLCache._readFilesFromInputDirs should handle case where glob stat result is `false`

Normally all of the results for an npm-glob operation are files or directories that really exist. As a result, globResult.statCache contains a Map<string, Stat>. However, under some circumstances (TBD), some glob patterns, like those which are just simply a path to a file that does not exist, cause the statCache to have type like Map<string, Stat | bool>. Since bool obviously does not define an mtime property, this code blows up:

Object.keys(globResult.statCache).map(filePath => ({
  filePath,
  mtime: Math.trunc(
    globResult.statCache[filePath].mtime.getTime() / 1000,
  ),
  size: globResult.statCache[filePath].size,
}))

This issue was first reported here: stephen/vscode-graphql#17 (comment).

Initial fragment caching does not work for some glob patterns

If .graphqlconfig contains an includes key, with only a single glob such as below, the resulting set of matched files will always be empty.

{
  "includes": [ "{path/to}/**/*.{js, graphql}" ]
}

In the above example, glob would ultimately look for files ending in .js or .graphql which are literally in a directory called {path/to}.

This occurs because the underlying library performing the globbing (minimatch), does not expand glob braces when there's only a single value inside those braces. For instance, some implementations of glob (such as your shell) expand {foo} into foo. Minimatch does not perform an expansion in this case. It's unclear if this is by design or not.

When includes contains multiple glob paths, this behavior does not occur because, as one would expect, minimatch correctly expands {path/a,path/b}/**/*.{js, graphql} into ['path/a/**.{js, graphql}', 'path/a/**.{js, graphql}'].

The end result is that fragments are not cached when graphql-language-service first loads in the above case. Caching is thus delayed until each file has changed (a fact which is learned only after being notified by watchman or via language service protocol).

Keep Greenkeeper integration alive

Scary warning on the last pull request that I looked at saying we need to re-"install" our Greenkeeper integration as it is going to stop working at the end of the month. I don't think we have admin privileges over the repo now though. cc @asiandrummer

🚨🔥⚠️ Action required: Switch to the new Greenkeeper now! 🚨🔥⚠️
This version of Greenkeper will be shutdown on May 31st.

Seen at: #114

Upgrade graphql dependency

graphql 0.12.x is out and this repo requires 0.11.x (which is treated like a semver major difference)

If you use GraphiQL for example, this means duplicate versions of graphql are installed and warnings/errors occur.

This came up before in the last graphql update.

PRs:
#192
#193

Warnings with webpack

When this package is bundled with webpack, warnings are emitted ("Critical dependency: the request of a dependency is an expression") because of the dynamic requires here:

const rulesPath = require.resolve(customRulesModulePath);
if (rulesPath) {
customRules = require(rulesPath)(this._graphQLConfig);

I encountered this when upgrading graphiql to 0.10.2, which depends on codemirror-graphql, which depends on this.

GraphQL Language Service IntelliJ plugin

Hi @jimkyndemeyer and @martijnwalraven - I've been talking to you guys individually, but you guys have experiences/working examples of the IntelliJ plugin for GraphQL Language Service, which is amazing btw :D I just wanted to initiate the discussion for us to collaborate together in creating a IntelliJ plugin using this GraphQL Language Service and the server!

For the actual details to making it happen I have less preferences - I thought that we could either work together on already-existing @jimkyndemeyer's IntelliJ plugin and improve that, or start from the scratch depending on how the plugin development is structured and etc. You guys obviously have a better idea how this goes, but I'm here to help as much as I can.

Also, note that by us working together to implement this, we can make any changes we want in this graphql-language-service repo to fit your needs when this is still a private repo. Let me know how we can proceed!

Online schema support

I suggest that graphql-language-service should prefer to use the online schema when an endpoint is specified in .graphqlconfig, and only on failure fall back to the schemaPath on disk.

This does leave open how a client might specify which endpoint to use when more than one is specified. Potentially this could be (optionally) specified in server Options. Edit: graphql-config by default will read process.env.GRAPHQL_CONFIG_ENDPOINT_NAME for the endpoint name so perhaps it is ok not to accept a name via config.

N.b. graphql-config has an endpoints extension for resolving online schemas.

`graphql-config` discussion

This is a brain dump to get us started for discussing having the shared GraphQL configurations (at least the agreed common format of it). @schickling - please feel free to add anything that I've missed and/or misspoken of.

@schickling and I talked about an idea for a generalized configuration for GraphQL applications - since GraphQL-powered environments usually include information about the GraphQL artifacts (such as the location and specifications within the application directory), the idea is basically to define the information within one file, such as .graphqlrc.

What .graphqlrc currently supports, based on how this repository expects, is:

{
  "build-configs": [
    "app1": {
      "input-dirs": [
        "/dir/paths/to/your/graphql/files"
      ],
      "exclude-dirs": [
        "/dir/paths/to/ignore/"
      ],
      "schema-path": "/path/to/the/schema/"
    },
    "app2": { ... }
  ]
}

In above JSON, input-dirs and exclude-dirs are useful to determine where your GraphQL queries/fragments are defined if you have a complex directory structure. schema-path suggests where to look for a GraphQL schema definition, and it can parse .graphql or .json file.

After discussing with @schickling for a bit, a high-level proposal that came out was to suggest this shared GraphQL configuration idea as one of the best practices to develop GraphQL applications, and implement an example (or a reference implementation) for how one may set up the GraphQL configuration (one place suggested is an existing graphql-config repository). In addition to what the above JSON suggests, @schickling also had an idea to be able to customize the expected value for some of the configuration entries:

  • schema-path can be a local path to the GraphQL schema definition within the application, or an URL to the endpoint that would be used to fetch GraphQL introspection:
"schema-path": {
  "endpoint": "https://localhost:8080/graphql",
  "localPath": "/local/dir/path" // This would be an optional fallback schema definition
}

This is not to require all GraphQL configurations to limit its potential to the above configuration options only - I can imagine some apps would like to define their own configuration options (i.e. Relay apps including Relay-related config options and such).

I'd love to hear what everyone thinks of this!

Warning: You may need an appropriate loader to handle this file type.

getting 6 big scary yellow warnings all of this nature when trying to use the graphiql React component.. how do i silence this please?

WARNING in ./~/graphql-language-service-interface/dist/getOutline.js.flow
Module parse failed: ROUTE_TO_ABOVEMENTIONED_FILE Unexpected token (11:12)
You may need an appropriate loader to handle this file type.
|  */
|
| import type {
|   Outline,
|   TextToken,
 @ ./~/graphql-language-service-interface/dist ^.*$
 @ ./~/graphql-language-service-interface/dist/GraphQLLanguageService.js
 @ ./~/graphql-language-service-interface/dist/index.js
 @ ./~/codemirror-graphql/hint.js
 @ ./~/graphiql/dist/components/QueryEditor.js
 @ ./~/graphiql/dist/components/GraphiQL.js
 @ ./~/graphiql/dist/index.js
 @ ./client/components/graphql.js
 @ ./client/components/user-home.js
 @ ./client/components/index.js
 @ ./client/routes.js
 @ ./client/index.js

Globs specified by .graphqlconfig includes are not honored as intended by spec

According to the graphqlconfig spec, the string values contained within the includes value of .graphqlconfig (either top-level or project-level) are to be treated as file globs. However, graphql-language-service makes some incorrect assumptions about the structure of those globs (e.g. that they contain wildcards) and then replaces a portion of the glob with a hard-coded definition. Here's an example:

{
  "includes": [ "path/to/**/*.graphql" ]
}

"path/to/**/*.graphql" gets truncated at the first wildcard, then *.{js,graphql} is appended to produce:

"path/to/**/*.{js,graphql}"

While the set of .js and .graphql files isn't a bad set from which to extract queries and fragments, it's not actually what the user intended in this case (i.e. they intend to include JavaScript files).

I think the only reasonable expectation a user can have about how includes should behave is as defined by the spec.

File change notifications delivered via watchman do not work if there are projects specified in .graphqlconfig

This is a bug that shook out the refactoring to make watchman optional #218. If watchman is installed on the user's system, we need to subscribe the loaded project or projects from .graphqlconfig to file change events. However, it looks like in the case where the .graphqlconfig didn't define any projects, that is, it just contains top-level data about the project, this line blows up because config.getProjects returns undefined.

The simple fix should be:

let projectConfigs: GraphQLProjectConfig[] =
        Object.values(config.getProjects() || {}) || [];

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.