wrbapp/frontend/server/api/sendmessage.post.js

64 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-01-21 21:36:22 +01:00
import { db } from '../utils/firebase'
import { getAuth } from 'firebase-admin/auth'
import { getMessaging } from 'firebase-admin/messaging'
export default defineEventHandler(async event => {
const { token, body, title } = await readBody(event);
if (!token) throw createError({ statusCode: 400, statusMessage: 'no-token'})
if (!body) throw createError({ statusCode: 400, statusMessage: 'no-body'})
if (!title) throw createError({ statusCode: 400, statusMessage: 'no-title'})
let decodedToken = null;
try {
decodedToken = await getAuth().verifyIdToken(token)
} catch (e) {
console.log(e)
throw createError({ statusCode: 500, statusMessage: 'error-verify-id'})
}
if (!decodedToken) throw createError({ statusCode: 500, statusMessage: 'error-verify-id-test'})
try {
const uid = decodedToken.uid;
const docRef = db.collection('users').doc(uid);
const doc = await docRef.get();
if (!doc.exists) throw createError({ statusCode: 500, statusMessage: 'doc-not-found'})
const data = doc.data()
if (!data.sendNews) throw createError({ statusCode: 500, statusMessage: 'no-permissions'})
const message = {
notification: {
title: title,
body: body,
},
webpush: {
notification: {
icon: '/ios/256.png'
}
},
topic: 'test',
apns: {
payload: {
aps: {
sound: 'default'
}
}
}
};
const response = await getMessaging().send(message)
console.log('Successfully sent message:', response);
return { code: 'success', response: response }
} catch (e) {
throw createError({ statusCode: 500, statusMessage: e.message })
}
})