forked from leiverandres/goodreads-graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema.py
88 lines (69 loc) · 2.58 KB
/
schema.py
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
import graphene
from pymongo import MongoClient
from bson.objectid import ObjectId
from basic_types import Book, Review
client = MongoClient()
books_collection = client.goodreads.books
reviews_collection = client.goodreads.reviews
class CreateReview(graphene.Mutation):
class Arguments:
bookId = graphene.Int(name='bookId', required=True)
username = graphene.String(required=True)
rate = graphene.Float(required=True)
text = graphene.String(required=True)
state = graphene.String()
review = graphene.Field(Review)
def mutate(self, info, bookId, username, rate, text):
result = books_collection.find_one({'bookId': bookId})
if result == None:
return CreateReview(state='Book id not found')
new_review = {
'bookId': bookId,
'username': username,
'rate': rate,
'text': text,
'likes': 0,
}
result = reviews_collection.insert_one(new_review)
if not result is None:
return CreateReview(state='success', review=new_review)
else:
return {'state': 'Something went wrong on serverside'}
class LikeReview(graphene.Mutation):
class Arguments:
id = graphene.ID()
review = graphene.Field(Review)
def mutate(self, info, id):
reviews_collection.update_one({
'_id': ObjectId(id)
}, {'$inc': {
'likes': 1
}})
review = reviews_collection.find_one(ObjectId(id))
return LikeReview(review=review)
class Query(graphene.ObjectType):
books = graphene.List(Book, pageSize=graphene.Int(), page=graphene.Int())
book = graphene.Field(Book, bookId=graphene.ID(required=True))
reviews = graphene.List(Review)
def resolve_books(self, info, **kwargs):
pageSize = kwargs.get('pageSize', None)
page = kwargs.get('page', None)
books = books_collection.find()
if pageSize != None and page != None:
start = page * pageSize
end = start + pageSize
return books[start:end]
return books
def resolve_book(self, info, bookId):
result = books_collection.find_one({'bookId': int(bookId)})
if result == None:
return {'message': 'Book not found'}
else:
return result
def resolve_reviews(self, info):
results = reviews_collection.find({})
return results
class Mutations(graphene.ObjectType):
create_review = CreateReview.Field()
like_review = LikeReview.Field()
schema = graphene.Schema(query=Query, mutation=Mutations)