11import graphene
22from graphene_django import DjangoObjectType
3+ from graphql import GraphQLError
4+ from django .db .models import Q
35from .models import Book , Like
46from users .schema import UserType
57
@@ -14,10 +16,19 @@ class Meta:
1416
1517
1618class Query (graphene .ObjectType ):
17- books = graphene .List (BookType )
19+ books = graphene .List (BookType , search = graphene . String () )
1820 likes = graphene .List (LikeType )
1921
20- def resolve_books (self , info ):
22+ def resolve_books (self , info , search = None ):
23+ if search :
24+ filter = (
25+ Q (title__icontains = search ) |
26+ Q (description__icontains = search ) |
27+ Q (url__icontains = search ) |
28+ Q (posted_by__username__icontains = search )
29+ )
30+ return Book .objects .filter (filter )
31+
2132 return Book .objects .all ()
2233 def resolve_likes (self , info ):
2334 return Like .objects .all ()
@@ -36,7 +47,7 @@ def mutate(self, info, title, author, description, url):
3647 user = info .context .user
3748
3849 if user .is_anonymous :
39- raise Exception ("Login to add a book" )
50+ raise GraphQLError ("Login to add a book" )
4051
4152 book = Book (title = title , author = author , description = description , url = url , posted_by = user )
4253 book .save ()
@@ -58,7 +69,7 @@ def mutate(self, info, book_id, title, author, description, url):
5869 book = Book .objects .get (id = book_id )
5970
6071 if book .posted_by != user :
61- raise Exception ("Not permited to update" )
72+ raise GraphQLError ("Not permited to update" )
6273
6374 book .title = title
6475 book .description = description
@@ -81,7 +92,7 @@ def mutate(self, info, book_id):
8192 book = Book .objects .get (id = book_id )
8293
8394 if book .posted_by != user :
84- raise Exception ("Not permited to delete this book" )
95+ raise GraphQLError ("Not permited to delete this book" )
8596
8697 book .delete ()
8798
@@ -99,11 +110,11 @@ def mutate(self, info, book_id):
99110 user = info .context .user
100111
101112 if user .is_anonymous :
102- raise Exception ("Login first" )
113+ raise GraphQLError ("Login first" )
103114
104115 book = Book .objects .get (id = book_id )
105116 if not book :
106- raise Exception ('Cannot find a book with id {}' .format (book_id ))
117+ raise GraphQLError ('Cannot find a book with id {}' .format (book_id ))
107118
108119 Like .objects .create (
109120 user = user ,
0 commit comments