-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
736 lines (558 loc) · 22.8 KB
/
db.js
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
const dbConnector = require('./dbConnector');
const DRAFT_STORE_INTERVAL_MINUTES = 5;
class PostNotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'PostNotFound';
}
};
class DraftNotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'DraftNotFound';
}
};
class ImageNotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'ImageNotFound';
}
}
class UnknownStaticGroupError extends Error {
constructor(message) {
super(message);
this.name = 'UnknownStaticGroup';
}
}
class UnknownAfterPageIdError extends Error {
constructor(message) {
super(message);
this.name = 'UnknownAfterPageId';
}
}
const dep = {
newDate: () => new Date()
};
async function runOnTransaction(callback) {
const client = await dbConnector.connectToPool();
var toReturn;
try {
await client.query('BEGIN');
try {
toReturn = await callback(client);
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
}
} finally {
client.release();
}
return toReturn;
}
async function useClient(callback) {
const client = await dbConnector.connectToPool();
var toReturn;
try {
toReturn = await callback(client);
} finally {
client.release();
}
return toReturn;
}
function constructPostsFromRows(rows) {
const posts = [];
for (var row of rows) {
posts.push(constructPostFromRow(row));
}
return posts;
}
function constructPostFromRow(row) {
const post = {
_id: row.id,
createdAt: row.created_at,
updatedAt: row.updated_at,
workingTitle: row.working_title,
suggestedLocation: row.suggested_location,
previewPassword: row.preview_password,
};
// Only set published values when the post is published
if (row.draft_id) {
post.title = row.title;
post.content = row.content;
post.summary = row.summary;
post.url = row.url;
post.draftId = row.draft_id;
post.publishedAt = row.published_at;
post.republishedAt = row.republished_at;
post.staticGroup = row.static_group;
post.staticOrder = row.static_order;
}
return post;
}
function constructDraftFromRow(row) {
return {
_id: row.id,
postId: row.post_id,
createdAt: row.created_at,
updatedAt: row.updated_at,
title: row.title,
content: row.content,
suggestedLocation: row.suggested_location
};
}
function constructDraftsFromRows(rows) {
const drafts = [];
for (var row of rows) {
drafts.push(constructDraftFromRow(row));
}
return drafts;
}
function constructImageFromRow(row) {
return {
_id: row.id,
postId: row.post_id,
hash: row.hash,
filename: row.filename,
mimetype: row.mimetype,
imageData: row.image,
published: row.published,
originalDimensions: {width: row.width, height: row.height},
normalSizeImageData: row.normal_image,
normalDimensions: {width: row.normal_width, height: row.normal_height},
thumbnailImageData: row.thumbnail_image,
thumbnailDimensions: {width: row.thumbnail_width, height: row.thumbnail_height}
};
}
function constructImagesFromRows(rows) {
const images = [];
for (var row of rows) {
images.push(constructImageFromRow(row));
}
return images;
}
async function createPost(client, title, suggestedLocation) {
const insertPostResult = await client.query(
"INSERT into posts (working_title, suggested_location) VALUES ($1, $2) RETURNING id",
[ title, suggestedLocation ]);
const postId = insertPostResult.rows[0].id;
await client.query(
"INSERT into drafts (post_id, title, content) VALUES ($1, $2, '')",
[ postId, title ]);
return {
post: await getPost(client, postId),
drafts: [ await getNewestDraft(client, postId) ]
};
}
async function getPost(client, postId) {
const res = await client.query(
"SELECT * from posts where id=$1;",
[postId]);
if (res.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
return constructPostFromRow(res.rows[0]);
}
async function getNewestDraft(client, postId) {
const selectDraftResult = await client.query(
"SELECT * from drafts where post_id=$1 ORDER BY created_at DESC LIMIT 1;",
[postId]);
if (selectDraftResult.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
return constructDraftFromRow(selectDraftResult.rows[0]);
}
async function appendDraft(client, postId, title, content, suggestedLocation) {
const post = await getPost(client, postId);
const currentDraft = await getNewestDraft(client, postId);
if (null == currentDraft || null == post) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
const updatePostResult = await client.query(
"UPDATE posts SET working_title=$2, suggested_location=$3 WHERE id=$1",
[postId, title, suggestedLocation]);
if (updatePostResult.rowCount != 1) {
throw new Error(`Could not update post ${postId}`);
}
const ageMs = dep.newDate() - currentDraft.createdAt;
const ageSeconds = ageMs / 1000;
const ageMinutes = ageSeconds / 60;
const insert = (ageMinutes > DRAFT_STORE_INTERVAL_MINUTES) || (currentDraft._id == post.draftId);
var draftId;
if (insert) {
const insertDraftResult = await client.query(
'INSERT into drafts (post_id, title, content, suggested_location) VALUES ($1, $2, $3, $4) RETURNING id',
[ postId, title, content, suggestedLocation ]);
draftId = insertDraftResult.rows[0].id;
} else {
draftId = currentDraft._id;
const updateDraftResult = await client.query(
"UPDATE drafts SET title=$2, content=$3, suggested_location=$4 WHERE id=$1",
[draftId, title, content, suggestedLocation]);
if (updateDraftResult.rowCount != 1) {
throw new Error(`Could not update draft ${draftId}`);
}
}
const selectDraftResult = await client.query(
"SELECT * from drafts where id=$1;",
[draftId]);
if (selectDraftResult.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
return constructDraftFromRow(selectDraftResult.rows[0]);
}
async function getPostAndDrafts(client, postId) {
const selectDraftsResult = await client.query(
"SELECT * FROM drafts WHERE post_id = $1 ORDER BY created_at DESC;",
[postId]);
if (selectDraftsResult.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
return {
post: await getPost(client, postId),
drafts: constructDraftsFromRows(selectDraftsResult.rows)
};
}
async function getDraft(client, draftId) {
const selectDraftResult = await client.query(
"SELECT * from drafts where id=$1",
[draftId]);
if (selectDraftResult.rowCount == 0) {
throw new DraftNotFoundError(`DraftId ${draftId} missing`);
}
return constructDraftFromRow(selectDraftResult.rows[0]);
}
async function restoreDraft(client, draftId) {
const originalDraft = await getDraft(client, draftId);
const insertDraftResult = await client.query(
'INSERT into drafts (post_id, title, content) VALUES ($1, $2, $3) RETURNING id',
[ originalDraft.postId, originalDraft.title, originalDraft.content ]);
const newDraftId = insertDraftResult.rows[0].id;
return getDraft(client, newDraftId);
}
async function publishPost(
client,
postId,
draftId,
publishedAt,
republishedAt,
title,
content,
url,
summary,
imageIdsToPublish,
staticGroup,
afterPageId) {
async function calculateStaticOrder(client) {
if (staticGroup) {
const staticPages = await getAllStaticPages(client);
if (!(staticGroup in staticPages)) {
throw new UnknownStaticGroupError(`Static group ${staticGroup} unknown`);
}
const pages = staticPages[staticGroup];
if (afterPageId == postId) {
// Page isn't moving
} else if (afterPageId) {
// Page will be inserted relative to another page
var afterPageIndex = null;
for (var pageIndex = 0; pageIndex < pages.length; pageIndex++) {
if (pages[pageIndex]._id == afterPageId) {
afterPageIndex = pageIndex;
}
}
if (afterPageIndex == null) {
throw new UnknownAfterPageIdError(`Page ID ${afterPageId} is not part of ${staticGroup}`);
}
if (afterPageIndex + 1 == pages.length) {
// Page is going last
return pages[afterPageIndex].staticOrder + 10000;
} else if (postId != pages[afterPageIndex + 1]._id) {
// Page goes between two other pages
return (pages[afterPageIndex].staticOrder + pages[afterPageIndex + 1].staticOrder) / 2;
}
} else {
// Page is going first
if (pages.length > 0) {
// inserting the page before the other pages
return pages[0].staticOrder - 10000;
}
else {
// This is the first page
return 0;
}
}
}
else if (afterPageId) {
throw new UnknownAfterPageIdError('afterPostId can only be specified when staticPageName is specified');
}
return null;
}
const staticOrder = await calculateStaticOrder(client);
if (staticOrder != null) {
const updateStaticOrderResult = await client.query(
"UPDATE posts SET static_order = $2 WHERE id=$1",
[postId, staticOrder]);
if (updateStaticOrderResult.rowCount != 1) {
throw new Error(`Could not update post ${postId}`);
}
}
// Do not allow publishing multiple posts to the same url
// Unpublish in this case
const postToUnpublish = await getPostFromUrlOrNull(client, url);
if (postToUnpublish) {
if (postToUnpublish._id != postId) {
await unPublishPost(client, postToUnpublish._id);
}
}
const updatePostResult = await client.query(
"UPDATE posts SET published_at=$2, republished_at=$3, title=$4, content=$5, url=$6, summary=$7, static_group=$8, draft_id=$9 WHERE id=$1",
[postId, publishedAt, republishedAt, title, content, url, summary, staticGroup, draftId]);
if (updatePostResult.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
await client.query(
"UPDATE images SET published=false WHERE post_id=$1",
[postId]);
for (var imageId of imageIdsToPublish) {
const updateImageResult = await client.query(
"UPDATE images SET published=true WHERE id=$1",
[imageId]);
if (updateImageResult.rowCount == 0) {
throw new Error(`No image with id: ${imageId}`);
}
}
}
async function unPublishPost(client, postId) {
const updatePostResult = await client.query(
"UPDATE posts SET draft_id=NULL, title=NULL, content=NULL, url=NULL, published_at=NULL, republished_at=NULL, summary=NULL, static_group=NULL, static_order=NULL WHERE id=$1",
[postId]);
if (updatePostResult.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
await client.query(
"UPDATE images SET published=false WHERE post_id=$1",
[postId]);
}
async function setPostPreviewPassword(client, postId, previewPassword) {
const updateResult = await client.query(
"UPDATE posts SET preview_password=$2 WHERE id=$1",
[postId, previewPassword]);
if (updateResult.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
}
async function deletePost(client, postId) {
await client.query(
"DELETE FROM images WHERE post_id = $1",
[postId]);
await client.query(
"UPDATE posts SET draft_id=NULL WHERE id=$1",
[postId]);
const deleteDraftsResult = await client.query(
"DELETE FROM drafts WHERE post_id = $1",
[postId]);
if (deleteDraftsResult.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
const deletePostResult = await client.query(
"DELETE FROM posts WHERE id = $1",
[postId]);
if (deletePostResult.rowCount == 0) {
throw new PostNotFoundError(`No posts with id ${postId}`);
}
}
async function getPostFromUrl(client, url) {
const post = await getPostFromUrlOrNull(client, url);
if (post == null) {
throw new PostNotFoundError(`No post at url ${url}`);
}
return post;
};
async function getPosts(client, skip = 0, limit = Number.MAX_SAFE_INTEGER) {
const selectPostsResult = await client.query(
"SELECT * FROM posts ORDER BY updated_at DESC LIMIT $2 OFFSET $1",
[skip, limit]);
return constructPostsFromRows(selectPostsResult.rows);
}
async function countAllPosts(client) {
const selectPostsResult = await client.query("SELECT count(id) as numPosts FROM posts");
return selectPostsResult.rows[0].numposts;
}
async function getPublishedPosts(client, skip = 0, limit = Number.MAX_SAFE_INTEGER) {
const selectPostsResult = await client.query(
"SELECT * FROM posts WHERE url IS NOT NULL AND NOT(url='') AND static_group IS NULL ORDER BY published_at DESC LIMIT $2 OFFSET $1",
[skip, limit]);
return constructPostsFromRows(selectPostsResult.rows);
}
async function countPublishedPosts(client) {
const selectPostsResult = await client.query("SELECT count(id) as numPosts FROM posts WHERE url IS NOT NULL AND NOT(url='') AND static_group IS NULL");
return selectPostsResult.rows[0].numposts;
}
async function getPostFromUrlOrNull(client, url) {
const selectPostsResult = await client.query(
"SELECT * FROM posts where url=$1;",
[url]);
if (selectPostsResult.rowCount == 0) {
return null;
}
return constructPostFromRow(selectPostsResult.rows[0]);
};
async function getAllStaticPages(client) {
const selectPostsResult = await client.query(
"SELECT * FROM posts WHERE static_group IS NOT NULL ORDER BY static_order");
const posts = constructPostsFromRows(selectPostsResult.rows);
const staticPages = {};
const staticLocations = z3.staticLocations;
for (const staticLocation of staticLocations) {
staticPages[staticLocation] = [];
}
for (var post of posts) {
staticPages[post.staticGroup].push(post);
}
return staticPages;
};
async function insertImage(
client,
postId,
hash,
filename,
mimetype,
originalImageBuffer,
originalDimensions,
normalSizeBuffer,
normalDimensions,
thumbnailBuffer,
thumbnailDimensions) {
// Determine if the filename should change
const originalFilename = filename;
var duplicateFilenameCtr = 1;
var duplicateFilename;
do {
const selectImageByFilenameResult = await client.query(
"SELECT * FROM images WHERE post_id=$1 AND filename=$2",
[postId, filename]);
if (selectImageByFilenameResult.rowCount == 1) {
const duplicateFilenameImage = constructImageFromRow(selectImageByFilenameResult.rows[0]);
if (duplicateFilenameImage.hash != hash) {
// Need to change the filename
duplicateFilename = true;
filename = `${duplicateFilenameCtr}-${originalFilename}`;
duplicateFilenameCtr++;
} else {
duplicateFilename = false;
}
} else {
duplicateFilename = false;
}
} while (duplicateFilename);
var imageId;
const selectImageByHashResult = await client.query(
"SELECT * FROM images WHERE post_id=$1 AND hash=$2",
[postId, hash]);
if (selectImageByHashResult.rowCount == 0) {
const insertImageResult = await client.query(
"INSERT INTO images (post_id, hash, filename, mimetype, width, height, image, normal_width, normal_height, normal_image, thumbnail_width, thumbnail_height, thumbnail_image) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id",
[postId, hash, filename, mimetype, originalDimensions.width, originalDimensions.height, originalImageBuffer, normalDimensions.width, normalDimensions.height, normalSizeBuffer, thumbnailDimensions.width, thumbnailDimensions.height, thumbnailBuffer]);
if (insertImageResult.rowCount != 1) {
throw new Error("Can not insert an image");
}
imageId = insertImageResult.rows[0].id;
} else {
const imageRow = selectImageByHashResult.rows[0];
imageId = imageRow.id;
const updateImageResult = await client.query(
"UPDATE images SET filename=$2, mimetype=$3 WHERE id=$1",
[imageId, filename, mimetype]);
if (updateImageResult.rowCount != 1) {
throw new Error("Can not update an image");
}
}
return getImage(client, imageId);
};
async function getImageOrNull(client, imageId) {
const selectImageResult = await client.query(
"SELECT * FROM images WHERE id=$1",
[imageId]);
if (selectImageResult.rowCount == 0) {
return null;
}
return constructImageFromRow(selectImageResult.rows[0]);
};
async function getImage(client, imageId) {
const imageRecord = await getImageOrNull(client, imageId);
if (imageRecord == null) {
throw new ImageNotFoundError(`No image with id: ${imageId}`);
}
return imageRecord;
};
async function getImagesForPost(client, postId) {
const selectImagesResult = await client.query(
"SELECT * FROM images WHERE post_id=$1",
[postId]);
return constructImagesFromRows(selectImagesResult.rows);
}
async function getImageForPostByFilename(client, postId, filename) {
const selectImageResult = await client.query(
"SELECT * FROM images WHERE post_id=$1 AND images.filename=$2",
[postId, filename]);
if (selectImageResult.rows.length == 0) {
throw new ImageNotFoundError(`No image with postId: ${postId} and filename ${filename}`);
}
return constructImageFromRow(selectImageResult.rows[0]);
}
async function deleteImage(client, imageId) {
await client.query(
"DELETE FROM images WHERE id=$1",
[imageId]);
}
async function getImageOrNullByUrlAndFilename(client, url, filename) {
const selectImageResult = await client.query(
"SELECT images.* FROM images INNER JOIN posts on images.post_id = posts.id WHERE posts.url=$1 AND images.filename=$2",
[url, filename]);
if (selectImageResult.rowCount == 0) {
return null;
}
return constructImageFromRow(selectImageResult.rows[0]);
}
module.exports = {
PostNotFoundError,
DraftNotFoundError,
ImageNotFoundError,
UnknownStaticGroupError,
UnknownAfterPageIdError,
dep,
createPost: async (title, suggestedLocation) => await runOnTransaction(
async client => createPost(client, title, suggestedLocation)),
getPost: async postId => useClient(client => getPost(client, postId)),
getNewestDraft: async postId => useClient(client => getNewestDraft(client, postId)),
appendDraft: async (postId, title, content, suggestedLocation) =>
await runOnTransaction(async client => appendDraft(client, postId, title, content, suggestedLocation)),
getDraft: async draftId => await useClient(client => getDraft(client, draftId)),
restoreDraft: async draftId => await runOnTransaction(client => restoreDraft(client, draftId)),
publishPost: async (postId, draftId, publishedAt, republishedAt, title, content, url, summary, imageIdsToPublish, staticGroup, afterPageId) =>
await runOnTransaction(async client => await publishPost(client, postId, draftId, publishedAt, republishedAt, title, content, url, summary, imageIdsToPublish, staticGroup, afterPageId)),
unPublishPost: async postId => await runOnTransaction(async client => await unPublishPost(client, postId)),
setPostPreviewPassword: async (postId, previewPassword) => await useClient(async client => await setPostPreviewPassword(client, postId, previewPassword)),
deletePost: async postId => await runOnTransaction(client => deletePost(client, postId)),
getPostFromUrl: async url => await useClient(async client => getPostFromUrl(client, url)),
getPostAndDrafts: async postId => useClient(async client => getPostAndDrafts(client, postId)),
getAllStaticPages: async () => await useClient(getAllStaticPages),
getPosts: async (skip = 0, limit = Number.MAX_SAFE_INTEGER) => await useClient(
client => getPosts(client, skip, limit)),
getPublishedPosts: async (skip = 0, limit = Number.MAX_SAFE_INTEGER) =>
useClient(async client => await getPublishedPosts(client, skip, limit)),
countAllPosts: async () => await useClient(countAllPosts),
countPublishedPosts: async () => await useClient(countPublishedPosts),
getPostFromUrlOrNull: async url => useClient(async client => await getPostFromUrlOrNull(client, url)),
getPostFromUrl: async url => useClient(async client => await getPostFromUrl(client, url)),
insertImage: async (postId, hash, filename, mimetype, originalImageBuffer, originalDimensions, normalSizeBuffer, normalDimensions, thumbnailBuffer, thumbnailDimensions) =>
runOnTransaction(async client => await insertImage(client, postId, hash, filename, mimetype, originalImageBuffer, originalDimensions, normalSizeBuffer, normalDimensions, thumbnailBuffer, thumbnailDimensions)),
getImageOrNull: async imageId => useClient(async client => await getImageOrNull(client, imageId)),
getImage: async imageId => useClient(async client => await getImage(client, imageId)),
getImagesForPost: async postId => useClient(async client => await getImagesForPost(client, postId)),
getImageForPostByFilename: async (postId, filename) => useClient(async client => await getImageForPostByFilename(client, postId, filename)),
deleteImage: async imageId => useClient(async client => await deleteImage(client, imageId)),
getImageOrNullByUrlAndFilename: async (url, filename) => useClient(async client => await getImageOrNullByUrlAndFilename(client, url, filename)),
}
// Loading z3 after the exports works around a circular reference
const z3 = require('./z3');