@@ -2,45 +2,53 @@ import admin from 'firebase-admin'
22import { useUserDeviceCrud } from '@base/server/composables/useUserDeviceCrud'
33
44export default defineEventHandler ( async ( event ) => {
5- const { user_id } = await readBody ( event )
5+ try {
6+ const { user_id } = await readBody ( event )
67
7- if ( ! user_id )
8- return { message : 'User id is required' }
8+ if ( ! user_id )
9+ return { message : 'User id is required' }
910
10- const service = getFirebaseServiceAccount ( )
11+ const service = getFirebaseServiceAccount ( )
1112
12- if ( admin . apps . length === 0 ) {
13- admin . initializeApp ( {
14- credential : admin . credential . cert ( service as admin . ServiceAccount ) ,
15- } )
16- }
17-
18- const { getUserDeviceAllTokens } = useUserDeviceCrud ( { user_id } )
19- const response = await getUserDeviceAllTokens ( { } as ParsedFilterQuery )
20-
21- if ( response && response . total === 0 ) {
22- setResponseStatus ( event , 200 )
23- return { message : 'No device found' }
24- }
25- else {
26- const tokens = response . data ! . map < string > ( ( item : any ) => item . token_device )
27- const body = {
28- tokens,
29- notification : {
30- body : 'You have a new notification.' ,
31- title : 'Nuxt Template' ,
32- } ,
13+ if ( admin . apps . length === 0 ) {
14+ admin . initializeApp ( {
15+ credential : admin . credential . cert ( service as admin . ServiceAccount ) ,
16+ } )
3317 }
3418
35- const res = await admin . messaging ( ) . sendEachForMulticast ( body )
19+ const { getUserDeviceAllTokens } = useUserDeviceCrud ( { user_id } )
20+ const response = await getUserDeviceAllTokens ( { } as ParsedFilterQuery )
3621
37- if ( res ) {
22+ if ( response && response . total === 0 ) {
3823 setResponseStatus ( event , 200 )
39- return { message : 'Notification sent successfully ' }
24+ return { message : 'No device found ' }
4025 }
4126 else {
42- setResponseStatus ( event , 400 )
43- return { message : 'Failed to send notification' }
27+ const tokens = response . data ! . map < string > ( ( item : any ) => item . token_device )
28+ const body = {
29+ tokens,
30+ notification : {
31+ body : 'You have a new notification.' ,
32+ title : 'Nuxt Template' ,
33+ } ,
34+ }
35+
36+ const res = await admin . messaging ( ) . sendEachForMulticast ( body )
37+
38+ if ( res ) {
39+ setResponseStatus ( event , 200 )
40+ return { message : 'Notification sent successfully' }
41+ }
42+ else {
43+ setResponseStatus ( event , 400 )
44+ return { message : 'Failed to send notification' }
45+ }
4446 }
4547 }
48+ catch ( error : any ) {
49+ throw createError ( {
50+ statusCode : 500 ,
51+ statusMessage : error . message ,
52+ } )
53+ }
4654} )
0 commit comments