gpt4 book ai didi

graphql - 如何使用 GraphQL 突变在解析器中添加递归逻辑?

转载 作者:行者123 更新时间:2023-12-03 22:32:54 25 4
gpt4 key购买 nike

是否可以使用 GraphQL 突变在解析器中添加逻辑?
如果用户不提供,我正在尝试创建一个四位数的字符串作为帖子的别名。然后,我想检查一下数据库,看看这个四位数的字符串是否存在。如果字符串存在,我想递归地创建另一个四位字符串。
目前,我正在探索为解析器中的突变添加逻辑,但我不确定这是否可行。我将这些文件用于我的基金会:graphql.org sequelize.org
这是我当前的代码块:
工作于 2020 年 12 月 4 日

const MakeSlug = require("./services/MakeSlug");

const resolvers = {
Query: {
async allLinks(root, args, { models }) {
return models.Link.findAll();
},
async link(root, { id }, { models }) {
return models.Link.findByPk(id);
}
},
Mutation: {
async createLink(root, { slug, description, link }, { models }) {
if (slug !== undefined) {
const foundSlug = await models.Link.findOne({
where: { slug: slug }
});
if (foundSlug === undefined) {
return await models.Link.create({
slug,
description,
link,
shortLink: `https://shink.com/${slug}`
});
} else {
throw new Error(slug + " exists. Try a new short description.");
}
}

if (slug === undefined) {
const MAX_ATTEMPTS = 10;
let attempts = 0;
while (attempts < MAX_ATTEMPTS) {
attempts++;
let madeSlug = MakeSlug(4);
const foundSlug = await models.Link.findOne({
where: { slug: madeSlug }
});
if (foundSlug !== undefined) {
return await models.Link.create({
slug: madeSlug,
description,
link,
shortLink: `https://shink.com/${madeSlug}`
});
}
}
throw new Error("Unable to generate unique alias.");
}
}
}
};

module.exports = resolvers;

这是我完整的 codebase .
谢谢!

最佳答案

一个while循环解决了这个挑战。谢谢 xadm .

const MakeSlug = require("./services/MakeSlug");

const resolvers = {
Query: {
async allLinks(root, args, { models }) {
return models.Link.findAll();
},
async link(root, { id }, { models }) {
return models.Link.findByPk(id);
}
},
Mutation: {
async createLink(root, { slug, description, link }, { models }) {
if (slug !== undefined) {
const foundSlug = await models.Link.findOne({
where: { slug: slug }
});
if (foundSlug === undefined) {
return await models.Link.create({
slug,
description,
link,
shortLink: `https://shink.com/${slug}`
});
} else {
throw new Error(slug + " exists. Try a new short description.");
}
}

if (slug === undefined) {
const MAX_ATTEMPTS = 10;
let attempts = 0;
while (attempts < MAX_ATTEMPTS) {
attempts++;
let madeSlug = MakeSlug(4);
const foundSlug = await models.Link.findOne({
where: { slug: madeSlug }
});
if (foundSlug !== undefined) {
return await models.Link.create({
slug: madeSlug,
description,
link,
shortLink: `https://shink.com/${madeSlug}`
});
}
}
throw new Error("Unable to generate unique alias.");
}
}
}
};

module.exports = resolvers;

关于graphql - 如何使用 GraphQL 突变在解析器中添加递归逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65132891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com