Line data Source code
1 4 : (ns matchscore.domain.team.repository.postgres
2 : (:require
3 : [honey.sql :as sql]
4 : [matchscore.domain.team.entity :as entity]
5 : [matchscore.utils.db :as utils.db]
6 : [matchscore.utils.pagination :as qh]
7 : [next.jdbc :as jdbc]))
8 :
9 :
10 4 : (defprotocol
11 : TeamPostgresRepository
12 : (find-by-id
13 : [this id]
14 : "Find team by UUID. Returns Team map or nil.")
15 : (find-by-ids
16 : [this ids]
17 : "Find teams by multiple UUIDs. Returns seq.")
18 : (search
19 : [this filters pagination]
20 : "Search teams by filters and pagination.
21 : filters: {:name {...}}
22 : pagination: {:limit 20 :cursor \"base64...\" :sort-by :name :sort-dir :asc}
23 : Returns {:items [...] :has-next-page bool :end-cursor \"base64-or-nil\"}"))
24 :
25 :
26 4 : (defn- filters->specs
27 : "Converts a GraphQL filters map to a seq of [column op value] specs."
28 : [{:keys [name]}]
29 5 : (qh/typed-filters->specs {:name name}))
30 :
31 :
32 4 : (defn- row->team
33 : "Converts a database row to a domain Team map."
34 : [row]
35 16 : (when row (entity/make-team (utils.db/unqualify-keys row))))
36 :
37 :
38 12 : (def ^:private valid-sort-fields #{:name})
39 :
40 :
41 8 : (def ^:private default-sort :name)
42 :
43 :
44 4 : (def ^:private base-query
45 28 : {:select [[:t.uuid :uuid]
46 12 : [:t.public-id :public-id]
47 12 : [:t.name :name]
48 12 : [:t.photo-url :photo-url]
49 12 : [:t.created-datetime :created-datetime]
50 12 : [:t.updated-datetime :updated-datetime]
51 12 : [:t.source :source]]
52 16 : :from [[:teams :t]]})
53 :
54 :
55 4 : (defrecord
56 : PostgresTeamRepository
57 : [ds]
58 : TeamPostgresRepository
59 :
60 : (find-by-id
61 : [_ id]
62 3 : (let [query (->
63 1 : base-query
64 8 : (assoc :where [:= :t.uuid [:cast id :uuid]]))
65 1 : result (->>
66 3 : (sql/format query)
67 3 : (jdbc/execute! ds)
68 1 : first)]
69 3 : (row->team result)))
70 :
71 : (find-by-ids
72 : [_ ids]
73 4 : (if (empty? ids)
74 0 : []
75 3 : (let [query (->
76 1 : base-query
77 13 : (assoc :where [:in :t.uuid (mapv #(vector :cast % :uuid) ids)]))]
78 1 : (->>
79 3 : (sql/format query)
80 3 : (jdbc/execute! ds)
81 2 : (mapv row->team)))))
82 :
83 : (search
84 : [_ filters pagination]
85 4 : (let [specs (filters->specs filters)
86 7 : query (qh/build-search-query base-query specs valid-sort-fields default-sort pagination)
87 1 : rows (->>
88 3 : (sql/format query)
89 3 : (jdbc/execute! ds)
90 2 : (mapv row->team))
91 6 : opts (when-not (:cursor pagination)
92 5 : (let [cnt-query (qh/build-count-query base-query specs)
93 3 : total (->>
94 3 : (sql/format cnt-query)
95 3 : (jdbc/execute-one! ds)
96 1 : utils.db/unqualify-keys
97 : :total)]
98 3 : {:total-count total}))]
99 7 : (qh/paginate-results rows valid-sort-fields default-sort pagination opts))))
100 :
101 :
102 4 : (defn make-repository
103 : "Creates a PostgresTeamRepository from a ds."
104 : [ds]
105 12 : (->PostgresTeamRepository ds))
|