用 JavaScript 定义 GraphQL Query/Mutation 的聪明方法

Clever way to define a GraphQL Query/Mutation with JavaScript

也许这只是我,但我对用反引号定义我的 GraphQL Queries/Mutations 感到非常恼火。这里的问题是,如果我必须对查询字符串应用一些更改,重新格式化反引号内的字符串会很烦人。

有没有一种聪明的方法可以用 JavaScript 定义更具可读性和可维护性的 GraphQL Query/Mutation?当查询字符串混乱时,也很难找到丢失的括号。

我现在就是这样做的:

import gql from 'graphql-tag';

export const fancyMutation = gql`
mutation($id: ID!)
{
  delete_something(id:$id) {
    id
    foo
    bar
  }
}
`;

JS GraphQL WebStorm 插件从 1.4.1 版本开始支持嵌入的 GraphQL 字符串。

从 WebStorm 菜单 select File -> Settings -> Plugins -> Browse repositories 找到 JS GraphQL 插件。检查您是否至少安装了此插件的 1.4.1 版本。

安装后,它应该突出显示大括号,并允许您通过 selecting 代码块并从 IDE 菜单中选择 Code -> Reformat code 来重新格式化字符串中的 GraphQL。

此插件项目页面位于此处:

https://github.com/jimkyndemeyer/js-graphql-intellij-plugin

您也可以将查询放入自己的文件中,例如使用 .graphql.gql 文件扩展名,以及 use the graphql-tag/loader 从您需要的文件加载查询。

在其自己的文件中给出此查询:

query CurrentUserForLayout {
  currentUser {
    login
    avatar_url
  }
}

使用 webpack 你需要以下配置:

module: {
  rules: [
    {
      test: /\.(graphql|gql)$/,
      exclude: /node_modules/,
      loader: 'graphql-tag/loader',
    },
  ],
},

然后你可以这样加载它:

import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import currentUserQuery from './currentUser.graphql';

class Profile extends Component { ... }
Profile.propTypes = { ... };

export default graphql(currentUserQuery)(Profile)

更新:

您也可以在一个文件中包含多个查询:

query MyQuery1 {
  ...
}

query MyQuery2 {
  ...
}

然后您可以像这样加载它们:

import { MyQuery1, MyQuery2 } from 'query.gql'

除此之外,我不知道还有其他内联定义查询的选项。反引号不是特定于 graphql 的。它只是使用 es6 template tags 就像样式组件确实定义了内联 css。您唯一的选择是获得一个可以识别 graphql 查询以提供编辑帮助和代码突出显示的 IDE。 IntelliJ 编辑器(IDEA、WebStorm、PyCharm)有一个插件,就像@Victor Vlasenko 指出的那样。