我在 Node js 中为我的 Oracle 数据库使用 graphql,其中我连接到远程数据库并获取一些详细信息。我对这些技术相当陌生,所以请原谅我。我有一个 customer
表,其架构如下:
const Customer = new GraphQLObjectType({
description: 'Customer data schema',
name: 'Customer',
fields: () => ({
name: {
type: GraphQLString,
sqlColumn: 'NAME',
},
city: {
type: GraphQLString,
sqlColumn: 'CITY'
},
country: {
type: GraphQLString,
sqlColumn: 'COUNTRY'
},
gender: {
type: GraphQLString,
sqlColumn: 'GENDER'
},
emp_id: {
type: GraphQLString,
sqlColumn: 'EMP_ID'
}
})
});
Customer._typeConfig = {
sqlTable: 'CUSTOMER',
uniqueKey: ['NAME','EMP_ID']
}
使用 join monster 我创建查询根为:
const QueryRoot = new GraphQLObjectType({
description: 'global query object',
name: 'RootQuery',
fields: () => ({
customer: {
type: new GraphQLList(Customer),
args: {
emp_id: {
description: 'Emp Id',
type: GraphQLString
},
name: {
description: 'Customer Name',
type: GraphQLString
}
},
where: (customer, args, context) => {
return `${customer}."EMP_ID" = :emp_id AND ${customer}."NAME" = :name`;
},
resolve: (parent, args, context, resolveInfo) => {
return joinMonster(resolveInfo, context, sql => {
console.log('joinMaster', sql);
return database.simpleExecute(sql, args,{
outFormat: database.OBJECT
});
});
}
}
})
})
当我使用 emp_id 和 name 参数在浏览器中的 graphql 中传递查询时,我会获取数据。但在某些情况下,我无法传递任何参数,并且希望获取所有行。
当我不发送参数时,出现错误:
ORA-01008:并非所有变量都绑定(bind)
我希望参数是可选的,如果我不发送它们,那么它应该返回所有行。
谢谢。
最佳答案
where
和 resolver
函数都传递一个 args
参数。这将包含参数名称和值(如果有)。您可以使用该参数构建动态 where 子句。这是一个未经测试的示例:
const QueryRoot = new GraphQLObjectType({
description: 'global query object',
name: 'RootQuery',
fields: () => ({
customer: {
type: new GraphQLList(Customer),
args: {
emp_id: {
description: 'Emp Id',
type: GraphQLString
},
name: {
description: 'Customer Name',
type: GraphQLString
}
},
where: (customer, args, context) => {
if (Object.keys(args).length === 0) {
return false;
}
let whereClause = '1 = 1';
if (args.emp_id != undefined) {
whereClause += `\n AND ${customer}."EMP_ID" = :emp_id`;
}
if (args.name != undefined) {
whereClause += `\n AND ${customer}."NAME" = :name`;
}
return whereClause;
},
resolve: (parent, args, context, resolveInfo) => {
return joinMonster(resolveInfo, context, sql => {
console.log('joinMaster', sql);
return database.simpleExecute(sql, args,{
outFormat: database.OBJECT
});
});
}
}
})
})
由于 where 子句将匹配参数的数量,因此您不应收到 ORA-01008 错误。
关于node.js - Graphql 仅在传递参数时执行 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57164165/