/
subscription.js
107 lines (84 loc) · 2.87 KB
/
subscription.js
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* @fileoverview Subscription routes
*/
import express from 'express';
import httpStatus from 'http-status';
import {params as sanitizeParams} from '../middleware/sanitize';
/**
* Export the routes
* @param {object} repo - subscriptions repo
* @return {object} router
*/
export default (subscriptionRepo) => {
// express router
const router = express.Router();
// set variables in req object based on the subscription id in the
// url. the param() doesn't accept multiple route parameters, so some
// funky code is done to get around it.
router.param('subscriptionId', (req, res, next) => {
const load = () => {
const { subscriptionId } = req.sanitizedParams;
subscriptionRepo.load(subscriptionId).then(o => {
req.subscriptionObj = o;
subscriptionRepo.ofType(o.type).then(t => {
req.repo = t;
next();
});
}).catch(next);
};
sanitizeParams()(req, res, load);
});
router.route('/')
/** GET /api/subscriptions - list of subscriptions */
.get((req, res, next) => {
subscriptionRepo.list(req.sanitizedQuery).then(subscriptions => {
res.json(subscriptions);
}).catch(next);
})
/** POST /api/subscriptions - creates a subscription */
.post((req, res, next) => {
const data = req.sanitizedBody.subscription;
// not a valid subscription object sent
if (!data || typeof data !== 'object') {
res.status(httpStatus.UNPROCESSABLE_ENTITY).json({ message: 'No subscription data sent in this request.' });
}
else {
subscriptionRepo.ofType(data.type).then(repo => {
return repo.subscribe(data);
}).then(newSubscription => {
res.json(newSubscription);
}).catch(next);
}
});
router.route('/:subscriptionId')
// gets a subscription
.get((req, res, next) => {
res.json(req.subscriptionObj);
})
// unsubscribe
.delete((req, res, next) => {
req.repo.unsubscribe(req.subscriptionObj).then(() => {
res.json({ message: 'Subscription removed' });
}).catch(next);
});
// PATCH - confirm subscription
router.patch('/:subscriptionId/confirm', (req, res, next) => {
req.repo.markConfirmed(req.subscriptionObj).then(updatedObj => {
res.json(updatedObj);
}).catch(next);
});
// PATCH - manage components
router.patch('/:subscriptionId/manage_components', (req, res, next) => {
const { components } = req.sanitizedBody;
req.repo.manageComponents(req.subscriptionObj, components).then(updatedObj => {
res.json(updatedObj);
}).catch(next);
});
// GET - send confirmation link
router.get('/:subscriptionId/send_confirmation_link', (req, res, next) => {
req.repo.sendConfirmationLink(req.subscriptionObj).then(() => {
res.json({ message: 'Confirmation link sent.'});
}).catch(next);
});
return router;
};