首页 文章

没有`graphql-tools`的GraphQL自定义标量定义

提问于
浏览
3

阅读官方文档中的演练后:

http://graphql.org/graphql-js/object-types/

我对如何制作没有第三方库的自定义标量类型解析器感到很困惑 . 以下是文档中的示例代码:

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type RandomDie {
    numSides: Int!
    rollOnce: Int!
    roll(numRolls: Int!): [Int]
  }

  type Query {
    getDie(numSides: Int): RandomDie
  }
`);

// This class implements the RandomDie GraphQL type
class RandomDie {
  constructor(numSides) {
    this.numSides = numSides;
  }

  rollOnce() {
    return 1 + Math.floor(Math.random() * this.numSides);
  }

  roll({numRolls}) {
    var output = [];
    for (var i = 0; i < numRolls; i++) {
      output.push(this.rollOnce());
    }
    return output;
  }
}

// The root provides the top-level API endpoints
var root = {
  getDie: function ({numSides}) {
    return new RandomDie(numSides || 6);
  }
}

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

我知道我可以使用 graphql-tools 从基于字符串的类型定义和解析器对象生成"executable schema" . 我想知道为什么没有更低级别/命令式 graphql-js API我可以用来定义和解析自定义标量类型?换句话说, graphql-tools 如何工作?

提前致谢!


编辑:

这是一些概述问题的示例代码 . 在第4行,您可以看到我正在导入GraphQLJSON但它从未使用过 . 我知道如何使用 graphql-tools 来完成这项工作,但我想了解它是如何工作的 . 换句话说,如果 graphql-tools 不存在,在使用 graphql 语法编写我的模式时,如何注入自定义标量类型?据我所知,只有 graphql-js 解决方案是使用非声明性方法来创作模式(下面的第二个例子)

import express from 'express';
import graphqlHTTP from 'express-graphql';
import { buildSchema } from 'graphql';
import GraphQLJSON from 'graphql-type-json'; // where should I inject this?

const schema = buildSchema(`
  type Image {
    id: ID!
    width: Int!
    height: Int!
    metadata: JSON!
  }

  type Query {
    getImage(id: ID!): Image!
  }

  scalar JSON
`);

class Image {
  constructor(id) {
    this.id = id;
    this.width = 640;
    this.height = 480;
  }
  metadata() {
    // what do I need to do in order to have this return value parsed by GraphQLJSON
    return { foo: 'bar' };
  }
}

const rootValue = {
  getImage: function({ id }) {
    return new Image(id);
  },
};

const app = express();
app.use(
  '/graphql',
  graphqlHTTP({
    schema: schema,
    rootValue: rootValue,
    graphiql: true,
  })
);
app.listen(4000);

运行此查询:

{
    getImage(id: "foo") {
    id
    width
    height
    metadata
  }
}

结果出现此错误:

Expected a value of type \"JSON\" but received: [object Object]

我正在寻找的答案将帮助我在不使用 graphql-tools 的情况下返回JSON类型 . 我没有反对这个库,但对于我来说,我必须使用第三方库来获得 graphql-js 中类型解析系统的基本功能 . 我想更多地了解为什么在采用它之前需要这种依赖 .

这是另一种使这项工作的方法:

import { GraphQLObjectType, GraphQLInt, GraphQLID } from 'graphql/type';

const foo = new GraphQLObjectType({
  name: 'Image',
  fields: {
    id: { type: GraphQLID },
    metadata: { type: GraphQLJSON },
    width: { type: GraphQLInt },
    height: { type: GraphQLInt },
  },
});

但是,这不允许我使用 graphql 语法创建我的架构,这是我的目标 .

1 回答

  • 6

    UPDATE

    经过一些澄清之后,看起来您正在尝试将自定义标量添加到使用模式语言创建的模式中 . 由于构建的架构 buildSchema (或其他客户端工具)没有 serializeparseValueparseLiteral 绑定的处理函数,因此您需要修改构建的架构以包含这些函数 . 你可以做点什么

    import { buildSchema } from 'graphql'
    import GraphQLJSON from 'graphql-type-json'
    
    const definition = `
    type Foo {
      config: JSON
    }
    
    scalar JSON
    
    Query {
      readFoo: Foo
    }
    
    schema {
      query: Query
    }`
    
    const schema = buildSchema(definition)
    Object.assign(schema._typeMap.JSON, GraphQLJSON)
    

    或者,您也可以执行以下操作,这可能有助于将标量重命名为其他内容

    Object.assign(schema._typeMap.JSON, {
      name: 'JSON',
      serialize: GraphQLJSON.serialize,
      parseValue: GraphQLJSON.parseValue,
      parseLiteral: GraphQLJSON.parseLiteral
    })
    

    Original Answer

    buildSchema 确实创建了一个模式,但该模式没有与之关联的resolve,serialize,parseLiteral等函数 . 我相信graphql-tools只允许您将解析器函数映射到在您尝试创建自定义标量时无法帮助您的字段 .

    graphql-jsGraphQLScalarType ,您可以使用它来构建自定义标量 . 请参阅http://graphql.org/graphql-js/type/#graphqlscalartype的官方文档和示例

    npm中还有几个包可以作为示例使用

    一个我发现非常有用的是https://github.com/taion/graphql-type-json/blob/master/src/index.js

    例如,如果要创建一个base64类型,将字符串存储为base64并在响应中返回它们之前解码base64字符串,则可以创建这样的自定义base64标量

    import { GraphQLScalarType, GraphQLError, Kind } from 'graphql'
    
    const Base64Type = new GraphQLScalarType({
      name: 'Base64',
      description: 'Serializes and Deserializes Base64 strings',
      serialize (value) {
        return (new Buffer(value, 'base64')).toString()
      },
      parseValue (value) {
        return (new Buffer(value)).toString('base64')
      },
      parseLiteral (ast) {
        if (ast.kind !== Kind.STRING) {
          throw new GraphQLError('Expected Base64 to be a string but got: ' + ast.kind, [ast])
        }
        return (new Buffer(ast.value)).toString('base64')
      }
    })
    

相关问题