summaryrefslogtreecommitdiff
path: root/server.mjs
blob: b958049dcebba3161eb02171eac98cfea81d4a89 (plain)
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
'use strict'

import { DatabaseSync } from 'node:sqlite'
import { createServer } from 'node:http'

const database = new DatabaseSync(':memory:')

database.exec(`
  CREATE TABLE eagles(
    id INTEGER PRIMARY KEY,
    mac_address TEXT,
    key TEXT
  ) STRICT
`)

const server = createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' })
    res.end('It works!\n')
  } else if (req.method === 'GET' && req.url === '/gettime') {
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({ time: Math.floor(Date.now() / 1000) }))
  } else if (req.method === 'GET' && req.url.startsWith('/eagle')) {
    const params = new URLSearchParams(req.url.substring('/eagle'.length))
    const mac = params.get('mac')
    const key = params.get('key')
    if (mac === null || key === null) {
      res.writeHead(400, { 'Content-Type': 'application/json' })
      res.end('{}\n')
      return
    }
    const insert = database.prepare('INSERT INTO eagles(mac_address, key) VALUES(?, ?)')
    const record = insert.run(mac, key)
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({ status: 200, data: { eagleId: record.lastInsertRowid } }))
  } else if (req.method === 'GET' && req.url.startsWith('/exchange')) {
    const params = new URLSearchParams(req.url.substring('/exchange'.length))
    const device = params.get('device')
    if (device === null) {
      res.writeHead(422)
      res.end()
      return
    }
    const query = database.prepare('SELECT * FROM eagles WHERE id = ?').get(device)
    if (query === undefined) {
      res.writeHead(404)
      res.end()
      return
    }
    res.writeHead(200)
    res.end(JSON.stringify({ key: query.key }))
  } else {
    res.writeHead(404)
    res.end()
  }
})

const hostname = process.env.HOSTNAME || '0.0.0.0'
const port = process.env.PORT || 80

server.listen(port, hostname, () => {
  console.log(`Listening on ${hostname}:${port}`)
})