mirror of
https://git.hmsn.ink/kospo/helptalk/push.git
synced 2026-03-20 06:33:30 +09:00
first
This commit is contained in:
78
app.js
Normal file
78
app.js
Normal file
@@ -0,0 +1,78 @@
|
||||
// 서버 사이드 (Node.js Express)
|
||||
const express = require('express');
|
||||
const webpush = require('web-push');
|
||||
const bodyParser = require('body-parser');
|
||||
const cors = require('cors');
|
||||
const app = express();
|
||||
|
||||
// VAPID 키 생성 (최초 1회 생성 후 저장해서 사용)
|
||||
// const vapidKeys = webpush.generateVAPIDKeys();
|
||||
// const publicVapidKey = vapidKeys.publicKey;
|
||||
// const privateVapidKey = vapidKeys.privateKey;
|
||||
|
||||
const publicVapidKey = 'BLBOCa4S62kYyYn3qwAAwSw-8g9gQ5xK6BU_PYC4f-NAZkihmBRkjYbI9ao5npLEW88H2bsDiCsSznNbtWSSNWA'
|
||||
privateVapidKey = 'KFyzoAfq6jawkfA16iwUd7NhQIBbWJ44XVvyPxb3L1g'
|
||||
|
||||
webpush.setVapidDetails(
|
||||
'mailto:bangae2@gmail.com',
|
||||
publicVapidKey,
|
||||
privateVapidKey
|
||||
);
|
||||
|
||||
// 구독 정보 저장소 (실제 구현시 DB 사용)
|
||||
const subscriptions = new Map();
|
||||
|
||||
app.use(bodyParser.json());
|
||||
app.use(cors({
|
||||
origin: '*'
|
||||
}))
|
||||
|
||||
// 클라이언트 구독 등록 엔드포인트
|
||||
app.post('/api/subscribe', (req, res) => {
|
||||
const subscription = req.body;
|
||||
const userId = req.headers['user-id']; // 사용자 식별자
|
||||
console.log(userId)
|
||||
subscriptions.set(userId, subscription);
|
||||
res.status(201).json({});
|
||||
});
|
||||
|
||||
// 푸시 메시지 전송 엔드포인트
|
||||
app.post('/api/push', async (req, res) => {
|
||||
const notifications = req.body;
|
||||
|
||||
if(!Array.isArray(notifications)) {
|
||||
return res.status(400).json({ error: 'Notifications must be an array' });
|
||||
}
|
||||
|
||||
const payload = JSON.stringify({
|
||||
notifications: notifications.map((notif, index) => ({
|
||||
...notif,
|
||||
title: `${notif.workNm}[${notif.insName}]`,
|
||||
tag: `notification-${Date.now()}-${index}`
|
||||
}))
|
||||
})
|
||||
|
||||
// const subscription = subscriptions.get(userId);
|
||||
|
||||
|
||||
try {
|
||||
|
||||
const sendPromises = Array.from(subscriptions.keys()).map(key => {
|
||||
if(key === "17131303") {
|
||||
webpush.sendNotification(subscriptions.get(key), payload);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
await Promise.all(sendPromises);
|
||||
res.status(200).json({ message: 'Notification sent successfully.' });
|
||||
} catch (error) {
|
||||
console.error('푸시 전송 실패:', error);
|
||||
res.status(500).json({ error: '푸시 전송 실패' });
|
||||
}
|
||||
});
|
||||
|
||||
// 서버 시작
|
||||
app.listen(3000, () => {
|
||||
console.log('푸시 서버가 3000 포트에서 실행중입니다.');
|
||||
});
|
||||
Reference in New Issue
Block a user