在编写用于处理graphql过滤器的解析器功能时,我需要建议。过滤器支持eq,ne,contains和not like运算符。
import { gql } from 'apollo-server-express';
export default gql`
extend type Query {
authGroups(filter: AuthGroupFilterInput): AuthGroupConnection!
}
type AuthGroup implements Node {
id: ID!
name: String
}
input AuthGroupFilterInput {
name: StringFilterInput
}
type AuthGroupConnection {
edges: [AuthGroup!]!
pageInfo: PageInfo
}
input StringFilterInput {
lt: String,
gt: String,
eq: String,
ne: String,
contains: String,
like: String,
notLike: String,
}
`;
Query {
authGroups(filter: {
name: {
like: '%AD'
}
}
)
{
edges {
id
name
}
}
}
authGroups: async (parent, args, { models }) => {
const filter = args.filter;
const filters = filter
? {
where: filter,
}
: {};
const authGroups = await models.authGroup.findAll({
...filters
// where : {
// name: {
// [Sequelize.Op.like] : 'AD%'
// }
// }
});
}
如何用[Sequelize.Op.operator]替换过滤器中的运算符?我尝试在config.json中使用operatorAliases,但没有任何效果。非常感谢您的帮助。
答案 0 :(得分:1)
您可以仅使用括号符号来访问Op
上的正确属性。像这样:
function transformFilter (filter) {
for (const fieldName in filter) {
const condition = filter[fieldName]
filter[fieldName] = {}
for (const operatorName in condition) {
filter[fieldName][Op[operatorName]] = condition[operatorName]
}
}
}
即使这样“嵌套”,括号符号也可以使用。
答案 1 :(得分:1)
我通过在Sequelize构造函数中传递了OperatorAliases解决了这个问题。
ADO enumerator
在连接时顺序使用此别名。
import Sequelize from 'sequelize';
const operatorsAliases = {
eq: Op.eq,
ne: Op.ne,
gte: Op.gte,
gt: Op.gt,
lte: Op.lte,
lt: Op.lt,
......
}
它应该直接在您的解析器中运行,而无需任何额外的努力。
const dbService = {
connect: (host, database) => {
const sequelize = new Sequelize(
database,
user,
pwd, {
host: host,
dialect: 'yourDialect',
dialectOptions: {
domain: domain,
encrypt: true
},
operatorsAliases: operatorsAliases,
pool: {
max: 100,
min: 10,
idle: 200
}
}
);
sequelize
.authenticate()
.then(() => {
console.log(database, 'Connection has been established successfully.');
})
.catch((err) => {
console.error(err, `Unable to connect to the database.`);
});
return sequelize;
}
};
const yourDBRef = dbService.connect(hostName, dbName);