【发布时间】:2018-05-29 04:58:03
【问题描述】:
阅读官方文档中的这个演练后:
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 从基于字符串的类型定义和解析器对象中创建“可执行模式”。我想知道为什么没有较低级别/命令式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 语法创作我的架构,这是我的目标。
【问题讨论】:
标签: javascript graphql graphql-js