forked from cypress-io/cypress-realworld-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.ts
859 lines (709 loc) · 25 KB
/
database.ts
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
import path from "path";
import bcrypt from "bcryptjs";
import fs from "fs";
import { v4 } from "uuid";
import {
uniqBy,
map,
sample,
reject,
includes,
orderBy,
flow,
flatMap,
curry,
get,
constant,
filter,
inRange,
remove,
} from "lodash/fp";
import { isWithinInterval } from "date-fns";
import low from "lowdb";
import FileSync from "lowdb/adapters/FileSync";
import shortid from "shortid";
import {
BankAccount,
Transaction,
User,
Contact,
TransactionStatus,
TransactionRequestStatus,
Like,
Comment,
PaymentNotification,
PaymentNotificationStatus,
LikeNotification,
CommentNotification,
NotificationType,
NotificationPayloadType,
NotificationsType,
TransactionResponseItem,
TransactionPayload,
BankTransfer,
BankTransferPayload,
BankTransferType,
NotificationResponseItem,
TransactionQueryPayload,
DefaultPrivacyLevel,
} from "../src/models";
import Fuse from "fuse.js";
import {
isPayment,
getTransferAmount,
hasSufficientFunds,
getChargeAmount,
hasDateQueryFields,
getDateQueryFields,
hasAmountQueryFields,
getAmountQueryFields,
getQueryWithoutFilterFields,
getPayAppCreditedAmount,
isRequestTransaction,
formatFullName,
isLikeNotification,
isCommentNotification,
} from "../src/utils/transactionUtils";
import { DbSchema } from "../src/models/db-schema";
export type TDatabase = {
users: User[];
contacts: Contact[];
bankaccounts: BankAccount[];
transactions: Transaction[];
likes: Like[];
comments: Comment[];
notifications: NotificationType[];
banktransfers: BankTransfer[];
};
const USER_TABLE = "users";
const CONTACT_TABLE = "contacts";
const BANK_ACCOUNT_TABLE = "bankaccounts";
const TRANSACTION_TABLE = "transactions";
const LIKE_TABLE = "likes";
const COMMENT_TABLE = "comments";
const NOTIFICATION_TABLE = "notifications";
const BANK_TRANSFER_TABLE = "banktransfers";
const databaseFile = path.join(__dirname, "../data/database.json");
const adapter = new FileSync<DbSchema>(databaseFile);
const db = low(adapter);
export const seedDatabase = () => {
const testSeed = JSON.parse(
fs.readFileSync(path.join(process.cwd(), "data", "database-seed.json"), "utf-8")
);
// seed database with test data
db.setState(testSeed).write();
return;
};
export const getAllUsers = () => db.get(USER_TABLE).value();
export const getAllPublicTransactions = () =>
db.get(TRANSACTION_TABLE).filter({ privacyLevel: DefaultPrivacyLevel.public }).value();
export const getAllForEntity = (entity: keyof DbSchema) => db.get(entity).value();
export const getAllBy = (entity: keyof DbSchema, key: string, value: any) => {
const result = db
.get(entity)
// @ts-ignore
.filter({ [`${key}`]: value })
.value();
return result;
};
export const getBy = (entity: keyof DbSchema, key: string, value: any) => {
const result = db
.get(entity)
// @ts-ignore
.find({ [`${key}`]: value })
.value();
return result;
};
export const getAllByObj = (entity: keyof DbSchema, query: object) => {
const result = db
.get(entity)
// @ts-ignore
.filter(query)
.value();
return result;
};
// Search
export const cleanSearchQuery = (query: string) => query.replace(/[^a-zA-Z0-9]/g, "");
export const setupSearch = curry((items: object[], options: {}, query: string) => {
const fuse = new Fuse(items, options);
return fuse.search(query);
});
export const performSearch = (items: object[], options: {}, query: string) =>
flow(
cleanSearchQuery,
setupSearch(items, options),
map((result) => result.item)
)(query);
export const searchUsers = (query: string) => {
const items = getAllUsers();
return performSearch(
items,
{
keys: ["firstName", "lastName", "username", "email", "phoneNumber"],
},
query
) as User[];
};
export const removeUserFromResults = (userId: User["id"], results: User[]) =>
remove({ id: userId }, results);
// convenience methods
// User
export const getUserBy = (key: string, value: any) => getBy(USER_TABLE, key, value);
export const getUserId = (user: User): string => user.id;
export const getUserById = (id: string) => getUserBy("id", id);
export const getUserByUsername = (username: string) => getUserBy("username", username);
export const createUser = (userDetails: Partial<User>): User => {
const password = bcrypt.hashSync(userDetails.password!, 10);
const user: User = {
id: shortid(),
uuid: v4(),
firstName: userDetails.firstName!,
lastName: userDetails.lastName!,
username: userDetails.username!,
password,
email: userDetails.email!,
phoneNumber: userDetails.phoneNumber!,
balance: userDetails.balance! || 0,
avatar: userDetails.avatar!,
defaultPrivacyLevel: userDetails.defaultPrivacyLevel!,
createdAt: new Date(),
modifiedAt: new Date(),
};
saveUser(user);
return user;
};
const saveUser = (user: User) => {
db.get(USER_TABLE).push(user).write();
};
export const updateUserById = (userId: string, edits: Partial<User>) => {
const user = getUserById(userId);
db.get(USER_TABLE).find(user).assign(edits).write();
};
// Contact
export const getContactBy = (key: string, value: any) => getBy(CONTACT_TABLE, key, value);
export const getContactsBy = (key: string, value: any) => getAllBy(CONTACT_TABLE, key, value);
export const getContactsByUsername = (username: string) =>
flow(getUserByUsername, getUserId, getContactsByUserId)(username);
export const getContactsByUserId = (userId: string): Contact[] => getContactsBy("userId", userId);
export const createContact = (contact: Contact) => {
db.get(CONTACT_TABLE).push(contact).write();
// manual lookup after create
return getContactBy("id", contact.id);
};
export const removeContactById = (contactId: string) => {
const contact = getContactBy("id", contactId);
db.get(CONTACT_TABLE).remove(contact).write();
};
export const createContactForUser = (userId: string, contactUserId: string) => {
const contactId = shortid();
const contact: Contact = {
id: contactId,
uuid: v4(),
userId,
contactUserId,
createdAt: new Date(),
modifiedAt: new Date(),
};
// Write contact record to the database
const result = createContact(contact);
return result;
};
// Bank Account
export const getBankAccountBy = (key: string, value: any) => getBy(BANK_ACCOUNT_TABLE, key, value);
export const getBankAccountById = (id: string) => getBankAccountBy("id", id);
export const getBankAccountsBy = (key: string, value: any) =>
getAllBy(BANK_ACCOUNT_TABLE, key, value);
export const createBankAccount = (bankaccount: BankAccount) => {
db.get(BANK_ACCOUNT_TABLE).push(bankaccount).write();
// manual lookup after create
return getBankAccountBy("id", bankaccount.id);
};
export const createBankAccountForUser = (userId: string, accountDetails: Partial<BankAccount>) => {
const accountId = shortid();
const bankaccount: BankAccount = {
id: accountId,
uuid: v4(),
userId,
bankName: accountDetails.bankName!,
accountNumber: accountDetails.accountNumber!,
routingNumber: accountDetails.routingNumber!,
isDeleted: false,
createdAt: new Date(),
modifiedAt: new Date(),
};
// Write bank account record to the database
const result = createBankAccount(bankaccount);
return result;
};
export const removeBankAccountById = (bankAccountId: string) => {
db.get(BANK_ACCOUNT_TABLE)
.find({ id: bankAccountId })
.assign({ isDeleted: true }) // soft delete
.write();
};
// Bank Transfer
// Note: Balance transfers from/to bank accounts is a future feature,
// but some of the backend database functionality is already implemented here.
/* istanbul ignore next */
export const getBankTransferBy = (key: string, value: any) =>
getBy(BANK_TRANSFER_TABLE, key, value);
export const getBankTransfersBy = (key: string, value: any) =>
getAllBy(BANK_TRANSFER_TABLE, key, value);
export const getBankTransfersByUserId = (userId: string) => getBankTransfersBy("userId", userId);
/* istanbul ignore next */
export const createBankTransfer = (bankTransferDetails: BankTransferPayload) => {
const bankTransfer: BankTransfer = {
id: shortid(),
uuid: v4(),
...bankTransferDetails,
createdAt: new Date(),
modifiedAt: new Date(),
};
const savedBankTransfer = saveBankTransfer(bankTransfer);
return savedBankTransfer;
};
/* istanbul ignore next */
const saveBankTransfer = (bankTransfer: BankTransfer): BankTransfer => {
db.get(BANK_TRANSFER_TABLE).push(bankTransfer).write();
// manual lookup after banktransfer created
return getBankTransferBy("id", bankTransfer.id);
};
// Transaction
export const getTransactionBy = (key: string, value: any) => getBy(TRANSACTION_TABLE, key, value);
export const getTransactionById = (id: string) => getTransactionBy("id", id);
export const getTransactionsByObj = (query: object) => getAllByObj(TRANSACTION_TABLE, query);
export const getTransactionByIdForApi = (id: string) =>
formatTransactionForApiResponse(getTransactionBy("id", id));
export const getTransactionsForUserForApi = (userId: string, query?: object) =>
flow(getTransactionsForUserByObj(userId), formatTransactionsForApiResponse)(query);
export const getFullNameForUser = (userId: User["id"]) => flow(getUserById, formatFullName)(userId);
export const formatTransactionForApiResponse = (
transaction: Transaction
): TransactionResponseItem => {
const receiver = getUserById(transaction.receiverId);
const sender = getUserById(transaction.senderId);
const receiverName = getFullNameForUser(transaction.receiverId);
const senderName = getFullNameForUser(transaction.senderId);
const likes = getLikesByTransactionId(transaction.id);
const comments = getCommentsByTransactionId(transaction.id);
return {
receiverName,
senderName,
receiverAvatar: receiver.avatar,
senderAvatar: sender.avatar,
likes,
comments,
...transaction,
};
};
export const formatTransactionsForApiResponse = (
transactions: Transaction[]
): TransactionResponseItem[] =>
orderBy(
[(transaction: Transaction) => new Date(transaction.modifiedAt)],
["desc"],
transactions.map((transaction) => formatTransactionForApiResponse(transaction))
);
export const getAllTransactionsForUserByObj = curry((userId: string, query?: object) => {
const queryWithoutFilterFields = query && getQueryWithoutFilterFields(query);
const queryFields = queryWithoutFilterFields || query;
const userTransactions = flatMap(getTransactionsByObj)([
{
receiverId: userId,
...queryFields,
},
{
senderId: userId,
...queryFields,
},
]);
if (query && (hasDateQueryFields(query) || hasAmountQueryFields(query))) {
const { dateRangeStart, dateRangeEnd } = getDateQueryFields(query);
const { amountMin, amountMax } = getAmountQueryFields(query);
return flow(
transactionsWithinDateRange(dateRangeStart!, dateRangeEnd!),
transactionsWithinAmountRange(amountMin!, amountMax!)
)(userTransactions);
}
return userTransactions;
});
export const transactionsWithinAmountRange = curry(
(amountMin: number, amountMax: number, transactions: Transaction[]) => {
if (!amountMin || !amountMax) {
return transactions;
}
return filter(
(transaction: Transaction) => inRange(amountMin, amountMax, transaction.amount),
transactions
);
}
);
export const transactionsWithinDateRange = curry(
(dateRangeStart: string, dateRangeEnd: string, transactions: Transaction[]) => {
if (!dateRangeStart || !dateRangeEnd) {
return transactions;
}
return filter(
(transaction: Transaction) =>
isWithinInterval(new Date(transaction.createdAt), {
start: new Date(dateRangeStart),
end: new Date(dateRangeEnd),
}),
transactions
);
}
);
export const getTransactionsForUserByObj = curry((userId: string, query: object) =>
flow(getAllTransactionsForUserByObj(userId), uniqBy("id"))(query)
);
export const getContactIdsForUser = (userId: string): Contact["id"][] =>
flow(getContactsByUserId, map("contactUserId"))(userId);
export const getTransactionsForUserContacts = (userId: string, query?: object) =>
uniqBy(
"id",
flatMap(
(contactId) => getTransactionsForUserForApi(contactId, query),
getContactIdsForUser(userId)
)
);
export const getTransactionIds = (transactions: Transaction[]) => map("id", transactions);
export const getContactsTransactionIds = (userId: string): Transaction["id"][] =>
flow(getTransactionsForUserContacts, getTransactionIds)(userId);
export const nonContactPublicTransactions = (userId: string): Transaction[] => {
const contactsTransactionIds = getContactsTransactionIds(userId);
return flow(
getAllPublicTransactions,
reject((transaction: Transaction) => includes(transaction.id, contactsTransactionIds))
)();
};
export const getNonContactPublicTransactionsForApi = (userId: string) =>
flow(nonContactPublicTransactions, formatTransactionsForApiResponse)(userId);
export const getPublicTransactionsDefaultSort = (userId: string) => ({
contactsTransactions: getTransactionsForUserContacts(userId),
publicTransactions: getNonContactPublicTransactionsForApi(userId),
});
export const getPublicTransactionsByQuery = (userId: string, query: TransactionQueryPayload) => {
if (query && (hasDateQueryFields(query) || hasAmountQueryFields(query))) {
const { dateRangeStart, dateRangeEnd } = getDateQueryFields(query);
const { amountMin, amountMax } = getAmountQueryFields(query);
return {
contactsTransactions: getTransactionsForUserContacts(userId, query),
publicTransactions: flow(
transactionsWithinDateRange(dateRangeStart!, dateRangeEnd!),
transactionsWithinAmountRange(amountMin!, amountMax!)
)(getNonContactPublicTransactionsForApi(userId)),
};
} else {
return {
contactsTransactions: getTransactionsForUserContacts(userId),
publicTransactions: getNonContactPublicTransactionsForApi(userId),
};
}
};
export const resetPayAppBalance = constant(0);
export const debitPayAppBalance = (user: User, transaction: Transaction) => {
if (hasSufficientFunds(user, transaction)) {
flow(getChargeAmount, savePayAppBalance(user))(user, transaction);
} else {
/* istanbul ignore next */
flow(
getTransferAmount(user),
createBankTransferWithdrawal(user, transaction),
resetPayAppBalance,
savePayAppBalance(user)
)(transaction);
}
};
export const creditPayAppBalance = (user: User, transaction: Transaction) =>
flow(getPayAppCreditedAmount, savePayAppBalance(user))(user, transaction);
/* istanbul ignore next */
export const createBankTransferWithdrawal = curry(
(sender: User, transaction: Transaction, transferAmount: number) =>
createBankTransfer({
userId: sender.id,
source: transaction.source,
amount: transferAmount,
transactionId: transaction.id,
type: BankTransferType.withdrawal,
})
);
export const savePayAppBalance = curry((sender: User, balance: number) =>
updateUserById(get("id", sender), { balance })
);
export const createTransaction = (
userId: User["id"],
transactionType: "payment" | "request",
transactionDetails: TransactionPayload
): Transaction => {
const sender = getUserById(userId);
const receiver = getUserById(transactionDetails.receiverId);
const transaction: Transaction = {
id: shortid(),
uuid: v4(),
source: transactionDetails.source,
amount: transactionDetails.amount * 100,
description: transactionDetails.description,
receiverId: transactionDetails.receiverId,
senderId: userId,
privacyLevel: transactionDetails.privacyLevel || sender.defaultPrivacyLevel,
status: TransactionStatus.pending,
requestStatus: transactionType === "request" ? TransactionRequestStatus.pending : undefined,
createdAt: new Date(),
modifiedAt: new Date(),
};
const savedTransaction = saveTransaction(transaction);
// if payment, debit sender's balance for payment amount
if (isPayment(transaction)) {
debitPayAppBalance(sender, transaction);
creditPayAppBalance(receiver, transaction);
updateTransactionById(transaction.id, {
status: TransactionStatus.complete,
});
createPaymentNotification(
transaction.receiverId,
transaction.id,
PaymentNotificationStatus.received
);
} else {
createPaymentNotification(
transaction.receiverId,
transaction.id,
PaymentNotificationStatus.requested
);
}
return savedTransaction;
};
const saveTransaction = (transaction: Transaction): Transaction => {
db.get(TRANSACTION_TABLE).push(transaction).write();
// manual lookup after transaction created
return getTransactionBy("id", transaction.id);
};
export const updateTransactionById = (transactionId: string, edits: Partial<Transaction>) => {
const transaction = getTransactionBy("id", transactionId);
const { senderId, receiverId } = transaction;
const sender = getUserById(senderId);
const receiver = getUserById(receiverId);
// if payment, debit sender's balance for payment amount
if (isRequestTransaction(transaction)) {
debitPayAppBalance(receiver, transaction);
creditPayAppBalance(sender, transaction);
edits.status = TransactionStatus.complete;
createPaymentNotification(
transaction.senderId,
transaction.id,
PaymentNotificationStatus.received
);
}
db.get(TRANSACTION_TABLE).find(transaction).assign(edits).write();
};
// Likes
export const getLikeBy = (key: string, value: any): Like => getBy(LIKE_TABLE, key, value);
export const getLikesByObj = (query: object) => getAllByObj(LIKE_TABLE, query);
export const getLikeById = (id: string): Like => getLikeBy("id", id);
export const getLikesByTransactionId = (transactionId: string) => getLikesByObj({ transactionId });
export const createLike = (userId: string, transactionId: string): Like => {
const like = {
id: shortid(),
uuid: v4(),
userId,
transactionId,
createdAt: new Date(),
modifiedAt: new Date(),
};
const savedLike = saveLike(like);
return savedLike;
};
export const createLikes = (userId: string, transactionId: string) => {
const { senderId, receiverId } = getTransactionById(transactionId);
const like = createLike(userId, transactionId);
/* istanbul ignore next */
if (userId !== senderId || userId !== receiverId) {
createLikeNotification(senderId, transactionId, like.id);
createLikeNotification(receiverId, transactionId, like.id);
} else if (userId === senderId) {
createLikeNotification(senderId, transactionId, like.id);
} else {
createLikeNotification(receiverId, transactionId, like.id);
}
};
const saveLike = (like: Like): Like => {
db.get(LIKE_TABLE).push(like).write();
// manual lookup after like created
return getLikeById(like.id);
};
// Comments
export const getCommentBy = (key: string, value: any): Comment => getBy(COMMENT_TABLE, key, value);
export const getCommentsByObj = (query: object) => getAllByObj(COMMENT_TABLE, query);
export const getCommentById = (id: string): Comment => getCommentBy("id", id);
export const getCommentsByTransactionId = (transactionId: string) =>
getCommentsByObj({ transactionId });
export const createComment = (userId: string, transactionId: string, content: string): Comment => {
const comment = {
id: shortid(),
uuid: v4(),
content,
userId,
transactionId,
createdAt: new Date(),
modifiedAt: new Date(),
};
const savedComment = saveComment(comment);
return savedComment;
};
export const createComments = (userId: string, transactionId: string, content: string) => {
const { senderId, receiverId } = getTransactionById(transactionId);
const comment = createComment(userId, transactionId, content);
/* istanbul ignore next */
if (userId !== senderId || userId !== receiverId) {
createCommentNotification(senderId, transactionId, comment.id);
createCommentNotification(receiverId, transactionId, comment.id);
} else if (userId === senderId) {
createCommentNotification(senderId, transactionId, comment.id);
} else {
createCommentNotification(receiverId, transactionId, comment.id);
}
};
const saveComment = (comment: Comment): Comment => {
db.get(COMMENT_TABLE).push(comment).write();
// manual lookup after comment created
return getCommentById(comment.id);
};
// Notifications
export const getNotificationBy = (key: string, value: any): NotificationType =>
getBy(NOTIFICATION_TABLE, key, value);
export const getNotificationsByObj = (query: object): Notification[] =>
getAllByObj(NOTIFICATION_TABLE, query);
export const getUnreadNotificationsByUserId = (userId: string) =>
flow(getNotificationsByObj, formatNotificationsForApiResponse)({ userId, isRead: false });
export const createPaymentNotification = (
userId: string,
transactionId: string,
status: PaymentNotificationStatus
): PaymentNotification => {
const notification: PaymentNotification = {
id: shortid(),
uuid: v4(),
userId: userId,
transactionId: transactionId,
status,
isRead: false,
createdAt: new Date(),
modifiedAt: new Date(),
};
saveNotification(notification);
return notification;
};
export const createLikeNotification = (
userId: string,
transactionId: string,
likeId: string
): LikeNotification => {
const notification: LikeNotification = {
id: shortid(),
uuid: v4(),
userId: userId,
transactionId: transactionId,
likeId: likeId,
isRead: false,
createdAt: new Date(),
modifiedAt: new Date(),
};
saveNotification(notification);
return notification;
};
export const createCommentNotification = (
userId: string,
transactionId: string,
commentId: string
): CommentNotification => {
const notification: CommentNotification = {
id: shortid(),
uuid: v4(),
userId: userId,
transactionId: transactionId,
commentId: commentId,
isRead: false,
createdAt: new Date(),
modifiedAt: new Date(),
};
saveNotification(notification);
return notification;
};
const saveNotification = (notification: NotificationType) => {
db.get(NOTIFICATION_TABLE).push(notification).write();
};
export const createNotifications = (userId: string, notifications: NotificationPayloadType[]) =>
notifications.flatMap((item: NotificationPayloadType) => {
if ("status" in item && item.type === NotificationsType.payment) {
return createPaymentNotification(userId, item.transactionId, item.status);
} else if ("likeId" in item && item.type === NotificationsType.like) {
return createLikeNotification(userId, item.transactionId, item.likeId);
} else {
/* istanbul ignore next */
if ("commentId" in item) {
return createCommentNotification(userId, item.transactionId, item.commentId);
}
}
});
export const updateNotificationById = (
userId: string,
notificationId: string,
edits: Partial<NotificationType>
) => {
const notification = getNotificationBy("id", notificationId);
db.get(NOTIFICATION_TABLE).find(notification).assign(edits).write();
};
export const formatNotificationForApiResponse = (
notification: NotificationType
): NotificationResponseItem => {
let userFullName = getFullNameForUser(notification.userId);
const transaction = getTransactionById(notification.transactionId);
if (isRequestTransaction(transaction)) {
userFullName = getFullNameForUser(transaction.senderId);
}
if (isLikeNotification(notification)) {
const like = getLikeById(notification.likeId);
userFullName = getFullNameForUser(like.userId);
}
if (isCommentNotification(notification)) {
const comment = getCommentById(notification.commentId);
userFullName = getFullNameForUser(comment.userId);
}
return {
userFullName,
...notification,
};
};
export const formatNotificationsForApiResponse = (
notifications: NotificationResponseItem[]
): NotificationResponseItem[] =>
orderBy(
[(notification: NotificationResponseItem) => new Date(notification.modifiedAt)],
["desc"],
notifications.map((notification) => formatNotificationForApiResponse(notification))
);
// dev/test private methods
/* istanbul ignore next */
export const getRandomUser = () => {
const users = getAllUsers();
return sample(users)!;
};
/* istanbul ignore next */
export const getAllContacts = () => db.get(CONTACT_TABLE).value();
/* istanbul ignore next */
export const getAllTransactions = () => db.get(TRANSACTION_TABLE).value();
/* istanbul ignore */
export const getBankAccountsByUserId = (userId: string) => getBankAccountsBy("userId", userId);
/* istanbul ignore next */
export const getNotificationById = (id: string): NotificationType => getNotificationBy("id", id);
/* istanbul ignore next */
export const getNotificationsByUserId = (userId: string) => getNotificationsByObj({ userId });
/* istanbul ignore next */
export const getBankTransferByTransactionId = (transactionId: string) =>
getBankTransferBy("transactionId", transactionId);
/* istanbul ignore next */
export const getTransactionsBy = (key: string, value: string) =>
getAllBy(TRANSACTION_TABLE, key, value);
/* istanbul ignore next */
export const getTransactionsByUserId = (userId: string) => getTransactionsBy("receiverId", userId);
export default db;