S R*_*sam 9 javascript node.js graphql
刚刚使用 node 和 c# 学习 GraphQL。我正在尝试将 C# 示例移植到 node 上,因为这将是一个很好的学习练习(因为我不太了解 node 或 graphql)
我有 2 种类型。Account and Owner(即帐户所有者)
一切正常(即拥有帐户(列表)和第一个帐户(单个对象)的字段)
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);
}
}
}
}); Run Code Online (Sandbox Code Playgroud)
当我尝试将 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);
}
}
}
});Run Code Online (Sandbox Code Playgroud)
如果您需要更多信息或任何其他代码,请告诉我。
编辑:如果我更改两种类型(帐户和所有者)的声明并将它们放在同一个 .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
}
Run Code Online (Sandbox Code Playgroud)