Giter Club home page Giter Club logo

graphql-config's People

Contributors

acao avatar akre54 avatar ardatan avatar asiandrummer avatar beerose avatar charlypoly avatar dependabot-preview[bot] avatar dependabot[bot] avatar dimamachina avatar dotansimha avatar gilgardosh avatar github-actions[bot] avatar greenkeeper[bot] avatar ivangoncharov avatar jnwng avatar kamilkisiela avatar kbrandwijk avatar lvarayut avatar n1ru4l avatar peterdresslar avatar renovate-bot avatar renovate[bot] avatar romanhotsiy avatar saihaj avatar schickling avatar stephen avatar timsuchanek avatar tuvalsimha avatar tvvignesh avatar urigo 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

graphql-config's Issues

How do I work with two endpoints?

Currently I'm using something like the following to work with two different endpoints that I switch between in my work (a local and a remote), with the consequence that I (need to manually) overwrite the schema file when I switch between them.

Is there a way to do this with a different schema file for each endpoint? What is the correct idiom for working with (and switching between) two endpoints?

{
  "name": "My Schema",
  "schemaPath": "_schema.graphql",
  "extensions": {
    "endpoints": {
      "Local GraphQL Endpoint": {
        "url": "http://localhost:5000",
        "headers": {
          "user-agent": "JS GraphQL"
        },
        "introspect": true
      },
      "Remote GraphQL Endpoint": {
        "url": "http://my.remote.io",
        "headers": {
          "user-agent": "JS GraphQL"
        },
        "introspect": true
      }
    }
  }
}

A new path for graphql-config - help us decide on the roadmap!

Hi everyone!

I'm @Urigo the founder of The Guild.

As recently been announced on the Prisma blog, we are taking over the maintenance of this library going forward.
I've expressed it in the blog post in more details but I would like to start by thanking Prisma for conceiving, creating and maintaining this library so far and also for doing the selfless act of providing it with fresh life by handing over the maintenance to us.

We already have a certain plan in mind going forward, some of it we've specified in the blog post, but we want you, the users and community of the library to be part of influencing the roadmap going forward.

One thing to note about The Guild - We place all the open source packages we maintain under individual person's Github profile instead of under a GitHub org or a company.
That is part of our philosophy - it puts more accountability on the maintainer and it also lowers the barrier of creating successful competing forks.
So we will transfer that repository from under Prisma as part of the transition.

I'm looking forward to start the discussion here below.
Please share how and why you use the library today, what are your biggest pain points today and ideas and features you would like to see in the future.

I will add points into the description here as we go.

Let's make this happen!

Local schema as npm dependency

Hi guys,
I have dependency in my project which contains the schema file. It seems I can't get the config right, or at least my IDE (webstorm) seems to be ignorant of the schema file. Some help would be appreciated. Thanks!

{
  "schemaPath": "./node_modules/@foo/graphql-schema/schema/schema.graphqls",
  "extensions": {
    "endpoints": {
      "local": {
        "url": "http://localhost:8000/graphql"
      }
    }
  }
}

Allow the file to be named .graphqlconfig.json

Howdy,
I'm working on tools in the GraphQL ecosystem and like the idea to have a unified configuration file that can be shared by many tools.

Unfortunately, I find the editing experience of the .graphqlconfig file to be a bit unpleasant at the moment.

Issue #52 tracks the idea to provide a JSON schema to allow editors to autocomplete code, which would help a bit. In addition, I want to make the case for allowing the config file to be named .graphqlconfig.json:

  • It would immediately improve the editing experience in most code editors, checking for syntax errors, highlighting code and providing auto-formatting, without needing to install another extension.
  • It is the obvious companion to the already allowed .graphqlconfig.yaml
  • It would bring home the message that the file format is, in fact, JSON.
  • Existing .graphqlconfig files would of course still be supported.

It is not clear to me if there is any reason why using the json extension for the config file would not be allowed, but I was also unable to find any previous discussion on the issue.

How to create the schema.graphql file ?

Hi,

I wonder if anyone can help ? I know this format is used by other programs but I am just wanting to create a schema file from an endpoint.

I have the following

