From 5c63faaab8512849f146628ebb02e4bc946537f5 Mon Sep 17 00:00:00 2001 From: Martin Sosic Date: Wed, 25 Nov 2020 22:33:48 +0100 Subject: [PATCH] Tags can now be deleted. --- examples/realworld/README.md | 3 --- examples/realworld/ext/actions.js | 18 ++++++++++++++---- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/examples/realworld/README.md b/examples/realworld/README.md index fa1ff9833..d17fd7a49 100644 --- a/examples/realworld/README.md +++ b/examples/realworld/README.md @@ -17,9 +17,6 @@ Todo: - [x] For Article, use special id which contains title in the name, and display it in url? - [x] CR*D Comments on articles. - [x] Add tags to articles. -- [ ] Make article tags deleteable. Right now I have something but it does not delete them from the database! - I think I am using Prisma wrong here, the problem is probably in connectOrCreate when updating, - it does not seem to delete the ones that are missing now. - [ ] Show Popular Tags on home page. - [ ] Favorite articles. - [ ] Following other users. diff --git a/examples/realworld/ext/actions.js b/examples/realworld/ext/actions.js index dc35911a7..4e04f3a5c 100644 --- a/examples/realworld/ext/actions.js +++ b/examples/realworld/ext/actions.js @@ -61,19 +61,29 @@ export const updateArticle = async ({ id, title, description, markdownContent, t // TODO: Nicer error handling! Right now everything is returned as 500 while it could be instead // useful error message about username being taken / not unique, and other validation errors. - if (!await context.entities.Article.findFirst({ - where: { id, user: { id: context.user.id }} // TODO: This line is not fun to write. - })) { + + const article = await context.entities.Article.findFirst({ + where: { id, user: { id: context.user.id }}, // TODO: This line is not fun to write. + include: { tags: true } + }) + if (!article) { throw new HttpError(404) } + const subtractTags = (tags1, tags2) => tags1.filter(t1 => !tags2.find(t2 => t2.name === t1.name)) + const tagsToAdd = tags ? subtractTags(tags, article.tags) : [] + const tagsToRemove = tags ? subtractTags(article.tags, tags) : [] + await context.entities.Article.update({ where: { id }, data: { title, description, markdownContent, - tags: { connectOrCreate: tags.map(tag => ({ where: tag, create: tag })) } + tags: { + connectOrCreate: tagsToAdd.map(tag => ({ where: tag, create: tag })), + disconnect: tagsToRemove + } } }) }