Skip to content

Commit

Permalink
Tidy up group_membership_api_factory()
Browse files Browse the repository at this point in the history
Move stuff out into helper functions, making way for future changes to
the function's logic.
  • Loading branch information
seanh committed Jan 7, 2025
1 parent c0e6d72 commit 026e974
Showing 1 changed file with 25 additions and 18 deletions.
43 changes: 25 additions & 18 deletions h/traversal/group_membership.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,38 +21,45 @@ class EditGroupMembershipContext:
new_roles: list[GroupMembershipRoles]


def group_membership_api_factory(request) -> GroupMembershipContext:
def _get_user(request, userid) -> User | None:
user_service = request.find_service(name="user")

if userid == "me":
if request.authenticated_userid:
return user_service.fetch(request.authenticated_userid)

return None

try:
return user_service.fetch(userid)
except InvalidUserId:
return None


def _get_group(request, pubid) -> Group | None:
group_service = request.find_service(name="group")
group_members_service = request.find_service(name="group_members")
return group_service.fetch(pubid)

userid = request.matchdict["userid"]
pubid = request.matchdict["pubid"]

def get_user() -> User | None:
if userid == "me":
if request.authenticated_userid:
return user_service.fetch(request.authenticated_userid)
def _get_membership(request, group, user) -> GroupMembership | None:
group_members_service = request.find_service(name="group_members")
return group_members_service.get_membership(group, user)

return None

try:
return user_service.fetch(userid)
except InvalidUserId:
return None
def group_membership_api_factory(request) -> GroupMembershipContext:
userid = request.matchdict["userid"]
pubid = request.matchdict["pubid"]

user = get_user()
user = _get_user(request, userid)
group = _get_group(request, pubid)
membership = _get_membership(request, group, user)

if not user:
raise HTTPNotFound(f"User not found: {userid}")

group = group_service.fetch(pubid)

if not group:
raise HTTPNotFound(f"Group not found: {pubid}")

membership = group_members_service.get_membership(group, user)

if not membership and request.method != "POST":
raise HTTPNotFound(f"Membership not found: ({pubid}, {userid})")

Expand Down

0 comments on commit 026e974

Please sign in to comment.