projects:
  blog:
    schemaPath: schema.graphql
    extensions:
      endpoints:
        default: "http://localhost:3000/___graphql"

Is there some kind of util to create this schema.graphql file ?

Error when using along with the graphql-cli

I have tried to investigate problem and it looks like all of my dependencies are hoisted in root, but somehow graphql-config is not

[wtrocki@wtrockigraph generator-example (layered-resolvers โœ—)]$ graphql codegen
{ Error: Cannot find module 'globby'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at /Users/wtrocki/.nvm/versions/node/v10.15.3/lib/node_modules/graphql-cli/node_modules/graphql-config/index.js:480:105
    at new Promise (<anonymous>)
    at LoadersRegistry.<anonymous> (/Users/wtrocki/.nvm/versions/node/v10.15.3/lib/node_modules/graphql-cli/node_modules/graphql-config/index.js:480:46)

Couldn't find a GraphQL config.

Hi everyone.

Thanks for your work. :)

Using reacty-relay and babel-plugin-react-relay I am getting the following error:

Module build failed: Error: Couldn't find a GraphQL config. Please refer to https://github.com/graphcool/graphql-config
    at Array.map (native)

I can't figure out what is going wrong. I set up graphql settings in package.json and a .graphqlconfig file, but for some reason its not found. Don't know where to look or what to try anymore. Some help would be appreciated.

package.json:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:8000/",
  "dependencies": {
    "mobx": "^3.2.1",
    "react": "^15.6.1",
    "react-bootstrap": "^0.31.1",
    "react-dom": "^15.6.1",
    "react-relay": "^1.1.0",
    "react-router": "^4.1.2",
    "react-router-dom": "^4.1.2",
    "react-scripts": "^1.0.10",
    "relay-runtime": "^1.1.0"
  },
  "scripts": {
    "relay": "relay-compiler --src ./src --schema ./schema.graphql",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "babel-plugin-react-relay": "^0.10.0",
    "relay-compiler": "^1.1.0"
  },
  "babel": {
    "plugins": [
      "babel-plugin-react-relay"
    ]
  },
  "graphql": {
    "schemaPath": "./schema.json"
  }
}

.graphqlconfig:

{
  "schemaPath": "schema.json"
}

Cheers!

Joey

Deciding which project a file belongs to

An IDE or language server needs a way to decide what schema to use to interpret a particular file. Although projects in the .graphqlconfig can specify includes/excludes, there is nothing keeping these from overlapping.

The current implementation of getConfigForFile always returns the first project that includes a file. If that is the intended behavior, we should probably make that part of the spec.

One situation that seems counterintuitive if we do so is if project A doesn't specify any includes/excludes, but project B explicitly includes a file. If project A is listed first in the config, it will match every file, and project B will be ignored.

Ignoring port

# graphql get-schema
Downloading introspection from http://api.mysite.dev:8888/graphql
request to http://api.mysite.dev:8888/graphql failed, reason: connect ETIMEDOUT 10.0.75.1:80

{
  "schemaPath": "schema.graphql",
  "extensions": {
    "endpoints": {
      "dev": "http://api.mysite.dev:8888/graphql"
    }
  }
}

Host file:
10.0.75.1 api.mysite.dev

Usage information incorrect: `loadConfig` doesn't exist

Using v2.2.1, there is no exported member for loadConfig in graphql-config, unless I'm missing something here?

import {loadConfig} from 'graphql-config';

async function main() {
  const config = await loadConfig();

  const schema = await config.getDefault().getSchema();
}

I also assume this will return a GraphQlConfig type, which then has no exported members for getDefault().

Reference info from separate files

Like the serverless framework I think we should be able to reference specific vars from external files (e.g json, yaml, JS files) to configure our endpoints. In my particular flow, there's a complicated auth process to which I tap in and write the token to an external file after finished. Given we've no access to the shell that tools like Playground ran from, we can't update the env var. For now, we're modifying this file directly but it's a hassle to avoid committing to VCS.

Only works with npm run start

It only picks up the config if I run npm run start, that is, run the packager manually. If I run react-native run-ios it won't pick it up

Running graphql get-schema project_name gives an error, because of incorrect relative path of prisma.yml

