This repository has been archived by the owner on Mar 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
transaction.ts
135 lines (115 loc) · 4.53 KB
/
transaction.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
import admin from 'firebase-admin'
import { FirestoreSimple, Collection } from '../src'
//
// Start Firestore local emulator in background before start this script.
// `npx firebase emulators:start --only firestore`
//
// hack for using local emulator
process.env.GCLOUD_PROJECT = 'firestore-simple-test'
process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080'
admin.initializeApp({})
const firestore = admin.firestore()
const ROOT_PATH = 'example/admin_transaction'
interface User {
id: string,
name: string,
}
interface UserFriend {
id: string,
name: string,
created: Date,
ref: FirebaseFirestore.DocumentReference,
}
interface FriendRequest {
id: string,
from: string,
to: string,
status: 'pending' | 'accepted',
created: Date,
updated: Date,
}
class FriendRequestUsecase {
firestoreSimple: FirestoreSimple
userDao: Collection<User>
friendRequestDao: Collection<FriendRequest>
constructor ({ firestoreSimple, userDao, friendRequestDao }: {
firestoreSimple: FirestoreSimple,
userDao: Collection<User>,
friendRequestDao: Collection<FriendRequest>,
}) {
this.firestoreSimple = firestoreSimple
this.userDao = userDao
this.friendRequestDao = friendRequestDao
}
// Make friend request
async request (fromUserId: string, toUserId: string) {
// Check is target user already friend.
const friendDao = this.firestoreSimple.collection<UserFriend>({ path: `${ROOT_PATH}/user/${fromUserId}/friends` })
const friend = await friendDao.fetch(toUserId)
if (friend) throw new Error('Already friends!!')
// Create a unique id that does not depend on the order of the two user.
const requestId = [fromUserId, toUserId].sort().join('_')
await this.friendRequestDao.set({
id: requestId,
from: fromUserId,
to: toUserId,
status: 'pending',
created: new Date(),
updated: new Date(),
})
}
async getPendingRequest (userId: string) {
const pendingRequests = await this.friendRequestDao
.where('status', '==', 'pending')
.where('to', '==', userId)
.fetch()
if (pendingRequests.length === 0) return null
return pendingRequests[0]
}
// Accept friend request
async accept (friendRequest: FriendRequest) {
// Change status
await this.friendRequestDao.set({ ...friendRequest, status: 'accepted', updated: new Date() })
// Create each friend data that will set /user/:userId/friends/
const fromRef = this.userDao.docRef(friendRequest.from)
const fromUserFriend = { id: friendRequest.from, name: friendRequest.from, created: new Date(), ref: fromRef }
const toRef = this.userDao.docRef(friendRequest.to)
const toUserFriend = { id: friendRequest.to, name: friendRequest.to, created: new Date(), ref: toRef }
// Register each other's data.
const toUserFriendDao = this.firestoreSimple.collection<UserFriend>({ path: `${ROOT_PATH}/user/${toUserFriend}/friends` })
const fromUserFriendDao = this.firestoreSimple.collection<UserFriend>({ path: `${ROOT_PATH}/user/${fromUserFriend}/friends` })
await fromUserFriendDao.set(toUserFriend)
await toUserFriendDao.set(fromUserFriend)
}
}
const main = async () => {
const firestoreSimple = new FirestoreSimple(firestore)
const userDao = firestoreSimple.collection<User>({ path: `${ROOT_PATH}/user` })
const friendRequestDao = firestoreSimple.collection<FriendRequest>({ path: `${ROOT_PATH}/request_friend` })
// Clean before execute data
const prevUsers = await userDao.fetchAll()
await userDao.bulkDelete(prevUsers.map((user) => user.id))
const prevRequests = await friendRequestDao.fetchAll()
await friendRequestDao.bulkDelete(prevRequests.map((req) => req.id))
await userDao.docRef('alice').collection('friends').doc('bob').delete()
await userDao.docRef('bob').collection('friends').doc('alice').delete()
// Setup two user data
const bobId = await userDao.set({ id: 'bob', name: 'bob' })
const aliceId = await userDao.set({ id: 'alice', name: 'alice' })
const friendRequestUsecase = new FriendRequestUsecase({ firestoreSimple, userDao, friendRequestDao })
// Start transaction
// Bob send friend request to alice
await firestoreSimple.runTransaction(async (_tx) => {
await friendRequestUsecase.request(bobId, aliceId)
})
// End transaction
// Start transaction
// Alice check friend request and accept.
await firestoreSimple.runTransaction(async (_tx) => {
const request = await friendRequestUsecase.getPendingRequest(aliceId)
if (!request) return
await friendRequestUsecase.accept(request)
})
// End transaction
}
main()