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

64 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-01-22 17:37:10 +01:00
import { db, auth, messaging } from '../utils/firebase'
2023-01-21 21:36:22 +01:00
export default defineEventHandler(async event => {
2023-01-22 15:42:45 +01:00
const { token, body, title, topic } = await readBody(event);
2023-01-21 21:36:22 +01:00
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'})
2023-01-22 15:42:45 +01:00
if (!topic) throw createError({ statusCode: 400, statusMessage: 'no-topic'})
2023-01-21 21:36:22 +01:00
let decodedToken = null;
try {
2023-01-22 17:37:10 +01:00
decodedToken = await auth.verifyIdToken(token)
2023-01-21 21:36:22 +01:00
} 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: {
2023-01-22 20:02:53 +01:00
icon: '/ios/256.png',
2023-01-21 21:36:22 +01:00
}
},
2023-01-22 15:42:45 +01:00
topic: topic,
2023-01-21 21:36:22 +01:00
apns: {
payload: {
aps: {
sound: 'default'
}
}
}
};
2023-01-22 17:37:10 +01:00
const response = await messaging.send(message)
2023-01-21 21:36:22 +01:00
console.log('Successfully sent message:', response);
return { code: 'success', response: response }
} catch (e) {
throw createError({ statusCode: 500, statusMessage: e.message })
}
})