I have this file structure:

  • workspace
    .graphqlconfig
    • servers
      --- prisma
      --- app
      --- admin
    • clients
      --- relay-native
      --- react-graphql

.graphqlconfig:

{
	"projects": {
		"graphql": {
			"schemaPath": "servers/app/src/generated/prisma.graphql",
			"extensions": {
				"prisma": "servers/prisma/prisma.yml"
			}
		}
	}
}

So that .graphqlconfig is placed in the root of workspace.
I run this:

cd servers/app
graphql get-schema -p graphql
ร— servers/prisma/prisma.yml could not be found.

if I update my config with this line:
"prisma": "../../servers/prisma/prisma.yml"
everything works okay then.
So I guess its a bug, that should be fixed

I want to have at least 2 applications for one prisma server.. its usually 1) app 2) admin... pretty logical.. different endpoints.. different auth rules, security flows and so on.
and I want auto update schemas in all applications when I change prisma schema... current approach support updating only one app.. well.. maybe i'm wrong.. this type of project structure looks to me pretty logical, but i'm not able to configure it properly for some reason

Support directories for `includes/excludes` values

With the 1.0.0 release, there now exists a rather stricter rule around the format of values in includes/excludes - they should only be globs.

Note: excludes and includes fields are globs that should match filename.

Instead of this, what do you think about supporting directory paths:

// below two should basically be the same patterns
"foo/bar/**"
"foo/bar"

?

cc @RomanGotsiy @schickling

Support loading unwrapped schema.json file

It would be nice to support loading schema.json files that do not have the { "data": {}, "errors": [] } wrapper.

Other libraries support this by only passing introspectionResult.data if it exists.

While I do think this makes things a little more ambiguous, it seems nice to either implicitly support these files, or explicitly allow a user-configurable option to load non-wrapped introspection schemas. I would be curious to see if there is a good use case for wanting to write an error-result to a schema.json in the first place.

wdyt? I would be happy to send a PR for either.

Create PRs for GraphQL plugins

Support alternative file extension for GQL files

Hello,

And thank you for this library!
It's nice to have a standardized way for handling configurations.

One little thing that bugged me today, is that I cannot directly use my existing *.gql schema files because they don't have the required file extension :(

Maybe we could change this?

I can provide a PR with the basic change (add case '.gql') but no need for a PR I guess :)
Or with something more advanced if you have some ideas of improvements?

Environment variable expansion should allow default values

This is similar to the local dev/CI use-case in #46. It would be helpful to be able to provide default values for environment-variable configurations. So that the default is used normally, but the configuration can still be overridden locally without modifying the config file.

Make graphql-js work with ES6 module

The graphql-js option currently doesn't support ES6 module. If we exported a schema.js using ES6 syntax, as the following example, it will break:

export default  new GraphQLSchema({
  query: QueryType
})

Wrong peerDependencies?

I'm using GatsbyJS and it seems that it is installing this package which gives me this error:

npm WARN [email protected] requires a peer of graphql@^0.11.0 || ^0.12.0 || ^0.13.0 but none is installed. You must install peer dependencies yourself.

Is this correct? I'm using graphql 14.x and I get no errors with Gatsby on building my website.

Can't find graphql config

I've defined both in the package.json like this:

"graphql": {
    "request": {
      "url": "https://api.graph.cool/relay/v1/cj2b3cy...3556gi9j5u"
    }
  },

and exported the environment variable like this:
export GRAPHQL_ENDPOINT="https://api.graph.cool/relay/v1/cj2b3cy...3556gi9j5u"

And I'm running react-native run-ios

Even with these both set, I receive the message saying it can't find the config.

Am I doing something wrong?

`.graphqlrc` redesign proposal

@schickling and a group of contributors including myself discussed how a common GraphQL configuration would look like, and thought of redesigning the current implementation of graphql-config as well as including some new suggestions. Since GraphQL-powered environments usually include information about the common set of GraphQL artifacts (such as the location and specifications within the application directory), the idea is basically to recommend a commonly-used format/options within .graphqlrc, and provide some helper methods and use cases from other applications that already incorporate this concept.

A minimal .graphqlrc config file would consist of a JSON blob such as:

