blob: 6802ee790dfcf8ed50c3d031703a7ca935d73843 (
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
|
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 { 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>
) => {
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 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.post("/write", writeHandler);
router
.route("/subscribe")
.post(addSubHandler)
.delete(removeSubHandler);
router.listen(ctx.httpPort, () => ctx.logger("HTTPS server started"));
};
|