1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Feedback related features
21 # Group all api handlers in one router
22 class APIFeedbackRouter
25 # Mongo collection used to store ratings
26 var collection
: MongoCollection
29 use
("/stars/:id", new APIStars(model
, mainmodule
, collection
))
33 # Stars attributed to mentities
37 # Collection used to store ratings
38 var collection
: MongoCollection
40 redef fun get
(req
, res
) do
41 var mentity
= mentity_from_uri
(req
, res
)
42 if mentity
== null then
47 res
.json mentity_ratings
(mentity
)
50 redef fun post
(req
, res
) do
51 var mentity
= mentity_from_uri
(req
, res
)
52 if mentity
== null then
56 var obj
= req
.body
.parse_json
57 if not obj
isa JsonObject then
61 var rating
= obj
["rating"]
62 if not rating
isa Int then
67 var val
= new MEntityRating(mentity
.full_name
, rating
, get_time
)
68 collection
.insert
(val
.json
)
70 res
.json mentity_ratings
(mentity
)
73 # Get the ratings of a `mentity`
74 fun mentity_ratings
(mentity
: MEntity): MEntityRatings do
75 var ratings
= new MEntityRatings(mentity
)
77 var req
= new JsonObject
78 req
["mentity"] = mentity
.full_name
79 var rs
= collection
.find_all
(req
)
80 for r
in rs
do ratings
.ratings
.add
new MEntityRating.from_json
(r
)
85 # Ratings representation for a mentity
93 var ratings
= new Array[MEntityRating]
95 # Mean of all ratings or 0
97 if ratings
.is_empty
then return 0.0
99 for r
in ratings
do sum
+= r
.rating
.to_f
100 var res
= sum
/ ratings
.length
.to_f
104 # Json representation of `self`
105 fun json
: JsonObject do
106 var obj
= new JsonObject
107 obj
["mentity"] = mentity
.full_name
108 obj
["ratings"] = new JsonArray.from
(ratings
)
113 redef fun to_json
do return json
.to_json
116 # Rating value of a MEntity
120 # MEntity this rating is about
123 # Rating value (between 1 and 5)
126 # Timestamp of this rating
129 # Init this rating value from a JsonObject
130 init from_json
(obj
: JsonObject) do
131 init(obj
["mentity"].as(String), obj
["rating"].as(Int), obj
["timestamp"].as(Int))
134 # Translate this rating value to a JsonObject
135 fun json
: JsonObject do
136 var obj
= new JsonObject
137 obj
["mentity"] = mentity
138 obj
["rating"] = rating
139 obj
["timestamp"] = timestamp
143 redef fun to_json
do return json
.to_json