Compare commits

..

No commits in common. "main" and "main" have entirely different histories.
main ... main

6 changed files with 86 additions and 189 deletions

View File

@ -1,42 +1,13 @@
import express, { query } from 'express'; import express, { query } from 'express';
import { createDatabaseConnection } from '../db/database.js'; // db 연결 파일 import { createDatabaseConnection } from '../db/database.js'; // db 연결 파일
import { HandlePush } from './push.js';
import { dbConfig } from '../private/config.js'; import { dbConfig } from '../private/config.js';
import { HandlePush } from './push.js'; // const cmcd = "/JJ";
import { HandleUser } from './user.js'; // const db = "/JJ/db";
const router = express.Router(); const app = express();
app.use(express.json());
router.get('/version', async (req, res) => {
const {os_type} = req.query;
try {
const connection = await createDatabaseConnection(dbConfig);
let query = 'SELECT * FROM version';
const queryParams = [];
if (os_type) {
query += ' ';
query += 'WHERE os_type = ?';
queryParams.push(os_type);
}
// const [rows] = await connection.query('SELECT * FROM version');
const [rows] = await connection.query(query, queryParams);
await connection.end();
res.json(rows);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.get('/push', HandlePush);
router.get('/user/*', HandleUser);
export default router;
@ -102,16 +73,16 @@ export default router;
// DB 연결 테스트 // DB 연결 테스트
// app.get(`${db}/test`, async (req, res) => { app.get(`${db}/test`, async (req, res) => {
// try { try {
// const connection = await createDatabaseConnection(dbConfig); const connection = await createDatabaseConnection(dbConfig);
// const [rows] = await connection.query('SELECT 1 + 1 AS solution'); const [rows] = await connection.query('SELECT 1 + 1 AS solution');
// await connection.end(); await connection.end();
// res.json({ result: rows[0].solution }); res.json({ result: rows[0].solution });
// } catch (err) { } catch (err) {
// res.status(500).json({ error: err.message }); res.status(500).json({ error: err.message });
// } }
// }); });
// /////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////
@ -241,4 +212,4 @@ export default router;
// export default app; export default app;

View File

@ -1,53 +1,45 @@
import apn from 'apn'; import { admin } from '../firebaseConfig.js';
import path from 'path'; // path 모듈을 가져옵니다.
import { fileURLToPath } from 'url'; // ES 모듈에서 파일 경로를 얻기 위해 필요
import { bundleID, apnKey, apnKeyID, apnTeamID } from '../private/config.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// APNs 옵션 설정
const options = {
token: {
// key: `../private/${apnKey}`, // 다운로드한 .p8 파일 경로
key: path.join(__dirname, '../private', apnKey), // 절대 경로로 변경
keyId: apnKeyID, // Apple Developer Console에서 얻은 키 ID
teamId: apnTeamID, // Apple Developer Console에서 얻은 팀 ID
},
production: false, // 프로덕션(실제 배포 환경)인 경우 true로 설정
};
const apnProvider = new apn.Provider(options);
export function HandlePush(req, res) { export function HandlePush(req, res) {
// 쿼리 파라미터에서 값 추출 const { fcmToken, title, body, parameter, sound, badge } = req.body;
const { id: deviceToken, title, body, parameter, sound = "default", badge = 0 } = req.query;
if (!deviceToken || !title || !body) { if (!fcmToken || !title || !body) {
res.status(400).json({ error: 'deviceToken, title, and body are required' }); res.status(400).json({ error: 'fcmToken, title, body, and parameter are required' });
return; return;
} }
const notification = new apn.Notification(); const message = {
notification.topic = bundleID; token: fcmToken,
notification.expiry = Math.floor(Date.now() / 1000) + 3600; notification: {
notification.badge = Number(badge); title: title,
notification.sound = sound; body: body,
notification.alert = { title, body }; },
notification.payload = { parameter }; apns: {
payload: {
aps: {
alert: {
title: title,
body: body,
parameter: parameter,
},
sound: sound || 'default',
badge: badge ? Number(badge) : 0,
},
},
},
};
apnProvider.send(notification, deviceToken).then((response) => {
if (response.sent.length > 0) { // const jjApp = admin.app('jjungtable');
console.log('Successfully sent message:', response.sent);
admin.app('jjungtable').messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
res.status(200).json({ message: 'Successfully sent message' }); res.status(200).json({ message: 'Successfully sent message' });
} else { })
console.error('Failed to send message:', response.failed); .catch((error) => {
res.status(500).json({ error: 'Failed to send message', details: response.failed }); console.error('Error sending message:', error);
} res.status(500).json({ error: `Error sending message: ${error.message}` });
}).catch((error) => { });
console.error('Error sending message:', error);
res.status(500).json({ error: `Error sending message: ${error.message}` });
}).finally(() => {
apnProvider.shutdown();
});
} }

View File

@ -1,58 +0,0 @@
import express from 'express';
import { createDatabaseConnection } from '../db/database.js'; // db 연결 파일을 import
import { dbConfig } from '../private/config.js';
export const HandleUser = async (req, res) => {
const actionPath = req.params[0]; // 'userRead/sns'와 같은 나머지 경로를 잡아냄
const actionParts = actionPath.split('/'); // 슬래시로 나누어 배열로 변환
const action = actionParts[0]; // 첫 번째 부분 ('userRead')
if (action === 'userRead') {
// res.send(`Action: ${action}, ${actionParts}`); // 이 줄은 테스트용이므로 실제 응답 전에 사용 금지
let query;
let queryParams;
try {
const connection = await createDatabaseConnection(dbConfig);
if (actionParts[1] === 'sns') {
const { sns_id } = req.query; // 쿼리 파라미터에서 sns_id를 받아옴
if (!sns_id) {
await connection.end();
return res.status(400).json({ error: 'sns_id is required' });
}
query = 'SELECT * FROM user_info WHERE sns_id = ?';
queryParams = [sns_id];
}
else if (actionParts[1] === 'app') {
const { app_id } = req.query;
if (!app_id) {
await connection.end();
return res.status(400).json({ error: 'app_id is required' });
}
query = 'SELECT * FROM user_info WHERE app_id = ?';
queryParams = [app_id];
}
else {
await connection.end();
return res.status(400).json({ error: 'Invalid sub-action' });
}
const [rows] = await connection.query(query, queryParams);
await connection.end();
if (rows.length === 0) {
return res.status(404).json({ message: 'User not found' });
}
return res.json(rows); // 사용자의 첫 번째 정보를 반환
} catch (err) {
return res.status(500).json({ error: err.message });
}
} else {
return res.status(400).send('Invalid action');
}
};

View File

@ -2,16 +2,13 @@
import express from 'express'; import express from 'express';
import bodyParser from 'body-parser'; import bodyParser from 'body-parser';
// import swaggerJSDoc from 'swagger-jsdoc'; import swaggerJSDoc from 'swagger-jsdoc';
// import swaggerUi from 'swagger-ui-express'; import swaggerUi from 'swagger-ui-express';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import cookieParser from 'cookie-parser'; import cookieParser from 'cookie-parser';
import cors from 'cors'; import cors from 'cors';
import session from 'express-session'; // express-session 추가
import routes from './apps/app.js'; // ./apps/app.js에서 라우트를 가져옴
import { serverURL, serverPort } from './private/config.js'; import { serverURL, serverPort } from './private/config.js';
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
@ -22,34 +19,38 @@ console.log(process.cwd());
const app = express(); const app = express();
app.use(cors()); app.use(cors());
app.use(bodyParser.json()); // For parsing application/json app.use(bodyParser.json()); // For parsing application/json
app.use(cookieParser()); // For parsing cookies app.use(cookieParser()); // For parsing cookies
app.use(express.static(path.join(__dirname, 'Front'))); // Serve static files from Pront directory app.use(express.static(path.join(__dirname, 'Front'))); // Serve static files from Pront directory
// Swagger setup // Swagger setup
// const swaggerDefinition = { const swaggerDefinition = {
// openapi: '3.0.0', openapi: '3.0.0',
// info: { info: {
// title: 'My API', title: 'My API',
// version: '1.0.0', version: '1.0.0',
// description: 'API documentation', description: 'API documentation',
// }, },
// servers: [ servers: [
// { {
// url: serverURL, url: serverURL,
// description: 'JJ server', description: 'JJ server',
// }, },
// ], ],
// }; };
// const options = {
// swaggerDefinition,
// apis: ['./back/apps/app.js'],
// };
// const swaggerSpec = swaggerJSDoc(options); const options = {
swaggerDefinition,
apis: ['./back/apps/push.js'],
};
// app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); const swaggerSpec = swaggerJSDoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.use((req, res, next) => { app.use((req, res, next) => {
const host = req.headers.host; const host = req.headers.host;
@ -57,20 +58,16 @@ app.use((req, res, next) => {
next(); next();
}); });
app.use('/', routes);
app.listen(serverPort, () => {
console.log(`Server running`);
});
// Start the server // Start the server
//JJUNGTABLE 서버 연결 //JJUNGTABLE 서버 연결
// const jjungTable_server = express(); const jjungTable_server = express();
// jjungTable_server.use(jjungTableApp); jjungTable_server.use(jjungTableApp);
// jjungTable_server.listen(serverPort, () => { jjungTable_server.listen(serverPort, () => {
// console.log(`Server running`); console.log(`Server running`);
// }); });
// const sManagement_server = express(); // const sManagement_server = express();
// sManagement_server.use(sManagementApp); // sManagement_server.use(sManagementApp);

View File

@ -13,11 +13,6 @@
"author": "Team.Stein", "author": "Team.Stein",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"express": "^4.19.2", "express": "^4.19.2"
"mysql2": "^3.11.0",
"cookie-parser": "^1.4.6",
"body-parser": "^1.19.2",
"express-session": "^1.17.3",
"cors": "^2.8.5"
} }
} }