From 32411b76ef0752ebbd1480526cd05774d012b06c Mon Sep 17 00:00:00 2001 From: Daniel Nitsikopoulos Date: Fri, 1 Mar 2024 20:52:30 +1100 Subject: [PATCH] Validate bookmark URL uniqueness --- slices/micropub/repos/post_repo.rb | 6 ++++++ .../validation/posts/bookmark_contract.rb | 7 +++++++ spec/requests/create_post_spec.rb | 20 +++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/slices/micropub/repos/post_repo.rb b/slices/micropub/repos/post_repo.rb index 6212667..7296541 100644 --- a/slices/micropub/repos/post_repo.rb +++ b/slices/micropub/repos/post_repo.rb @@ -53,6 +53,12 @@ module Micropub .one end + def url_exists?(url) + !!posts + .where(url: url) + .one + end + def find!(id) posts .by_pk(id) diff --git a/slices/micropub/validation/posts/bookmark_contract.rb b/slices/micropub/validation/posts/bookmark_contract.rb index 0b1eb57..c8afe4d 100644 --- a/slices/micropub/validation/posts/bookmark_contract.rb +++ b/slices/micropub/validation/posts/bookmark_contract.rb @@ -2,6 +2,9 @@ module Micropub module Validation module Posts class BookmarkContract < Dry::Validation::Contract + + include Deps["repos.post_repo"] + params do required(:name).filled(:string) required(:content).maybe(:string) @@ -14,6 +17,10 @@ module Micropub required(:photos).array(:hash) required(:cache).filled(:bool) end + + rule(:url) do + key.failure("URL already bookmarked") if post_repo.url_exists?(values[:url]) + end end end end diff --git a/spec/requests/create_post_spec.rb b/spec/requests/create_post_spec.rb index 34c40d9..9a66952 100644 --- a/spec/requests/create_post_spec.rb +++ b/spec/requests/create_post_spec.rb @@ -176,6 +176,26 @@ RSpec.describe "Post creation", :db, :requests do expect(post_repo.bookmark_listing.count).to eq 1 expect(post_repo.bookmark_listing.last.cached_content).to_not eq nil end + + it "validates an already bookmarked URL" do + params = { + h: "entry", + "bookmark-of": "http://example.com", + name: "Name", + content: "Content of the post", + cache: "true" + } + + post "/micropub", params + + expect(last_response).to be_successful + expect(post_repo.bookmark_listing.count).to eq 1 + expect(post_repo.bookmark_listing.last.cached_content).to_not eq nil + + post "/micropub", params + expect(last_response).to_not be_successful + expect(post_repo.bookmark_listing.count).to eq 1 + end end context "checkins" do