forked from hjr265/toptal-recommengine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.coffee
112 lines (85 loc) · 2.23 KB
/
web.coffee
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
####
# This sample is published as part of the blog article at www.toptal.com/blog
# Visit www.toptal.com/blog and subscribe to our newsletter to read great posts
####
_ = require 'underscore'
async = require 'async'
Bourne = require 'bourne'
express = require 'express'
movies = require './data/movies.json'
Engine = require './lib/engine'
e = new Engine
app = express()
app.set 'views', "#{__dirname}/views"
app.set 'view engine', 'jade'
app.route('/refresh')
.post(({query}, res, next) ->
async.series [
(done) =>
e.similars.update query.user, done
(done) =>
e.suggestions.update query.user, done
], (err) =>
if err?
return next err
res.redirect "/?user=#{query.user}"
)
app.route('/like')
.post(({query}, res, next) ->
if query.unset is 'yes'
e.likes.remove query.user, query.movie, (err) =>
if err?
return next err
res.redirect "/?user=#{query.user}"
else
e.dislikes.remove query.user, query.movie, (err) =>
if err?
return next err
e.likes.add query.user, query.movie, (err) =>
if err?
return next err
res.redirect "/?user=#{query.user}"
)
app.route('/dislike')
.post(({query}, res, next) ->
if query.unset is 'yes'
e.dislikes.remove query.user, query.movie, (err) =>
if err?
return next err
res.redirect "/?user=#{query.user}"
else
e.likes.remove query.user, query.movie, (err) =>
if err?
return next err
e.dislikes.add query.user, query.movie, (err) =>
if err?
return next err
res.redirect "/?user=#{query.user}"
)
app.route('/')
.get(({query}, res, next) ->
async.auto
likes: (done) =>
e.likes.itemsByUser query.user, done
dislikes: (done) =>
e.dislikes.itemsByUser query.user, done
suggestions: (done) =>
e.suggestions.forUser query.user, (err, suggestions) =>
if err?
return done err
done null, _.map _.sortBy(suggestions, (suggestion) -> -suggestion.weight), (suggestion) =>
_.findWhere movies, id: suggestion.item
, (err, {likes, dislikes, suggestions}) =>
if err?
return next err
res.render 'index',
movies: movies
user: query.user
likes: likes
dislikes: dislikes
suggestions: suggestions[...4]
)
app.listen (port = 5000), (err) ->
if err?
throw err
console.log "Listening on #{port}"