aboutsummaryrefslogtreecommitdiff
path: root/index.js
blob: 7f20e1d88d8ab58032badefc78c9c14db4ef81cd (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
'use strict'

const fs = require('fs')
const express = require('express')
const compression = require('compression')

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

const PLACES = 7

function getCountImage({ count, theme='konachan', PLACES=PLACES }) {
  // This is not the greatest way for generating an SVG but it'll do for now
  const countArray = count.toString().padStart(PLACES, '0').split('')

  const parts = countArray.reduce((acc, next, index) => `
        ${acc}
        <image x="${index * 45}" y="0" width="45px" height="100px" xlink:href="${themify.wrap(next, theme)}" />
`, '')

  return `<?xml version="1.0" encoding="UTF-8"?>
<svg width="${PLACES * 45}" height="100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <title>Kawaii Count</title>
    <g>
      ${parts}
    </g>
</svg>
`
}


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

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

// get the image
app.get('/get/@:name', async (req, res) => {
  const name = req.params.name
  const theme = req.query.theme || 'konachan'
  let length = PLACES, num = 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'
  })

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

  } else {
    const counter = await db.getNum(name)
    num = counter.num + 1

    db.setNum(counter.name, num)
    console.log(counter, `theme: ${theme}`)
  }

  // Send the generated SVG as the result
  res.send(getCountImage({ count: num, theme, PLACES: length }))
})

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')
});

const listener = app.listen(process.env.PORT, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})