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
20 redef class NitwebConfig
22 # MongoDB collection used to store stars.
23 var stars
: MongoCollection is lazy
do return db
.collection
("stars")
29 use
("/feedback/stars/:id", new APIStars(config
))
33 # Stars attributed to mentities
37 redef fun get
(req
, res
) do
38 var mentity
= mentity_from_uri
(req
, res
)
39 if mentity
== null then
44 res
.json mentity_ratings
(mentity
)
47 redef fun post
(req
, res
) do
48 var mentity
= mentity_from_uri
(req
, res
)
49 if mentity
== null then
53 var obj
= req
.body
.parse_json
54 if not obj
isa JsonObject then
58 var rating
= obj
["rating"]
59 if not rating
isa Int then
64 var val
= new MEntityRating(mentity
.full_name
, rating
, get_time
)
65 config
.stars
.insert
(val
.json
)
67 res
.json mentity_ratings
(mentity
)
70 # Get the ratings of a `mentity`
71 fun mentity_ratings
(mentity
: MEntity): MEntityRatings do
72 var ratings
= new MEntityRatings(mentity
)
74 var req
= new JsonObject
75 req
["mentity"] = mentity
.full_name
76 var rs
= config
.stars
.find_all
(req
)
77 for r
in rs
do ratings
.ratings
.add
new MEntityRating.from_json
(r
)
82 # Ratings representation for a mentity
90 var ratings
= new Array[MEntityRating]
92 # Mean of all ratings or 0
94 if ratings
.is_empty
then return 0.0
96 for r
in ratings
do sum
+= r
.rating
.to_f
97 var res
= sum
/ ratings
.length
.to_f
101 # Json representation of `self`
102 fun json
: JsonObject do
103 var obj
= new JsonObject
104 obj
["mentity"] = mentity
.full_name
105 obj
["ratings"] = new JsonArray.from
(ratings
)
110 redef fun to_json
do return json
.to_json
113 # Rating value of a MEntity
117 # MEntity this rating is about
120 # Rating value (between 1 and 5)
123 # Timestamp of this rating
126 # Init this rating value from a JsonObject
127 init from_json
(obj
: JsonObject) do
128 init(obj
["mentity"].as(String), obj
["rating"].as(Int), obj
["timestamp"].as(Int))
131 # Translate this rating value to a JsonObject
132 fun json
: JsonObject do
133 var obj
= new JsonObject
134 obj
["mentity"] = mentity
135 obj
["rating"] = rating
136 obj
["timestamp"] = timestamp
140 redef fun to_json
do return json
.to_json