只需使用node和c#来学习GraphQL。我正在尝试将C#示例移植到节点,因为这将是一个很好的学习练习(因为我不太了解node或graphql)
我有2种类型。帐户和所有者(即帐户所有者)
在以下情况(即拥有帐户的字段(列表)和第一帐户的字段(单个对象))下,一切都可以正常工作
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
}
答案 0 :(得分:2)
Node.js允许循环依赖。并非所有模块系统都允许这样做,但是它可以在Node中工作。问题是,无论首先解析哪个模块,都需要取消定义其中一个模块。在这种情况下,Node.js分配一个空对象作为此模块的导出。
因此,基本上,您有时会为一个空对象分配一个类型-从而抱怨该类型缺少name属性。好处是,如果您为其分配属性,对该对象的引用将不会更改。我已经here和here回答了您要做的事情。
答案 1 :(得分:1)
为什么会发生此错误?因为您提供的是编译时未定义的类型。因此,当编译器尝试编译文件时,它将搜索您在此处指定的类型AccountType
。尚未编译。这就是OwnerType
未获得AccountType
且您收到错误的原因。
简单解决方案:
您需要将AccountType
导入OwnerType
文件中。
const AccountType = require('./AccountType.js');
在OwenerType
代码之前。这可能会有所帮助。