Skip to content

Commit

Permalink
add unlike_photo mutation
Browse files Browse the repository at this point in the history
  • Loading branch information
jguo1002 committed Aug 17, 2022
1 parent ed7ce83 commit a200f2d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
7 changes: 6 additions & 1 deletion cat-photos/client/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ directive @specifiedBy(
url: String!
) on SCALAR

type Mutation {
likePhoto(id: String!): Photo!
unlikePhoto(id: String!): Photo!
}

type Photo {
id: String!
text: String!
Expand All @@ -14,6 +19,6 @@ type Photo {

type Query {
photos: [Photo!]!
photo(id: ID!): Photo!
photo(id: String!): Photo!
}

24 changes: 20 additions & 4 deletions cat-photos/server/schema.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import typing
from typing import List, Union, Any, Optional, NewType
import strawberry

import strawberry.asgi as gqla
import starlette.requests as strq
import starlette.responses as strp
Expand Down Expand Up @@ -65,6 +64,11 @@ async def get_photos():
class Query:
photos: typing.List[Photo] = strawberry.field(resolver=get_photos)

@strawberry.field
async def photo(self, id: str) -> Photo:
photo = collection.find_one({"id": id})
return Photo.marshal(photo)

# @strawberry.field
# async def photo(self, info: Info, id: strawberry.ID) -> Photo:
# return await info.context["photo_loader"].load(id)
Expand All @@ -73,12 +77,24 @@ class Query:
@strawberry.type
class Mutation:
@strawberry.mutation
def like_photo(self, id: str) -> None:
def like_photo(self, id: str) -> Photo:
print(f'Like a photo {id}')
likesCount = collection.find_one({"id": id})["likesCount"]
collection.update_one(
{'id': id},
{"$set": {"likesCount": likesCount + 1, "meHasLiked": True}}, upsert=False)
photo = collection.find_one({"id": id})
likesCount = photo["likesCount"]
return Photo.marshal(photo)

@strawberry.mutation
def unlike_photo(self, id: str) -> Photo:
print(f'Unlike a photo {id}')
likesCount = collection.find_one({"id": id})["likesCount"]
collection.update_one(
{'id': id}, {"$set": {"likesCount": likesCount + 1, "meHasLiked": True}}, upsert=False)
{'id': id},
{"$set": {"likesCount": likesCount - 1, "meHasLiked": False}}, upsert=False)
photo = collection.find_one({"id": id})
return Photo.marshal(photo)


schema = strawberry.Schema(query=Query, mutation=Mutation)
Expand Down

0 comments on commit a200f2d

Please sign in to comment.