forked from kvikuz/sls-web-application
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vote.ts
51 lines (43 loc) · 1.52 KB
/
vote.ts
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
import {getMovieById, getVotes, putVote, updateRating} from "./repository";
import {Vote} from "./model";
interface Event {
messages: Vote[]
}
const ERROR = {
"statusCode": 500,
"body": 'Fail to put vote and recalculate rating',
"isBase64Encoded": false
};
export const handler = async (event: Event): Promise<any> => {
try {
const vote = event.messages[0];
await putVote({
id: vote.user_id + "#" + vote.movie_id,
user_id: vote.user_id,
movie_id: vote.movie_id,
value: vote.value
} as Vote);
const votes = await getVotes(vote.movie_id);
if ("message" in votes) {
return ERROR;
}
console.debug(`Loaded ${votes.length} votes for movie ${vote.movie_id}`)
const movie = await getMovieById(vote.movie_id);
if (!movie || "message" in movie) {
return ERROR;
}
const sum = votes.reduce((sum, vote) => sum + vote.value, 0);
let tmdbRating = movie.vote_average ? movie.vote_average : 0;
const rating = (sum + tmdbRating * 100) / (votes.length + 100);
console.debug(`Recalculated rating: TMDB rating = ${tmdbRating}, old rating = ${movie.rating}, new rating = ${rating}`);
await updateRating(movie.id, rating);
return {
"statusCode": 200,
"body": 'Put vote successfully',
"isBase64Encoded": false
};
} catch (e) {
console.error("Failed to put vote: ", e);
return ERROR;
}
}