我使用阿波罗服务器2.0作为rest上的graphql聚合层(不同的微服务)。
我希望直接从微服务的api响应中生成graphql模式,而不是手工编写它们,这很容易出错。
如果我的api响应是
const restApiResponse = {
"id": 512,
"personName": "Caribbean T20 2016",
"personShortName": "caribbean-t20 2016",
"startDate": "2016-06-29T19:30:00.000Z",
"endDate": "2016-08-08T18:29:59.000Z",
"status": 0,
};
然后,我想根据提供的typeName (例如Person
)生成下面的模式-
type Person {
id: Float
personName: String
personShortName: String
startDate: String
endDate: String
status: Float
}
发布于 2018-11-21 21:15:28
最后,经过大量的搜索和查找,我为自己写了一个脚本-
这有一些小的问题,例如int被解析为浮点数,但这很好,因为如果需要的话,我可以用int替换它们。
const { composeWithJson } = require('graphql-compose-json');
const { GQC } = require('graphql-compose');
const { printSchema } = require('graphql'); // CommonJS
const restApiResponse = {
"id": 399,
"templateId": 115,
"amount": 100000,
"amountINR": 100000,
"amountUSD": 0,
"currencyCode": "INR",
"createdAt": "2018-06-07T00:08:28.000Z",
"createdBy": 36,
};
const GqlType = composeWithJson('Template', restApiResponse);
const PersonGraphQLType = GqlType.getType();
GqlType.addResolver({
name: 'findById',
type: GqlType,
args: {
id: 'Int!',
},
resolve: rp => {
},
});
GQC.rootQuery().addFields({
person: GqlType.getResolver('findById'),
});
const schema = GQC.buildSchema();
console.log(printSchema(schema));
,它生成类似于-的输出
type Template {
id: Float
templateId: Float
amount: Float
amountINR: Float
amountUSD: Float
currencyCode: String
createdAt: String
createdBy: Float
}
发布于 2018-11-19 10:30:46
这并不能真正回答你的问题,但我建议你不要这样做。GraphQL将自己定义为“毫无歉意的客户驱动”,这意味着您定义的每个查询都应该明确地定义为客户特别想要的内容。如果您只有平面数据,则不需要GraphQL,REST就足够了。如果不这样做,则需要按照客户端所需的方式精心制作和具体嵌套数据,并对您的UI有意义。有很多工具可以使这更容易,但我建议不要你要求什么。
https://stackoverflow.com/questions/53352739
复制