// Let's assume there is a directory that acts as one repository.
// For a single application within a directory,
{
  "schema-path": "url/to/your/endpoint/or/local/schema/path",
}
// For more than one application within a directory,
{
  "app-1-name": {
    "schema-path": "url/to/your/schema"
  },
  "app-2-name": {
    "schema-path": "url/to/your/schema"
  }
}

To support more use cases, .graphqlrc would have a potential to evolve into something a bit more complicated. For instance, user might need to specify which sub-directories to look into for .graphql files and other GraphQL-related artifacts. Also, 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.

To list these capabilities below:

{
  "app-1-name": {
    "schema-path": "url/to/your/schema",
    // the list of directories to look for GraphQL artifacts/queries
    "input-dirs": [
      "foo/bar",
      "foo/bar/baz"
    ],
    // the list of directories to ignore while looking for GraphQL artifacts/queries
    "exclude-dirs": [
      "a/b/c"
    ],
    // specifying customized validation rules if available
    "custom-validation-rules": "./customRules.js"
  },
  "app-2-name": {
    "schema-path": {
      "endpoint-url": "https://url",
      "local-schema-path": "./schema.graphql"
    },
    ...
  }
}

In a pseudo-flowtype format:

type GraphQLRC = {
  [appName: string]: GraphQLAppConfig
} | GraphQLAppConfig;

type GraphQLAppConfig = {
  schemaPath: URL | FilePath | {
    endPoint?: URL,
    localSchemaPath?: FilePath
  },
  inputDirs?: Array<DirPath>,
  excludeDirs?: Array<DirPath>,
  customValidationRules?: FilePath | Array<FilePath>
};

Note that these are not at all requirements - these specifications, I believe, will serve as an example for how to set up configurations for various GraphQL app use cases. From the above format I've suggested all config properties to be optional except for schemaPath.

@wincent and @jimkyndemeyer made a great suggestion that we provide some helpful tools/guidelines related to the configuration details we're proposing. Some examples are described below:

  • How would one discover .graphqlrc file programmatically from the top-level/sub-directories?
  • How would one fetch/parse/build a GraphQL schema from the introspection endpoint specified in schema-path?
  • Given a .graphql file in a repository, how would one recognize which app config to use?
  • How would configured custom validation rules be used?
  • How could existing GraphQL configurations be migrated into using this proposed .graphqlrc approach?

Finally, we're planning to propose this concept as one of "Best Practices" in graphql.org once it matures.

Please feel free to add/let me know if I've missed anything from our conversation @schickling and @wincent! I'm looking forward to see how this shapes up.

Not updating from URL

I love this package. However, recently it stopped updating and I'm not sure what to do to get it going again.

Is there any command I can do to force a refresh or a file I can delete to clear its cache to make it pull again?

I'm using the package.json option:

"graphql": {
    "request": {
      "url": "http://localhost:4000/queries"
    }
  },

The GraphQL endpoint is a Rails server. It had been working, and when I do a deploy script it will run and that script builds with the correct schema, but not during the normal process of running the dev server. The result is that my browser app throws console errors because I'm referencing things that it doesn't know exist. I don't know if it was a combination of updating a package or node, or something else.

Ideas?

how to disable?

I'm trying to configure webpack to build a subrepository I have in my react/relay project. the subrepo doesn't require a graphql endpoint, so I'd like to disable graph-config when executing the subrepo's webpack configs.

however, when calling webpack from the project's root (with its own package.json), I'm still facing build errors:

