我希望做的事情类似于graphql教程中的内容:https://graphql.org/learn/queries/#arguments
这是我的模式
type Query{
author(id:Int!):author
authors:[author]
books:[book]
book(id:Int!):book
}
type author{
id:Int!
name:String
surname: String
}
enum currency{
EUR
US
}
type book{
id:Int!
title:String!
authors:[author]
published:String
price(unit: currency = EUR):Float
}
schema{
query:Query
}
我想转换货币,但我不知道如何将函数与该返回类型连接,以返回转换后的值。
完整的server.js
const express=require('express');
const axios = require('axios');
const express_graphql = require('express-graphql');
var {buildSchema} = require('graphql');
var schema = buildSchema(`
type Query{
author(id:Int!):author
authors:[author]
books:[book]
book(id:Int!):book
}
type author{
id:Int!
name:String
surname: String
}
enum currency{
EUR
US
}
type book{
id:Int!
title:String!
authors:[author]
published:String
price(unit: currency = EUR):Float
}
schema{
query:Query
}
`)
var getAuthors = function(args){
return axios.get('http://localhost:1234/Authors').then(res => res.data);
}
var getAuthor = function(args){
return axios.get('http://localhost:1234/Authors/'+args.id).then(res => res.data);
}
var getBooks = function(args){
return axios.get('http://localhost:4321/Books').then(res => res.data);
}
var getBook = function(args) {
return axios.get('http://localhost:4321/Books/'+args.id).then(res => res.data);
}
var root = {
author:getAuthor,
authors:getAuthors,
books:getBooks,
book:getBook
}
const app=express();
app.use('/graphql', express_graphql({
schema,
rootValue: root,
graphiql: true
}));
function convertCurrency(Eur, unit){
if(unit==="EUR"){
return Eur;
}
if(Unit === "US"){
return Eur * 1.11;
}
}
app.listen(8080, ()=>{
console.log('server is running on port 8080..')
})
答案 0 :(得分:0)
您需要为price
字段提供一个解析器,看起来像这样:
(parent, args) => convertCurrency(parent.price, args.unit)
很遗憾,buildSchema
不允许您创建功能齐全的架构。通常,您将为要为其提供解析逻辑的任何字段定义一个resolve
函数(或解析器),但是buildSchema
创建一个没有任何解析器的架构。试图通过根值传递伪解析器的是a bit of hackery,它试图解决此问题,但是它有其局限性。
您有两个选择:
makeExecutableSchema