Line data Source code
1 4 : (ns matchscore.domain.resource.command
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [matchscore.domain.resource.entity :as entity]
6 : [matchscore.domain.resource.repository.postgres :as resource-postgres-repo]
7 : [matchscore.utils.errors :as utils.errors]
8 : [matchscore.utils.nanoid :as nanoid]
9 : [matchscore.utils.uuid :as uuid-utils]))
10 :
11 :
12 4 : (defn- make-resource-or-fail
13 : "Builds a Resource entity, mapping validation/creation failures onto the
14 : Either rail instead of letting them throw."
15 : [resource-data]
16 1 : (try
17 5 : (either/right (entity/make-resource resource-data))
18 : (catch clojure.lang.ExceptionInfo e
19 0 : (either/left
20 0 : (utils.errors/build-error
21 : :check
22 0 : {:code :error.resource/invalid
23 0 : :message (.getMessage e)
24 0 : :humanized-errors (:humanized-errors (ex-data e))
25 0 : :context {:uuid (:uuid resource-data)}})))))
26 :
27 :
28 4 : (defn create-resource!
29 : "Creates a new club resource. Returns Either<Error, Resource>."
30 : [{:keys [repos]} resource-data]
31 4 : (let [repo (:resource-postgres-repo repos)
32 15 : resource-data (cond-> resource-data
33 8 : (not (:uuid resource-data)) (assoc :uuid
34 2 : (uuid-utils/generate-uuid7-str))
35 10 : (not (:public-id resource-data)) (assoc :public-id (nanoid/generate))
36 9 : (nil? (:is-active resource-data)) (assoc :is-active true)
37 8 : (nil? (:attributes resource-data)) (assoc :attributes {}))]
38 10 : (c/mlet [resource (make-resource-or-fail resource-data)]
39 4 : (resource-postgres-repo/save! repo resource))))
40 :
41 :
42 4 : (defn update-resource!
43 : "Updates an existing club resource. Returns Either<Error, {:code :success.resource/ok|:no-changes :data Resource}>."
44 : [{:keys [repos]} resource-data]
45 4 : (let [repo (:resource-postgres-repo repos)
46 6 : existing (resource-postgres-repo/find-by-id repo (:uuid resource-data))]
47 4 : (if-not existing
48 0 : (either/left
49 0 : (utils.errors/build-error
50 : :not-found
51 0 : {:code :error.resource/not-found
52 : :message "Resource not found"
53 0 : :context {:uuid (:uuid resource-data)}}))
54 7 : (if-not (entity/has-changes? existing resource-data)
55 0 : (either/right
56 0 : {:code :success.resource/no-changes
57 0 : :data existing})
58 7 : (c/mlet [saved
59 7 : (resource-postgres-repo/save! repo (entity/merge-updates existing resource-data))]
60 2 : (c/return
61 4 : {:code :success.resource/ok
62 1 : :data saved}))))))
63 :
64 :
65 4 : (defn deactivate-resource!
66 : "Deactivates a club resource (soft delete). Returns Either<Error, Resource>."
67 : [{:keys [repos]} resource-uuid]
68 4 : (let [repo (:resource-postgres-repo repos)]
69 4 : (resource-postgres-repo/deactivate! repo resource-uuid)))
|