-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposts.js
More file actions
282 lines (241 loc) · 6.95 KB
/
Copy pathposts.js
File metadata and controls
282 lines (241 loc) · 6.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
const { pool, query } = require('./db')
const { slugify } = require('./slug')
// Builds the WHERE clause shared by the listing and its count, so the two can
// never disagree about which posts a filter selects.
// The tag filter uses EXISTS so a post is counted once, no matter how many of
// its tags match, while the aggregated list of tags stays complete.
const filterPosts = ({ category, tag } = {}) => {
const conditions = []
const params = []
if (category) {
params.push(category)
conditions.push(`c.slug = $${params.length}`)
}
if (tag) {
params.push(tag)
conditions.push(`EXISTS (
SELECT 1
FROM post_tags pt
JOIN tags t ON t.id = pt.tag_id
WHERE pt.post_id = p.id AND t.slug = $${params.length}
)`)
}
return {
where: conditions.length ? `WHERE ${conditions.join(' AND ')}` : '',
params,
}
}
// How many posts the filters select, which is what the page count is based on.
const countPosts = async filters => {
const { where, params } = filterPosts(filters)
const { rows } = await query(
`SELECT COUNT(*)::int AS total
FROM posts p
LEFT JOIN categories c ON c.id = p.category_id
${where}`,
params
)
return rows[0].total
}
// One page of posts, newest first. LIMIT and OFFSET are the last two
// parameters, after however many the filters used.
const listPosts = async ({ category, tag, limit = 10, offset = 0 } = {}) => {
const { where, params } = filterPosts({ category, tag })
const { rows } = await query(
`SELECT
p.id,
p.title,
p.body,
p.created_at,
c.name AS category_name,
c.slug AS category_slug,
COALESCE(
JSON_AGG(
JSON_BUILD_OBJECT('name', t.name, 'slug', t.slug)
ORDER BY t.name
) FILTER (WHERE t.id IS NOT NULL),
'[]'
) AS tags
FROM posts p
LEFT JOIN categories c ON c.id = p.category_id
LEFT JOIN post_tags pt ON pt.post_id = p.id
LEFT JOIN tags t ON t.id = pt.tag_id
${where}
GROUP BY p.id, c.name, c.slug
ORDER BY p.created_at DESC, p.id DESC
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
[...params, limit, offset]
)
return rows
}
const getPost = async id => {
const { rows } = await query(
`SELECT
p.id,
p.title,
p.category_id,
p.body,
p.created_at,
c.name AS category_name,
c.slug AS category_slug,
COALESCE(
JSON_AGG(
JSON_BUILD_OBJECT('name', t.name, 'slug', t.slug)
ORDER BY t.name
) FILTER (WHERE t.id IS NOT NULL),
'[]'
) AS tags
FROM posts p
LEFT JOIN categories c ON c.id = p.category_id
LEFT JOIN post_tags pt ON pt.post_id = p.id
LEFT JOIN tags t ON t.id = pt.tag_id
WHERE p.id = $1
GROUP BY p.id, c.name, c.slug`,
[id]
)
return rows[0]
}
// Attaches the given tag names to a post: unknown tags are created, known ones
// are reused, and any tag no longer listed is detached.
const syncTags = async (client, postId, tagNames) => {
const tagIds = []
for (const name of tagNames) {
const slug = slugify(name)
if (!slug) continue
const tag = await client.query(
`INSERT INTO tags (name, slug)
VALUES ($1, $2)
ON CONFLICT (slug) DO UPDATE SET name = tags.name
RETURNING id`,
[name.trim(), slug]
)
tagIds.push(tag.rows[0].id)
}
await client.query(
`DELETE FROM post_tags
WHERE post_id = $1 AND NOT (tag_id = ANY ($2::int[]))`,
[postId, tagIds]
)
for (const tagId of tagIds) {
await client.query(
`INSERT INTO post_tags (post_id, tag_id)
VALUES ($1, $2)
ON CONFLICT DO NOTHING`,
[postId, tagId]
)
}
}
// Every write below runs in a transaction, so a post and its tags are always
// saved together or not at all.
const createPost = async ({ title, body, categoryId, tagNames = [] }) => {
const client = await pool.connect()
try {
await client.query('BEGIN')
const { rows } = await client.query(
`INSERT INTO posts (title, body, category_id)
VALUES ($1, $2, $3)
RETURNING id`,
[title, body, categoryId || null]
)
const postId = rows[0].id
await syncTags(client, postId, tagNames)
await client.query('COMMIT')
return postId
} catch (error) {
await client.query('ROLLBACK')
throw error
} finally {
client.release()
}
}
const updatePost = async (id, { title, body, categoryId, tagNames = [] }) => {
const client = await pool.connect()
try {
await client.query('BEGIN')
const { rowCount } = await client.query(
`UPDATE posts
SET title = $1, body = $2, category_id = $3
WHERE id = $4`,
[title, body, categoryId || null, id]
)
if (!rowCount) {
await client.query('ROLLBACK')
return false
}
await syncTags(client, id, tagNames)
await client.query('COMMIT')
return true
} catch (error) {
await client.query('ROLLBACK')
throw error
} finally {
client.release()
}
}
// The rows in post_tags go away on their own: the foreign key cascades.
const deletePost = async id => {
const { rowCount } = await query('DELETE FROM posts WHERE id = $1', [id])
return rowCount > 0
}
const listCategories = async () => {
const { rows } = await query(
`SELECT c.id, c.name, c.slug, COUNT(p.id)::int AS posts_count
FROM categories c
LEFT JOIN posts p ON p.category_id = c.id
GROUP BY c.id
ORDER BY c.name`
)
return rows
}
// Returns the new category, or undefined when the name is already taken:
// ON CONFLICT DO NOTHING makes the insert a no-op instead of an error, so the
// route can tell the two cases apart without inspecting error codes.
const createCategory = async name => {
const { rows } = await query(
`INSERT INTO categories (name, slug)
VALUES ($1, $2)
ON CONFLICT DO NOTHING
RETURNING id, name, slug`,
[name, slugify(name)]
)
return rows[0]
}
const listTags = async () => {
const { rows } = await query(
`SELECT t.id, t.name, t.slug, COUNT(pt.post_id)::int AS posts_count
FROM tags t
LEFT JOIN post_tags pt ON pt.tag_id = t.id
GROUP BY t.id
ORDER BY t.name`
)
return rows
}
// Tags whose name contains `term`, most used first, for the autocomplete.
// % and _ are escaped so a user typing them searches for the character itself
// instead of turning it into a wildcard.
const searchTags = async (term, limit = 8) => {
const pattern = `%${term.replace(/[\\%_]/g, '\\$&')}%`
const { rows } = await query(
`SELECT t.name, t.slug, COUNT(pt.post_id)::int AS posts_count
FROM tags t
LEFT JOIN post_tags pt ON pt.tag_id = t.id
WHERE t.name ILIKE $1 ESCAPE '\\'
GROUP BY t.id
ORDER BY posts_count DESC, t.name
LIMIT $2`,
[pattern, limit]
)
return rows
}
module.exports = {
listPosts,
countPosts,
getPost,
createPost,
updatePost,
deletePost,
listCategories,
createCategory,
listTags,
searchTags,
}