1+ import graphene
2+ from django .db .models import Q
3+ from graphene_django import DjangoObjectType
4+
5+ from apps .accounts .schema import UserType
6+
7+ from .models import Link , Vote
8+
9+ class LinkType (DjangoObjectType ):
10+ class Meta :
11+ model = Link
12+
13+ class VoteType (DjangoObjectType ):
14+ class Meta :
15+ model = Vote
16+
17+
18+ class Query (graphene .ObjectType ):
19+ links = graphene .List (
20+ LinkType ,
21+ search = graphene .String (),
22+ first = graphene .Int (),
23+ skip = graphene .Int ()
24+ )
25+ votes = graphene .List (VoteType )
26+
27+ def resolve_links (self , info , search = None , first = None , skip = None , ** kwargs ):
28+ qs = Link .objects .all ()
29+ if search :
30+ filter = (
31+ Q (url__icontains = search ) |
32+ Q (description__icontains = search )
33+ )
34+ qs = qs .filter (filter )
35+
36+ if skip :
37+ qs = qs [skip :]
38+
39+ if first :
40+ qs = qs [:first ]
41+
42+ return qs
43+
44+ def resolve_votes (self , info , ** kwargs ):
45+ return Vote .objects .all ()
46+
47+
48+ class CreateLink (graphene .Mutation ):
49+ id = graphene .Int ()
50+ url = graphene .String ()
51+ description = graphene .String ()
52+ posted_by = graphene .Field (UserType )
53+
54+ class Arguments :
55+ url = graphene .String ()
56+ description = graphene .String ()
57+
58+ def mutate (self , info , url , description ):
59+ user = info .context .user or None
60+ link = Link (
61+ url = url ,
62+ description = description ,
63+ posted_by = user
64+ )
65+
66+ link .save ()
67+
68+ return CreateLink (
69+ id = link .id ,
70+ url = link .url ,
71+ description = link .description ,
72+ posted_by = link .posted_by
73+ )
74+
75+ class CreateVote (graphene .Mutation ):
76+ user = graphene .Field (UserType )
77+ link = graphene .Field (LinkType )
78+
79+ class Arguments :
80+ link_id = graphene .Int ()
81+
82+ def mutate (self , info , link_id ):
83+ user = info .context .user
84+ if user .is_anonymous :
85+ raise Exception ("Must be logged in to vote" )
86+
87+ link = Link .objects .filter (id = link_id ).first ()
88+
89+ if not link :
90+ raise Exception ("Invalid link" )
91+
92+ Vote .objects .create (
93+ user = user ,
94+ link = link
95+ )
96+
97+ return CreateVote (user = user , link = link )
98+
99+ class Mutation (graphene .ObjectType ):
100+ create_link = CreateLink .Field ()
101+ create_vote = CreateVote .Field ()
0 commit comments