ERROR in ./add/index.js
Module build failed: Error: Couldn't find a GraphQL config. Please refer to https://github.com/graphcool/graphql-config
    at parse (/home/bmp/storage/code/wayhome/web-app/node_modules/graphql-config-parser/src/index.js:41:11)
    at Object.<anonymous> (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-plugin-react-relay/lib/index.js:48:45)
    at Module._compile (module.js:573:32)
    at Object.Module._extensions..js (module.js:582:10)
    at Module.load (module.js:490:32)
    at tryModuleLoad (module.js:449:12)
    at Function.Module._load (module.js:441:3)
    at Module.require (module.js:500:17)
    at require (internal/module.js:20:19)
    at /home/bmp/storage/code/wayhome/web-app/node_modules/babel-core/lib/transformation/file/options/option-manager.js:178:20
    at Array.map (native)
    at Function.normalisePlugins (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
    at OptionManager.mergeOptions (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-core/lib/transformation/file/options/option-manager.js:233:36)
    at OptionManager.init (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-core/lib/transformation/file/options/option-manager.js:367:12)
    at File.initOptions (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-core/lib/transformation/file/index.js:216:65)
    at new File (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-core/lib/transformation/file/index.js:139:24)
    at Pipeline.transform (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-loader/index.js:38:20)
    at Object.module.exports (/home/bmp/storage/code/wayhome/web-app/node_modules/babel-loader/index.js:131:12)
 @ multi add

I tried setting an empty object to .graphqlrc or throwing in a fake endpoint, but no dice.

How is graphql-config even hooking onto this build command? I'm not using the same webpack.config.js or package.json/node_modules as the parent repo.

subrepo's stuff:

// webpack.config.js
var path = require("path")
var rootPath = './src/backend-functions'

module.exports = {
  entry: {
    add: [`./add/index.js`],
  },
  output: {
    //path: path.join(__dirname, "js"),
    filename: "bundle.js",
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel',
        babelrc: false,
        query: {
          presets: ['stage-0']
          //plugins: ['transform-flow-strip-types']
        }
      },
      {
        test: /\.json$/,
        loader: 'json'
      }
    ]
  }
}

//package.json
{
  "name": "web-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "start": "webpack"
  },
  "dependencies": {
    "webpack": "^1.14.0"
  }
}

Support GET in addition to POST

I was trying to use it with GraphQL Hub endpoint, but it just accepts GET, not POST, so I get this error: 'Cannot POST /playground'.

I see POST is hard coded here, so why not a config to change this?

Extend the extensions possibilities

Using different config extensions in the graphql-cli, I have noticed there is a gap between what the extensions can provide, and what custom behavior the cli needs. I think part of this needs to be solved in the cli, but the other part probably in graphql-config.

For example, retrieving an endpoint is part of the graphql-config extensions, and loading a schema is part of the core, and can't be influenced by extensions.

This is not a 'ready to be implemented' kind of issue, but food for thought...

How to set .graphqlrc programatically ?

Hi!
Really enjoy using your software so far! makes things way easier in the complicated graphql/relay world!

I got one question regarding programatically setting grapnel parameters.

The example of .graphqlrc shows how to set the Authorization header.

{
  "request": {
    "url": "https://example.com/graphql",
    "headers": {
      "Authorization": "xxxxx"
    }
  }
}

In my use case, the Auth header is set programatically (JWT token after login). So I'd need the .graphqlrc to be set programatically.

How can I achieve that?

GraphQL Configuration Protocol

GraphQL Configuration protocol

In a nutshell, the simplest format is:

export type GraphQLConfiguration = {
  schemaPath?: FilePath,  // may be .json or .graphql
  schemaUrl?: URL,
  schemaJS?: ModulePath | ModuleName,
  // If env is specified, use one of the app configs in here
  env?: GraphQLConfigurationEnvs

  // For multiple applications with overlapping files, bottom configuration options may be helpful
  includeDirs?: Array<DirPath>,
  excludeDirs?: Array<DirPath>,

  // If you have customized validation rules to run
  customValidationRules?: FilePath | Array<FilePath>,

  // If you'd like to specify any other configurations, we provide a reserved namespace for it
  extensions?: GraphQLConfigurationExtension
};

export type GraphQLConfigurationEnvs = {
  production: GraphQLConfiguration,
  development: GraphQLConfiguration,
  // but really just the below
  [envVarName: string]: GraphQLConfiguration
};

export type GraphQLConfigurationExtension = {
  [toolName: string]: any,
};

Note that I'd like to discourage the recursive pattern in using the EnvironmentalVariable - for example:

{
  "schemaPath": "...",
  "env": {
    "production": {
      "appProd": {
        // BEWARE OF THE BELOW PATTERN!
        "env": { ... }
      }
    }
  }
}

Now the reasoning for it: let's start with a most simple use case - one app/one schema.

Single-app/single-schema

