aboutsummaryrefslogtreecommitdiffstats
path: root/routes/items.ts
blob: df1d86ea6c6f493861a60d45a588af0d51889956 (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
87
88
import { g, s, db } from "$lib/db";
import { v4 } from "uuid";
import { bail, fail } from "$lib/utils";

export default {
  async list(req, res) {
    const {
      params: { id: uid },
    } = req;
    const items = [];
    for (const id of await db.lRange(`${uid}:items`, 0, -1)) {
      const item = await g(`item:${id}`);
      if (item) items.push(item);
      else await db.lRem(`${uid}:items`, 0, id);
    }

    res.send(items);
  },

  async get(req, res) {
    const {
      params: { id },
    } = req;
    try {
      const item = await g(`item:${id}`);
      if (!item) fail("Item not found");
      res.send(item);
    } catch (e) {
      bail(res, e.message);
    }
  },

  async create(req, res) {
    const {
      body: item,
      user: { id },
    } = req;
    try {
      if (!item.id) {
        item.id = v4();
        await db.lPush(`${id}:items`, item.id);
      }

      if (!parseFloat(item.price)) fail("Invalid price");
      item.name = item.name.replace(/[^a-zA-Z0-9 ]/g, "");

      await s(`item:${item.id}`, item);

      res.send(item);
    } catch (e) {
      bail(res, e.message);
    }
  },

  async del(req, res) {
    const {
      body: { item },
      user: { id },
    } = req;
    try {
      const n = await db.lRem(`${id}:items`, 0, item.id);
      if (n) db.del(`item:${item.id}`);
      else fail("item not found");

      res.send({});
    } catch (e) {
      bail(res, e.message);
    }
  },

  async sort(req, res) {
    const {
      body: { items },
      user: { id },
    } = req;
    try {
      await db.del(`${id}:items`);

      for (const item of items) {
        await db.rPush(`${id}:items`, item.id);
      }

      res.send({});
    } catch (e) {
      bail(res, e.message);
    }
  },
};