1
1
import { Context , NextFunction } from "grammy" ;
2
2
import { prisma } from "../../utils/prisma" ;
3
3
4
- export const telegramQueueHandler = async ( ctx :Context , next :NextFunction ) => {
4
+ export const telegramQueueStartHandler = async ( ctx : Context , next : NextFunction ) => {
5
5
if ( ! ctx . message ) return
6
6
7
7
const fromTelegramId = ctx . message ?. from . id . toString ( )
8
-
8
+ ctx . replyWithChatAction ( 'typing' )
9
9
// check for isWaiting
10
- let checkIsWaiting = await prisma . telegram . findFirst ( {
11
- where :{
12
- id :fromTelegramId
13
- } ,
14
- select :{
15
- isWaiting :true ,
10
+ try {
11
+ let checkIsWaiting = await prisma . telegram . findFirst ( {
12
+ where : {
13
+ id : fromTelegramId
14
+ } ,
15
+ select : {
16
+ isWaiting : true ,
17
+ }
18
+ } )
19
+
20
+ // if it's first time user, id would be false
21
+ if ( ! checkIsWaiting ) {
22
+ next ( )
23
+ }
24
+
25
+ // short polling the db
26
+ // inneficient, will be updated to long polling or pubsub when scaling is needed
27
+ while ( checkIsWaiting ?. isWaiting ) {
28
+ console . log ( "🚀 ~ file: index.ts:28 ~ telegramQueueHandler ~ checkIsWaiting:" , checkIsWaiting )
29
+ await new Promise ( r => setTimeout ( r , 10000 ) )
30
+ checkIsWaiting = await prisma . telegram . findFirst ( {
31
+ where : {
32
+ id : fromTelegramId
33
+ } ,
34
+ select : {
35
+ isWaiting : true ,
36
+ }
37
+ } )
16
38
}
17
- } )
18
39
19
- // if it's first time user, id would be false
20
- if ( ! checkIsWaiting ) {
40
+ await prisma . telegram . upsert ( {
41
+ where : {
42
+ id : fromTelegramId
43
+ } ,
44
+ update : {
45
+ isWaiting : true
46
+ } ,
47
+ create : {
48
+ isWaiting : true ,
49
+ id : fromTelegramId
50
+ }
51
+ } )
52
+
53
+
54
+ }
55
+ catch ( err ) {
56
+
57
+ console . log ( err )
58
+
59
+ }
60
+ finally {
61
+
21
62
next ( )
63
+
22
64
}
65
+ }
66
+
23
67
24
- // short polling the db
25
- // inneficient, will be updated to long polling or pubsub when scaling is needed
26
- while ( checkIsWaiting ?. isWaiting ) {
27
- await new Promise ( r => setTimeout ( r , 10000 ) )
28
- checkIsWaiting = await prisma . telegram . findFirst ( {
29
- where :{
30
- id :fromTelegramId
68
+ export const telegramQueueEndHandler = async ( ctx : Context , next : NextFunction ) => {
69
+ if ( ! ctx . message ) return
70
+
71
+ const fromTelegramId = ctx . message ?. from . id . toString ( )
72
+
73
+ try {
74
+
75
+ await prisma . telegram . update ( {
76
+ where : {
77
+ id : fromTelegramId
31
78
} ,
32
- select : {
33
- isWaiting :true ,
79
+ data : {
80
+ isWaiting : false
34
81
}
35
82
} )
83
+
36
84
}
85
+ catch ( err ) {
37
86
38
- next ( )
87
+ console . log ( err )
88
+ }
39
89
}
0 commit comments