Usually a single app requires a schema path/url and an env variable to facilitate the build and deployment:

export type GraphQLAppConfig = {
  schemaPath: FilePath,
  schemaUrl: URL,
  env: EnvironmentVariable
};

export type EnvironmentVariable = {
  [envVarName: string]: GraphQLAppConfig
};

Multiple-apps/isolated directories

For multiple apps with isolated directories, I like @wincent's idea about a common-default GraphQL configurations, but in spirit of keeping things simple at first, I'd like to propose an one-config-per-directory approach as our first draft. I think there's an edge case where we'd have multiple parent GraphQL configurations to consider:

./repo/.graphqlrc
./repo/appFamily/.graphqlrc
./repo/appFamily/app1/.graphqlrc

This can become a discussion of its own, which we can have separately ;)

Custom validation rules

You may want to run custom validation rules before building GraphQL apps/codegen/etc - customValidationRules is useful for that.

Reserved namespaces

@wincent made a suggestion to provide a way to include any other configurations if you desire. This namespace will contain an app/prod/organization/team-specific GraphQL configurations, and it will be treated as optional settings you'd like to use for your purpose.

{
  "schemaPath": "path/to/schema",
  "extensions": {
    "my-tool": {
      "here": "This is a tool-specific extension"
    }
  }
}

What is this repo, then?

I think this repo should serve two roles in a broader sense:

1. Maintain this protocol and become a town hall for discussions/improvements for this protocol.
2. Provide reference implementations of helper methods to lubricate adoption for this protocol.

An example of the reference implementation of the helper method: we mentioned a way to find this GraphQL configuration is to walk up a directory until it finds one. This basically can be implemented as such:

/**
 * (From `graphql-language-service` repo:
 * Finds a .graphqlrc configuration file, and returns null if not found.
 * If the file isn't present in the provided directory path, walk up the
 * directory tree until the file is found or it reaches the root directory.
 */
export function findGraphQLConfigDir(dirPath: string): ?string {
  let currentPath = path.resolve(dirPath);
  while (true) {
    const filePath = path.join(currentPath, '.graphqlrc');
    if (fs.existsSync(filePath)) {
      break;
    }
    if (isRootDir(currentPath)) {
      break;
    }
    currentPath = path.dirname(currentPath);
  }
  return !isRootDir(currentPath) ? currentPath : null;
}

function isRootDIr(path: string): boolean {
  return path.dirname(path) === path;
}

As there are several use cases, we can tackle each of them and present a way to use this configuration programmatically. I can begin by identifying/suggesting some of them below:

  • A generalized module bundler configurations, using GraphQL configurations
    • webpack, yeoman, babel, and etc...
  • How to include custom validation rules in your application
  • How to generate schema with provided schema path(s)
    • Sending introspection query to the endpoint
    • Parsing/building the schema using a local file path
    • Compiling GraphQLSchema object using schema definitions in .js
    • How to cache the schema
      • local files, indexedDB, and etc...

Action items

There are many things to do! But when we successfully deliver this, I believe we can get to the point where we have a shared GraphQL configuration that everyone agrees on, with commonly-used techniques and best practices to configure your GraphQL environment.

  • Write a draft for this protocol
  • Populate this repository with those helper methods
    • Discuss what the superset of those helper methods would be
    • Prioritize by the most impactful and common ones and implement them
    • Generalize existing implementations and move them here
  • Update other remaining documentations, including this repo's README
  • Suggest GraphQL configuration as a best-practice at graphql.org

Lastly, although we've begun this proposal and made a bunch of suggestions, I'd love to have a collaborative effort in pushing this forward. It'll be amazing to see us working together to improve and deliver this proposal to the GraphQL community.

Please post your thoughts/concerns/questions! Also if you'd like to be responsible for one of the actions items above, don't be hesitate to do so :D

"You have to specify endpoint name" error when more than one endpoint is defined

Running

graphql get-schema dev

with this config works:

{
  "schemaPath": "schema.graphql",
  "extensions": {
    "endpoints": {
      "dev": "http://localhost:3080/api/graphql"
    }
  }
}

but with this config (generated by graphql init):

