Skip to content

Commit

Permalink
refactor(organization): make organizations endpoint more "RESTful" (#…
Browse files Browse the repository at this point in the history
…5331)

### 📣 Summary
Refactored the organizations endpoint to adhere more closely to RESTful
principles. Added additional properties to the API response.


### 📖 Description
This PR refactors the organizations endpoint to align better with
RESTful standards. The changes enhance the API's usability and
consistency by including more properties in the response and relying on
url as an (even the primary) identifier for resources.
  • Loading branch information
noliveleger authored Dec 5, 2024
1 parent 3df2281 commit 019c02d
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions kobo/apps/organizations/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.contrib.auth import get_user_model
from django.utils.translation import gettext as t
from rest_framework import serializers
from rest_framework.relations import HyperlinkedIdentityField
from rest_framework.reverse import reverse

from kobo.apps.organizations.models import (
Expand Down Expand Up @@ -83,14 +84,20 @@ class Meta:

class OrganizationSerializer(serializers.ModelSerializer):

assets = serializers.SerializerMethodField()
asset_usage = serializers.SerializerMethodField()
is_mmo = serializers.BooleanField(read_only=True)
is_owner = serializers.SerializerMethodField()
members = serializers.SerializerMethodField()
request_user_role = serializers.SerializerMethodField()
service_usage = serializers.SerializerMethodField()
url = HyperlinkedIdentityField(lookup_field='id', view_name='organizations-detail')

class Meta:
model = Organization
fields = [
'id',
'url',
'name',
'website',
'organization_type',
Expand All @@ -99,13 +106,45 @@ class Meta:
'is_owner',
'is_mmo',
'request_user_role',
'members',
'assets',
'service_usage',
'asset_usage',
]
read_only_fields = ['id']

def create(self, validated_data):
user = self.context['request'].user
return create_organization(user, validated_data['name'])

def get_assets(self, organization: Organization) -> str:
return reverse(
'organizations-assets',
kwargs={'id': organization.id},
request=self.context['request'],
)

def get_asset_usage(self, organization: Organization) -> str:
return reverse(
'organizations-asset-usage',
kwargs={'id': organization.id},
request=self.context['request'],
)

def get_members(self, organization: Organization) -> str:
return reverse(
'organization-members-list',
kwargs={'organization_id': organization.id},
request=self.context['request'],
)

def get_service_usage(self, organization: Organization) -> str:
return reverse(
'organizations-service-usage',
kwargs={'id': organization.id},
request=self.context['request'],
)

def get_is_owner(self, organization):

# This method is deprecated.
Expand Down

0 comments on commit 019c02d

Please sign in to comment.