summaryrefslogtreecommitdiffstats
path: root/finished-application/backend/src/resolvers/Query.js
blob: a51ead5ea4d97034aaafe725633be3458e3f3197 (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
const { hasPermission } = require('../utils');

const { forwardTo } = require('prisma-binding');

const Query = {
  items: forwardTo('db'),
  itemsConnection: forwardTo('db'),
  async users(parent, args, ctx, info) {
    if (!ctx.request.userId) {
      throw new Error('Insufficient Permissions');
    }

    return ctx.db.query.users({}, info);
  },

  async order(parent, args, ctx, info) {
    // 1. make sure they are signed in
    if (!ctx.request.userId) {
      throw new Error('You Must be signed in to view an order');
    }

    // 2. Create the query
    const where = {
      id: args.id,
      user: {
        id: ctx.request.userId,
      },
    };
    // 3. Fire off the query
    const [order] = await ctx.db.query.orders({ where }, info);

    // 4. Check that they are allowed to view the order
    if (order.user.id !== ctx.request.userId || hasPermission(ctx.request.user, ['ADMIN'])) {
      throw new Error("You don't have permission");
    }
    // 5. If everything checks out, return the order
    return order;
  },

  me(parent, args, ctx, info) {
    if (!ctx.request.userId) {
      return null; // don't error out, just return nothing
    }

    return ctx.db.query.user(
      {
        where: { id: ctx.request.userId },
      },
      info
    );
  },

  async orders(parent, args, ctx, info) {
    const { userId } = ctx.request;
    if (!userId) {
      throw new Error('You must be signed in to see your orders');
    }
    return ctx.db.query.orders(
      {
        where: {
          user: { id: userId },
        },
      },
      info
    );
  },
};

module.exports = Query;