summaryrefslogtreecommitdiff
path: root/server/src/operations.ts
blob: 7484b33afc36ea13cd84e2cf4d38307eef2c53d4 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { Context } from './context.model'
import { SubscriptionRequest } from '../../lib/subscription-req.model'
import { WriteRequest } from '../../lib/write-req.model'
import { DatabaseChange } from '../../lib/database-change.model'

import { decodePath } from '../../lib/path'

import { DatabaseInterface } from 'naive-core'

import express, { RequestHandler } from 'express'
import bodyParser from 'body-parser'

export const bindOperations = (
  ctx: Context,
  db: DatabaseInterface,
  send: (e: DatabaseChange) => Promise<any>
) => {
  // these methods should be tracked using a better
  // data structure
  const unsubs: { [key: string]: () => any } = {}

  const writeHandler: RequestHandler = async (req, res) => {
    const { path, toWrite } = req.body as WriteRequest
    await db.write(path, toWrite)
    res.status(200).end()
  }

  const readHandler: RequestHandler = async (req, res) => {
    const { path: encodedPath } = req.params as WriteRequest
    const path = decodePath(encodedPath)
    try {
      const payload = await db.read(path)
      res.json(payload)
    } catch (err) {
      res.status(500).end()
    }
  }

  const addSubHandler: RequestHandler = async (req, res) => {
    const { path } = req.body as SubscriptionRequest
    // only allow users to subscribe
    // to a given path once
    // TODO return a better error
    if (unsubs[path]) {
      res.status(500).end()
      return
    }
    unsubs[path] = db.subscribe(path, async (change: Object) => {
      await send({
        path,
        change
      })
    })
    res.status(200).end()
  }

  const removeSubHandler: RequestHandler = async (req, res) => {
    const { path } = req.body as SubscriptionRequest
    const unsub = unsubs[path]
    if (unsub) unsub()
  }

  const router = express()
  router.use(bodyParser.json())
  router.get('/read/:path', readHandler)
  router.post('/write', writeHandler)
  router
    .route('/subscribe')
    .post(addSubHandler)
    .delete(removeSubHandler)
  const instance = router.listen(ctx.httpPort, () =>
    ctx.logger('HTTPS server started')
  )

  return () =>
    new Promise((resolve, reject) => {
      instance.close(resolve)
    })
}