-
Notifications
You must be signed in to change notification settings - Fork 8
/
router.js
115 lines (100 loc) · 2.68 KB
/
router.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
108
109
110
111
112
113
114
115
'use strict';
const router = require('koa-router')();
const UsersController = require('./controllers/usersController');
const EventsController = require('./controllers/eventsController');
const RatingsController = require('./controllers/ratingsController');
// MongoDb configure
const monk = require('monk');
const db = monk(process.env.MONGOLAB_URI);
// Creating Db instances
const Events = db.get('events');
const Users = db.get('users');
const Ratings = db.get('ratings');
// Geo Indexing for MongoDb
Events.createIndex({ location: '2dsphere' });
const eventsController = new EventsController(Events);
const ratingsController = new RatingsController(Ratings, Users);
// monk here is mandatory!
const usersController = new UsersController(Users, Events, monk, Ratings);
const authorize = async (ctx, next) => {
if (!ctx.user) {
ctx.status = 401;
return;
}
await next();
};
const routes = function (app) {
router
// Authorization
.post('/api/v1/auth', usersController.auth.bind(usersController))
// Get users info
.get(
'/api/v1/users/:id',
authorize,
usersController.getUser.bind(usersController)
)
// Get my info
.get('/api/v1/me', authorize, usersController.me.bind(usersController))
// Modify my info
.put(
'/api/v1/me',
authorize,
usersController.editUser.bind(usersController)
)
// Rate user
.put(
'/api/v1/users/:id/rating',
authorize,
ratingsController.rateUser.bind(ratingsController)
)
.post(
'/api/v1/events',
authorize,
eventsController.createEvent.bind(eventsController)
)
.put(
'/api/v1/events/:id',
authorize,
eventsController.editEvent.bind(eventsController)
)
.delete(
'/api/v1/events/:id',
authorize,
eventsController.deleteEvent.bind(eventsController)
)
.get(
'/api/v1/events/:id',
authorize,
eventsController.getEvent.bind(eventsController)
)
.put(
'/api/v1/events/:id/users',
authorize,
eventsController.joinEvent.bind(eventsController)
)
.delete(
'/api/v1/events/:id/users',
authorize,
eventsController.leaveEvent.bind(eventsController)
)
.get(
'/api/v1/events',
authorize,
eventsController.getEvents.bind(eventsController)
)
.options('/', options)
.trace('/', trace)
.head('/', head);
app.use(router.routes()).use(router.allowedMethods());
return app;
};
const head = async () => {
return;
};
const options = async () => {
this.body = 'Allow: HEAD,GET,PUT,DELETE,OPTIONS';
};
const trace = async () => {
this.body = 'Smart! But you can\'t trace.';
};
module.exports = routes;