{
  "schemaPath": "schema.graphql",
  "extensions": {
    "endpoints": {
      "dev": {
        "url": "http://localhost:3080/api/graphql"
      },
      "prod": {
        "url": "https://myserver.com/api/graphql"
      }
    }
  }
}

it just errors with

You have to specify endpoint name or define GRAPHQL_CONFIG_ENDPOINT_NAME enviroment variable

Environment specific configuration

I think it would be important to be able to specify a different GraphQL endpoint for development and production builds of an app. For example, for development you could have a GraphQL server running locally and make a production build that uses the schema from an external production server.

Out of current configuration methods, only the GRAPHQL_ENDPOINT environment variable supports this use case, but it doesn't allow specifying authentication credentials, so it's not ideal.

Throwing in some ideas so far:

  • It might be possible to add something like the env option of Babel, e.g.:

    {
      "request": {
        "url": "https://localhost:8080/graphql",
        "headers": {
          "Authorization": "xxxxx"
        }
      }
      "env": {
        "production": {
          "request": {
            "url": "https://api.example.com/graphql",
            "headers": {
              "Authorization": "xxxxx"
            }
          }
        }
      }
    }
    

    However, unlike Babel, graphql-config should probably not rely on NODE_ENV (it's used to just distinguish between non-optimized development and optimized production build of an app, not different environments like testing, staging, etc. Also graphql-config will be useful in more than just JS apps (e.g. native mobile apps) so NODE_ENV doesn't make sense there.) Therefore this approach would probably require a new environment variable like GRAPHQL_ENV. But this method of grouping config by environment is discouraged by some recommendations like the 12-Factor App. (Because doesn't scale well when you need more environments.)

    The approach that I personally use in my apps is to read each configuration value from a separate environment variable, so that they can be overridden for testing/staging/production environments as needed, but specify the development environment settings as defaults in the configuration file, so that the development environment can be started after checking out the project from git without any additional config.

  • @schickling suggested that we could include the environment in the graphqlrc filename, for example .graphql.dev.rc. I think this would be as good as the env option, but with the same drawbacks with the lack of granularity. These approaches also kind of promote storing production settings/secrets in your code repository.

I think an ideal configuration might be something like the current .graphqlrc / package.json approach, but with a way to override the settings (including authentication) through an environment variable. Any ideas how this could work?

Check for GRAPHQL_ENDPOINT first

I am curious to know if there is a specific reason for the order in which this plugin checks for the GraphQL URL. I ask because I am working on an integration with graphcool and Netlify but Netlify needs to use the GRAPHQL_ENDPOINT and it won't work if I have a local .graphqlrc/request URL.

Is it possible to check for the GRAPHQL_ENDPOINT first and then fallback to the checks for the package.json or the .graphqlrc

export function parse (path: string = process.cwd()): Config {
  try {
    const packageJson = require(`${path}/package.json`)
    if (packageJson.hasOwnProperty('graphql')) {
      return parseConfigJson(packageJson.graphql)
    }
  } catch (ex) {
    // do nothing here
  }

  try {
    const graphqlrc = JSON.parse(readFileSync(`${path}/.graphqlrc`, 'utf-8'))
    return parseConfigJson(graphqlrc)
  } catch (ex) {
    // do nothing here
  }

  if (process.env.hasOwnProperty('GRAPHQL_ENDPOINT')) {
    ...
  }

  throw new Error('Couldn\'t find a GraphQL config. Please refer to https://github.com/graphcool/graphql-config')
}

Would there be any limitation to doing this? My thought would be the GRAPHQL_ENDPOINT would take precedent over the .graphqlrc request URL.

export function parse (path: string = process.cwd()): Config {

  if (process.env.hasOwnProperty('GRAPHQL_ENDPOINT')) {
    ...
  }

  try {
   ...
  } catch (ex) {
    // do nothing here
  }

  try {
  ...
  } catch (ex) {
    // do nothing here
  }

  throw new Error('Couldn\'t find a GraphQL config. Please refer to https://github.com/graphcool/graphql-config')
}

Creating config programatically?

Is there assumption that config will be always written by people.
I'm looking to build vscode extensions and cli that will generate config automatically after detecting schema file to help kickstart project.

Is there way to define config apart from using bare yaml package

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.