challege.ctrl.js
1.78 KB
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
const Challenge = require("../../models/challenge");
const Joi = require("joi");
/*POST /api/challenge/getChallenge
{
challengeName: "challengeName"
}
*/
exports.getChallenge = async (ctx) => {
try {
const { challengeName } = ctx.request.body;
const challenge = await Challenge.findByChallengeName(challengeName);
if (!challenge) {
ctx.status = 401;
return;
}
ctx.body = challenge;
} catch (e) {
ctx.throw(500, e);
}
};
/*POST /api/challenge/addChallenge
{
challengeName: "challengeName",
startDate: Date Object,
endDate: Date Object,
durationPerSession: "2w", // '1d' means one day per session, '2w' means 2 weeks per session, '3m' means 3 months per session.
goalPerSession: 3,
groups: [{'name1', 'name2'}]
}
*/
exports.addChallenge = async (ctx) => {
const schema = Joi.object()
.keys({
challengeName: Joi.string(),
startDate: Joi.date(),
endDate: Joi.date(),
durationPerSession: Joi.string(),
goalPerSession: Joi.number(),
groups: Joi.array().items(Joi.string()),
})
.unknown();
const result = Joi.validate(ctx.request.body, schema);
if (result.error) {
ctx.status = 400;
ctx.body = result.error;
return;
}
const {
challengeName,
startDate,
endDate,
durationPerSession,
goalPerSession,
} = ctx.request.body;
try {
const isChallengeExist = await Challenge.findByChallengeName(challengeName);
if (isChallengeExist) {
ctx.status = 409;
return;
}
const challenge = new Challenge({
challengeName,
startDate,
endDate,
durationPerSession,
goalPerSession,
});
await challenge.save();
ctx.body = challenge();
} catch (e) {
ctx.throw(500, e);
}
/*
TODO: How to handle group?
*/
};