Cas*_*sey 5 javascript graphql graphql-js
阅读官方文档中的演练后:
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');
Run Code Online (Sandbox Code Playgroud)
我知道我可以用来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);
Run Code Online (Sandbox Code Playgroud)
运行此查询:
{
getImage(id: "foo") {
id
width
height
metadata
}
}
Run Code Online (Sandbox Code Playgroud)
结果出现此错误:
Expected a value of type \"JSON\" but received: [object Object]
我正在寻找的答案将帮助我在不使用的情况下返回JSON类型graphql-tools.我对这个库没有任何反对意见,但对我而言,我必须使用第三方库来获得类型解析系统的基本功能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 },
},
});
Run Code Online (Sandbox Code Playgroud)
但是这不允许我使用graphql语法编写我的模式,这是我的目标.
vbr*_*den 10
UPDATE
经过一些澄清之后,看起来您正在尝试将自定义标量添加到使用模式语言创建的模式中.由于构建的模式buildSchema(或其他客户端工具)没有for serialize,bound parseValue和parseLiteralbound的处理函数,因此您需要修改构建的模式以包含这些函数.你可以做点什么
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)
Run Code Online (Sandbox Code Playgroud)
或者,您也可以执行以下操作,这可能有助于将标量重命名为其他内容
Object.assign(schema._typeMap.JSON, {
name: 'JSON',
serialize: GraphQLJSON.serialize,
parseValue: GraphQLJSON.parseValue,
parseLiteral: GraphQLJSON.parseLiteral
})
Run Code Online (Sandbox Code Playgroud)
原始答案
buildSchema确实创建了一个模式,但该模式将没有与之关联的resolve,serialize,parseLiteral等函数.我相信graphql-tools只允许您将解析器函数映射到在您尝试创建自定义标量时无法帮助您的字段.
graphql-js有一个GraphQLScalarType你可以用来构建自定义标量.请参阅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')
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2174 次 |
| 最近记录: |