diff --git a/apps/app.js b/apps/app.js new file mode 100644 index 0000000..ed8bb19 --- /dev/null +++ b/apps/app.js @@ -0,0 +1,228 @@ +import express, { query } from 'express'; +import { createDatabaseConnection } from '../db/database.js'; // db 연결 파일 +import { HandlePush } from './push.js'; + +const cmcd = "/JJ"; +const db = "/JJ/db"; + +const app = express(); +app.use(express.json()); + +const dbConfig = { + host: 'ipStein.myDS.me', + user: 'root', + password: 'JJrootPW', + database: 'dev', + port: 8002 +}; + +/* + // query 클래스 묶음 + let query; + query = await getQueryModule('update', 'Update'); + if (!query) { return res.status(400).json({ error: 'Invalid parameter' }); } +*/ + + +const getQueryModule = async (type, className) => { + if (type === 'create') { + const module = await import('../../db/queries/create_query.js'); + return module[className]; + } + else if (type === 'read') { + const module = await import('../../db/queries/read_query.js'); + return module[className]; + } + else if (type === 'update') { + const module = await import('../../db/queries/update_query.js'); + return module[className]; + } + else if (type === 'delete') { + const module = await import('../../db/queries/update_query.js'); + return module[className]; + } + else if (type === 'function') { + const module = await import('../../db/queries/functions_query.js'); + return module[className]; + } + return '' +}; + +app.get(`${cmcd}/push`, async (req, res) => { + // HandlePush(req, res); + //3138117983JJ20240611 + // const { cid, title, body, cd } = req.query; + const { cid, title, body, badge, parameter } = req.query; + + + if (!cid || !title || !body) { + return res.status(400).json({ error: 'All parameters (cid, title, body) are required' }); + } + + let query; + query = await getQueryModule('function', 'Push'); + if (!query) { return res.status(400).json({ error: 'Invalid parameter' }); } + + try { + const connection = await createDatabaseConnection({ ...dbConfig, database: 'jjungtable_db'}); + const [rows] = await connection.query(query.loadFCM_token, [cid]); + await connection.end(); + + if (rows.length === 0) { + return res.status(404).json({ error: 'No fcm_token found for the provided cid' }); + } + + const fcmToken = rows[0].fcm_token; + console.log(fcmToken); + // HandlePush 호출 시 필요한 req.body에 fcmToken, title, body 설정 + req.body = { fcmToken, title, body, badge, parameter }; + HandlePush(req, res); + + } catch (err) { + console.error(err); + res.status(500).json({ error: 'Internal server error' }); + } +}); + + +// DB 연결 테스트 +app.get(`${db}/test`, async (req, res) => { + try { + const connection = await createDatabaseConnection(dbConfig); + const [rows] = await connection.query('SELECT 1 + 1 AS solution'); + await connection.end(); + res.json({ result: rows[0].solution }); + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + + +/////////////////////////////////////////////////////////////// +// GET +/////////////////////////////////////////////////////////////// +app.get(`${db}/version/read`, async (req, res) => { + const { os_type } = req.query; + if (!os_type) { return res.status(400).json({ error: 'ostype parameter is required' }) } + + let query; + query = await getQueryModule('read', 'Read'); + if (!query) { return res.status(400).json({ error: 'Invalid parameter' }); } + + try { + const connection = await createDatabaseConnection({ ...dbConfig, database: 'jjungtable_db' }); + const [rows] = await connection.query(query.version, [os_type]); + await connection.end(); + + if (rows.length === 0) { + return res.status(404).json({ error: 'No data found' }); + } + + res.json(rows); + } catch (err) { + console.error(err); + res.status(500).json({ error: 'Internal server error' }); + } +}); + +app.get(`${db}/userInfo/read`, async (req, res) => { + const { id, type } = req.query; + if (!id || !type) { return res.status(400).json({ error: 'ostype parameter is required' }) } + + let query; + query = await getQueryModule('read', 'Read'); + if (!query) { return res.status(400).json({ error: 'Invalid parameter' }); } + + try { + const connection = await createDatabaseConnection({ ...dbConfig, database: 'jjungtable_db' }); + const [rows] = await connection.query(query.login_code, [id, type]); + await connection.end(); + + if (rows.length === 0) { + return res.status(404).json({ error: 'No data found' }); + } + + res.json(rows); + } catch (err) { + console.error(err); + res.status(500).json({ error: 'Internal server error' }); + } +}); + +/////////////////////////////////////////////////////////////// +// POST +/////////////////////////////////////////////////////////////// + +async function insertLog(table, connection, query, body) { + if (table === 'version') { + const { date, managerId, os_type, final_ver, force_ver, update_ver, update_choice, log } = body; + await connection.query( query, [date, managerId, os_type, final_ver, force_ver, update_ver, update_choice, log] ); + } +} +app.post(`${db}/version/update`, async (req, res) => { + const { date, managerId, os_type, final_ver, force_ver, update_ver, update_choice, log } = req.body; + try { + const connection = await createDatabaseConnection({ ...dbConfig}); + let query; + + // 버전 정보 업데이트 + query = await getQueryModule('update', 'Update'); + if (!query) { return res.status(400).json({ error: 'Invalid parameter' }); } + await connection.query( query.version,[final_ver, force_ver, update_ver, update_choice, os_type]); + + // 로그 생성 + query = await getQueryModule('create', 'Log'); + if (!query) { return res.status(400).json({ error: 'Invalid parameter' }); } + await insertLog('version', connection, query.version_Log, req.body); + + await connection.end(); + res.json({ message: 'Update successful' }); + + } catch (err) { + res.status(500).json({ error: err.message }); + } +}); + + + + +/////////////////////////////////////////////////////////////// +// LOG 관련 + +// DB Log 읽어들이기 +app.get(`${db}/log/read`, async (req, res) => { + console.log('[JJ]Log: Version'); + const { param } = req.query; + + try { + const connection = await createDatabaseConnection({ ...dbConfig }); + let query, rows; + // let rows; + + if (param === 'version') { + query = await getQueryModule('read', 'Log'); + if (!query) { return res.status(400).json({ error: 'Invalid parameter' }); } + [rows] = await connection.query(query.version_Log); + } + + await connection.end(); + res.json(rows); + } catch (err) { + console.error(err); + res.status(500).json({ error: 'Internal server error' }); + } +}); + + + + + + + + + + + + + +export default app; \ No newline at end of file diff --git a/apps/push.js b/apps/push.js new file mode 100644 index 0000000..4d35511 --- /dev/null +++ b/apps/push.js @@ -0,0 +1,45 @@ +import { admin } from '../firebaseConfig.js'; + +export function HandlePush(req, res) { + const { fcmToken, title, body, parameter, sound, badge } = req.body; + + if (!fcmToken || !title || !body) { + res.status(400).json({ error: 'fcmToken, title, body, and parameter are required' }); + return; + } + + const message = { + token: fcmToken, + notification: { + title: title, + body: body, + }, + apns: { + payload: { + aps: { + alert: { + title: title, + body: body, + parameter: parameter, + }, + sound: sound || 'default', + badge: badge ? Number(badge) : 0, + }, + }, + }, + }; + + + // const jjApp = admin.app('jjungtable'); + + admin.app('jjungtable').messaging().send(message) + .then((response) => { + console.log('Successfully sent message:', response); + res.status(200).json({ message: 'Successfully sent message' }); + }) + .catch((error) => { + console.error('Error sending message:', error); + res.status(500).json({ error: `Error sending message: ${error.message}` }); + }); +} + diff --git a/db/database.js b/db/database.js new file mode 100644 index 0000000..abae567 --- /dev/null +++ b/db/database.js @@ -0,0 +1,16 @@ + +import mysql from 'mysql2/promise'; + +// 데이터베이스 연결 설정 함수 +export const createDatabaseConnection = (config) => { + return mysql.createConnection({ + host: config.host, + user: config.user, + password: config.password, + database: config.database, + port: config.port, + waitForConnections: true, + connectionLimit: 10, + queueLimit: 0 + }); +}; \ No newline at end of file diff --git a/firebaseConfig.js b/firebaseConfig.js new file mode 100644 index 0000000..3e5d7b6 --- /dev/null +++ b/firebaseConfig.js @@ -0,0 +1,59 @@ +import { initializeApp as initializeClientApp, getApps, getApp } from 'firebase/app'; +import admin from 'firebase-admin'; +import jjungtable_AccKey from './private/jjungtable-AccountKey.json' assert { type: 'json' }; + +// 첫 번째 파이어베이스 초기화 (관리자) +// if (!admin.apps.find(app => app.name === 'sManager')) { +// admin.initializeApp({ +// credential: admin.credential.cert(sManager_AccKey), +// databaseURL: "https://checkanything-18bf9.firebaseio.com" +// }, 'sManager'); +// } + +// 파이어베이스 초기화 +if (!admin.apps.find(app => app.name === 'jjungtable')) { + admin.initializeApp({ + credential: admin.credential.cert(jjungtable_AccKey), + databaseURL: "https://jjungtable-e5087-default-rtdb.firebaseio.com" + }, 'jjungtable'); +} + +// export const sm_firebaseConfig = { +// apiKey: "AIzaSyCxLVOqbrnlDwfx6WMbmTGtCGrUNoL-CqI", +// authDomain: "checkanything-18bf9.firebaseapp.com", +// projectId: "checkanything-18bf9", +// storageBucket: "checkanything-18bf9.appspot.com", +// messagingSenderId: "928156583361", +// appId: "1:928156583361:web:d157abe34e637fb2395b40", +// measurementId: "G-NBSP3XCXX7" +// }; + +export const jj_firebaseConfig = { + apiKey: "AIzaSyCHJI2u1lbmHYgKRvPSO9-mPOGENBBPnsg", + authDomain: "jjungtable-e5087.firebaseapp.com", + databaseURL: "https://jjungtable-e5087-default-rtdb.firebaseio.com", + projectId: "jjungtable-e5087", + storageBucket: "jjungtable-e5087.appspot.com", + messagingSenderId: "480609810019", + appId: "1:480609810019:web:b66f72216fa17e1b462a56", + measurementId: "G-BQP2SDL40C" +}; + +// 클라이언트 앱 초기화 (이미 초기화된 경우 확인) +// let sm_ClientApp; +// if (!getApps().some(app => app.name === 'sManagerClientApp')) { +// sm_ClientApp = initializeClientApp(sm_firebaseConfig, 'sManagerClientApp'); +// } else { +// sm_ClientApp = getApp('sManagerClientApp'); +// } + +let jj_ClientApp; +if (!getApps().some(app => app.name === 'jjungtableClientApp')) { + jj_ClientApp = initializeClientApp(jj_firebaseConfig, 'jjungtableClientApp'); +} else { + jj_ClientApp = getApp('jjungtableClientApp'); +} + +// export { admin, sm_ClientApp, jj_ClientApp }; + +export { admin, jj_ClientApp }; diff --git a/index.js b/index.js index e715334..ac16455 100755 --- a/index.js +++ b/index.js @@ -1,15 +1,72 @@ -// index.js - +// npm install express body-parser swagger-jsdoc swagger-ui-express cookie-parser cors import express from 'express'; +import bodyParser from 'body-parser'; +import swaggerJSDoc from 'swagger-jsdoc'; +import swaggerUi from 'swagger-ui-express'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import cookieParser from 'cookie-parser'; +import cors from 'cors'; + +// import jjungTableApp from './back/apps/jjungTable_index.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +console.log(__dirname); +console.log(process.cwd()); const app = express(); -const port = 7002; -app.get('/', (req, res) => { - res.send('Hello World!123123123123'); - +app.use(cors()); +app.use(bodyParser.json()); // For parsing application/json +app.use(cookieParser()); // For parsing cookies +app.use(express.static(path.join(__dirname, 'Front'))); // Serve static files from Pront directory + +// Swagger setup +const swaggerDefinition = { + openapi: '3.0.0', + info: { + title: 'My API', + version: '1.0.0', + description: 'API documentation', + }, + servers: [ + { + url: `http://localhost:7002`, + description: 'Local server', + }, + ], +}; + +const options = { + swaggerDefinition, + apis: ['./back/apps/push.js'], +}; + +const swaggerSpec = swaggerJSDoc(options); + +app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); + +app.use((req, res, next) => { + const host = req.headers.host; + console.log(`Client connected to host: ${host}`); + next(); }); -app.listen(port, () => { - console.log(`Server is running at http://localhost:${port}`); -}); \ No newline at end of file + + +// Start the server + +//JJUNGTABLE 서버 연결 +const jjungTable_server = express(); +jjungTable_server.use(jjungTableApp); +jjungTable_server.listen(7002, () => { + console.log(`Server running at http://localhost:7002/`); +}); + +// const sManagement_server = express(); +// sManagement_server.use(sManagementApp); +// sManagement_server.listen(6004, () => { +// console.log(`Server running at https://localhost:6004/`); +// }); \ No newline at end of file