-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #7 from ALPHACamp/refactor/modularize_apiServer
Refactor/modularize api server
- Loading branch information
Showing
19 changed files
with
633 additions
and
125 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
const app = require('./express'); | ||
const http = require('http'); | ||
|
||
const logger = require('../lib/logger.js'); | ||
|
||
class ApiServer { | ||
constructor(port) { | ||
logger.info('Configure API Server ...', { port, node_env: process.env.NODE_ENV }); | ||
|
||
this.port = port; | ||
this.httpServer = null; | ||
this.db = null; | ||
|
||
this.#createServer(); | ||
this.#bindEvents(); | ||
} | ||
|
||
#createServer() { | ||
this.httpServer = http.createServer(app); | ||
} | ||
|
||
#bindEvents() { | ||
logger.info('Binding Events ...'); | ||
this.httpServer.on('listening', () => { | ||
logger.info(`Server started on port: ${this.port} for NODE_ENV:${process.env.NODE_ENV}`); | ||
}); | ||
this.httpServer.on('error', (err) => { | ||
logger.error('Server error:', err); | ||
}); | ||
} | ||
|
||
start() { | ||
this.httpServer.listen(this.port); | ||
} | ||
} | ||
|
||
module.exports = ApiServer; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
const express = require('express'); | ||
require('express-async-errors'); // for catching async error | ||
const cors = require('cors'); | ||
const router = require('./routes/index.js'); | ||
const errorHandler = require('./middlewares/errorHandler.js'); | ||
const resMethod = require('./middlewares/resMethod.js'); | ||
const reqInitializer = require('./middlewares/reqInitializer.js'); | ||
|
||
const app = express(); | ||
|
||
app.use(cors({ | ||
exposedHeaders: ['X-Request-Id'], | ||
})); | ||
|
||
|
||
app.use(reqInitializer); | ||
app.use(resMethod); | ||
app.use('/api', router); | ||
|
||
app.use(errorHandler); | ||
|
||
// 404 handler | ||
app.use('*', (req, res) => res.status(404).send({ | ||
success: false, | ||
message: '指定路徑並不存在', | ||
error: { | ||
code: 404, | ||
type: 'RouteNotFound', | ||
debugInfo: {}, | ||
}, | ||
})); | ||
|
||
module.exports = app; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
const logger = require('../../lib/logger.js'); | ||
const Errors = require('../../lib/Errors.js'); | ||
|
||
/** | ||
* @type {import('express').ErrorRequestHandler} | ||
*/ | ||
module.exports = function errorHandler(err, req, res, next) { | ||
const errorMessage = err.msg || err.message; | ||
const data = {}; | ||
if (process.env.NODE_ENV === 'dev') { | ||
data.stack = err.stack; | ||
console.log(err); | ||
} | ||
|
||
logger.info(`General error handler for error: ${errorMessage}`, data); | ||
if (res.headersSent) { | ||
return next(err); | ||
} else if (err instanceof Errors.GeneralError) { | ||
return res.fail(err); | ||
} | ||
|
||
// 當錯誤並非預定義時 | ||
logger.error({ msg: 'Exception', errMsg: err.message, errName: err.name }); | ||
res.status(501); | ||
return res.send(err.message); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
const { v4: uuidv4 } = require('uuid'); | ||
const logger = require('../../lib/logger'); | ||
|
||
/** | ||
* @type {import('express').Handler} | ||
*/ | ||
module.exports = function reqInitializer(req, res, next) { | ||
const start = process.hrtime.bigint(); | ||
req.requestId = uuidv4(); | ||
|
||
const { method, query = {}, body = {}, requestId, originalUrl } = req; | ||
logger.debug({ msg: `${method} ${originalUrl} [STARTED]`, requestId, query, body }); | ||
|
||
res.on('finish', () => { | ||
const durationInMilliseconds = getDurationInMilliseconds(start); | ||
logger.info({ msg: `${method} ${originalUrl} [FINISHED] ${durationInMilliseconds.toLocaleString()} ms`, requestId }); | ||
}); | ||
|
||
res.on('close', () => { | ||
const durationInMilliseconds = getDurationInMilliseconds(start); | ||
logger.info({ msg: `${method} ${originalUrl} [CLOSED] ${durationInMilliseconds.toLocaleString()} ms`, requestId }); | ||
}); | ||
|
||
res.setHeader('X-Request-Id', req.requestId); | ||
next(); | ||
}; | ||
|
||
function getDurationInMilliseconds(start) { | ||
const diff = process.hrtime.bigint() - start; | ||
return Number(diff) / 1000000; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* @type {import('express').Handler} | ||
*/ | ||
module.exports = function resMethod(req, res, next) { | ||
res.success = function success({ data, ...info }) { | ||
res.status(200).send({ | ||
success: true, | ||
data, | ||
...info, | ||
}); | ||
}; | ||
|
||
/** | ||
* @param {Error} error | ||
*/ | ||
res.fail = function fail(error) { | ||
res.status(error.code).send({ | ||
success: false, | ||
message: error.message, | ||
error: { | ||
code: error.code, | ||
type: error.name, | ||
debugInfo: error.data, | ||
} | ||
}); | ||
}; | ||
|
||
next(); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
const express = require('express'); | ||
const router = express.Router(); | ||
|
||
router.use('/leaderboard', require('./leaderboard.js')); | ||
router.get('/healthCheck', (req, res) => { | ||
return res.success({ data: 'ok' }); | ||
}); | ||
|
||
|
||
module.exports = router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
const express = require('express'); | ||
const router = express.Router(); | ||
const Discord = require('discord.js'); | ||
|
||
const { db } = require('../../config/db'); | ||
const { pageSize } = require('../../const.js'); | ||
|
||
function validate(req, res, next) { | ||
const { date, discordId, page } = req.query; | ||
if (page && typeof Number(page) && Number(page) <= 0) { | ||
return res.status(400).json('page must be valid number'); | ||
} | ||
|
||
const dateRegex = /([12]\d{3}-(0[1-9]|1[0-2]))/; | ||
if (date && !dateRegex.test(date)) { | ||
return res.status(400).json('date must be in YYYY-MM format'); | ||
} | ||
|
||
if (discordId && typeof discordId !== 'string') { | ||
return res.status(400).json('discordId must be string'); | ||
} | ||
|
||
next(); | ||
} | ||
|
||
|
||
|
||
router.get('/', validate, async function (req, res) { | ||
const currentYearAndMonth = new Date().toISOString().slice(0, 7); | ||
const { date, discordId, page = 1 } = req.query; | ||
let ref = db | ||
.collection(`leaderboard-${currentYearAndMonth}`) | ||
.where('period', '=', date || currentYearAndMonth); | ||
|
||
const countSnapshot = await ref.count().get(); | ||
const totalDocsCount = countSnapshot.data().count; | ||
const totalPages = Math.ceil(totalDocsCount / 10); | ||
const offset = (page - 1) * pageSize; | ||
|
||
if (discordId) { | ||
ref = ref.where('discordId', '=', discordId); | ||
} | ||
|
||
const querySnapshot = await ref | ||
.orderBy('point', 'desc') | ||
.limit(pageSize) | ||
.offset(offset) | ||
.get(); | ||
|
||
const client = new Discord.Client({ | ||
intents: [] | ||
}); | ||
client.login(process.env.DISCORD_TOKEN); | ||
|
||
const fetchUserDetails = async (doc) => { | ||
const data = doc.data(); | ||
const guild = await client.guilds.fetch(process.env.DISCORD_GUILDID); | ||
const member = await guild.members.fetch(data.discordId); | ||
|
||
return { | ||
id: doc.id, | ||
name: member.nickname || member.user.username, | ||
avatarURL: member.user.displayAvatarURL(), | ||
...data | ||
}; | ||
}; | ||
|
||
const promises = querySnapshot.docs.map(fetchUserDetails); | ||
const results = await Promise.all(promises); | ||
|
||
return res.success({ | ||
data: results, | ||
offset, | ||
pageSize, | ||
totalPages, | ||
currentPage: page, | ||
totalDataCount: totalDocsCount | ||
}); | ||
}); | ||
|
||
module.exports = router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.