刚刚使用 Node 和 C# 学习 GraphQL。我正在尝试将 C# 示例移植到 Node,因为这将是一个很好的学习练习(因为我不太了解 Node 或 graphql)
我有两种类型。帐户和所有者(即帐户所有者)
以下内容一切正常(即拥有帐户的字段(列表)和第一个帐户(单个对象))
module.exports = new GraphQLObjectType({
name: 'OwnerType',
fields: {
Id: { type: GraphQLID},
Name: {type: GraphQLString},
Address: {type: GraphQLString},
OwnedAccounts: {
type: new GraphQLList(AccountType),
name: "OwnedAccounts",
resolve(obj, args, { mssqlConfig }){
return mssql_account(mssqlConfig).getByOwnerId(obj.Id);
}
},
FirstAccount: {
type: AccountType,
name: "FirstAccount",
resolve(obj, args, {mssqlConfig}){
return mssql_account(mssqlConfig).getFirstByOwnerId(obj.Id);
}
}
}
});
当我尝试将 AccountOwner 字段添加到 AccountType 时,就会出现问题。我收到错误“为构建架构提供的类型之一缺少名称。”
我曾尝试为我能看到的所有东西都命名,但这根本没有帮助。
有问题的 AccountType 定义是:
module.exports = new GraphQLObjectType({
name: 'AccountType',
fields: {
Id: { type: GraphQLID },
Description: { type: GraphQLString },
OwnerId: { type: GraphQLID },
Type: { type: AccountTypeEnum },
AccountOwner: {
type: OwnerType,
resolve(obj, args, { mssqlConfig }){
return mssql_owner(mssqlConfig).get(obj.OwnerId);
}
}
}
});
如果您需要更多信息或任何其他代码,请告诉我。
编辑:如果我更改两种类型(帐户和所有者)的声明并将它们放在同一个 .js 文件中,那么它就可以工作(见下文)。我还更改了字段以返回箭头函数,我相信这会延迟某种绑定,直到所有内容加载完毕。
所以现在我的问题是我应该如何将类型分成不同的文件。 (JS不是我的强项)
编辑...改变类型...
const {
GraphQLObjectType,
GraphQLID,
GraphQLString,
GraphQLList
} = require('graphql');
const AccountTypeEnum = require('./accountTypeEnum');
const mssql_owner = require('../../database/mssql/owner');
const mssql_account = require('../../database/mssql/account');
const ownerType = new GraphQLObjectType({
name: 'OwnerType',
fields: () => ({
Id: { type: GraphQLID, name: "Id"},
Name: {type: GraphQLString, Name: "Name"},
Address: {type: GraphQLString},
OwnedAccounts: {
type: new GraphQLList(accountType),
name: "OwnedAccounts",
resolve(obj, args, { mssqlConfig }){
return mssql_account(mssqlConfig).getByOwnerId(obj.Id);
}
},
FirstAccount: {
type: accountType,
name: "FirstAccount",
resolve(obj, args, {mssqlConfig}){
return mssql_account(mssqlConfig).getFirstByOwnerId(obj.Id);
}
}
})
});
const accountType = new GraphQLObjectType({
name: 'AccountType',
fields: () => ({
Id: { type: GraphQLID, name: "Id" },
Description: { type: GraphQLString, name: "Description" },
OwnerId: { type: GraphQLID, name: "OwnerId" },
Type: { type: AccountTypeEnum, name: "Type" },
AccountOwnerFoo: {
name: "Wombat",
type: ownerType,
resolve(parent, args, {mssqlConfig}){
return mssql_owner(mssqlConfig).get(parent.OwnerId);
}
}
})
});
module.exports = {
ownerType,
accountType
}