diff --git a/index.js b/index.js index f5614c3..88e6828 100644 --- a/index.js +++ b/index.js @@ -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 + + } +}