Skip to content

Commit

Permalink
Respond with absolute url for FileField
Browse files Browse the repository at this point in the history
  • Loading branch information
thenav56 committed Aug 21, 2024
1 parent 23efff0 commit 2353801
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,5 @@ dmypy.json

# editors
.idea/

assets/
1 change: 0 additions & 1 deletion schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,6 @@ scalar DateTime

type DjangoImageType {
name: String!
path: String!
size: Int!
url: String!
width: Int!
Expand Down
34 changes: 34 additions & 0 deletions utils/strawberry/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@

import strawberry
from django.contrib.gis.geos import GEOSGeometry
from django.core.files.storage import FileSystemStorage, default_storage
from django.db import models
from django.db.models.fields import Field as DjangoBaseField
from django.db.models.fields import files
from strawberry_django.fields.types import field_type_map

from main.graphql.context import Info

if typing.TYPE_CHECKING:
from django.db.models.fields import _FieldDescriptor
Expand Down Expand Up @@ -81,3 +86,32 @@ def nullable_string_(root) -> typing.Optional[str]:
if _field.null or _field.blank: # type: ignore[reportGeneralTypeIssues] FIXME
return nullable_string_
return string_


@strawberry.type
class DjangoFileType:
name: str
size: int

@strawberry.field
@staticmethod
def url(root: files.FieldFile, info: Info) -> str:
# TODO: Use cache if using S3 with signatured URL
if isinstance(default_storage, FileSystemStorage):
return info.context.request.build_absolute_uri(root.url)
return root.url


@strawberry.type
class DjangoImageType(DjangoFileType):
width: int
height: int


# Update the strawberry django field type mapping
field_type_map.update(
{
files.FileField: DjangoFileType,
files.ImageField: DjangoImageType,
}
)

0 comments on commit 2353801

Please sign in to comment.