1
0
mirror of https://github.com/journey-ad/Moe-Counter.git synced 2024-11-27 17:00:51 +01:00

Update index.js

修改了一些写法和逻辑
没必要处理所有的异常,比如配置文件出错这类启动时就能发现的
This commit is contained in:
Jad 2020-08-22 21:20:20 +08:00 committed by GitHub
parent 56c4a37f6d
commit 398f0ff6ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -20,41 +20,11 @@ app.get('/', (req, res) => {
res.render('index')
});
const getCountByName = async name=> {
// console.log(name)
if (name === 'demo') return { num: '0123456789', name }
try {
const counter = await db.getNum(name) || { name, num: 0 }
const r = counter.num + 1
db.setNum(counter.name, r)
return counter
} catch (error) {
console.log("get count by name is error: ", error)
const errorDefaultCount = 0
return errorDefaultCount
}
}
// the rest api get data
// link: https://www.liaoxuefeng.com/wiki/1022910821149312/1105009634703392
app.get('/rest/@:name', async (req, res) => {
const name = req.params.name
try {
const data = await getCountByName(name)
res.send(data)
} catch (error) {
res.send({
num: 0,
name
})
}
})
// get the image
app.get('/get/@:name', async (req, res) => {
const name = req.params.name
const theme = req.query.theme || 'moebooru'
let length = PLACES, count = 0
const { name } = req.params
const { theme = 'moebooru' } = req.query
let length = PLACES
// This helps with GitHub's image cache
res.set({
@ -63,7 +33,6 @@ app.get('/get/@:name', async (req, res) => {
})
const data = await getCountByName(name)
count = data.num
if (name === 'demo') {
res.set({
@ -73,8 +42,19 @@ app.get('/get/@:name', async (req, res) => {
}
// Send the generated SVG as the result
const renderSvg = themify.getCountImage({ count, theme, length })
const renderSvg = themify.getCountImage({ count: data.num, theme, length })
res.send(renderSvg)
console.log(data, `theme: ${theme}`)
})
// JSON record
app.get('/record/@:name', async (req, res) => {
const { name } = req.params
const data = await getCountByName(name)
res.json(data)
})
app.get('/heart-beat', (req, res) => {
@ -86,17 +66,24 @@ app.get('/heart-beat', (req, res) => {
console.log('heart-beat')
});
let port = 3000
try {
let configPort = config.app.port
if (configPort) {
port = configPort
}
} catch (error) {
throw new Error(error)
}
const listener = app.listen(port, () => {
const listener = app.listen(config.app.port || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
async function getCountByName(name) {
const defaultCount = { name, num: 0 }
if (name === 'demo') return { name, num: '0123456789' }
try {
const counter = await db.getNum(name) || defaultCount
const num = counter.num + 1
db.setNum(counter.name, num)
return counter
} catch (error) {
console.log("get count by name is error: ", error)
return defaultCount
}
}