aboutsummaryrefslogtreecommitdiff
path: root/index.js
blob: 34d4e2cf7fa0f6140e1c36f21132367e35c55fd8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict'

const fs = require('fs')
const config = require('config-yml')
const express = require('express')
const compression = require('compression')

const db = require('./db')
const themify = require('./utils/themify')

const PLACES = 7

const app = express()

app.use(express.static('assets'))
app.use(compression())
app.set('view engine', 'pug')

app.get('/', (req, res) => {
  res.render('index')
});

const getCountByName = async name=> {
  if (name === 'demo') return '0123456789'
  // console.log(name)
  try {
    const counter = await db.getNum(name) || { name, num: 0 }
    const r = counter.num + 1
    db.setNum(counter.name, r)
    return r
  } catch (error) {
    console.log("get count by name is error: ", error)
    const errorDefaultCount = 0
    return  errorDefaultCount
  }
}

// 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

  // This helps with GitHub's image cache 
  res.set({
    'content-type': 'image/svg+xml',
    'cache-control': 'max-age=0, no-cache, no-store, must-revalidate'
  })

  count = await getCountByName(name)

  if (name === 'demo') {
    res.set({
      'cache-control': 'max-age=31536000'
    })
    length = 10
  }

  // Send the generated SVG as the result
  const renderSvg = themify.getCountImage({ count, theme, length })
  res.send(renderSvg)
})

app.get('/heart-beat', (req, res) => {
  res.set({
    'cache-control': 'max-age=0, no-cache, no-store, must-revalidate'
  })

  res.send('alive')
  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, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})