Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/graphql scaffold #81

Merged
merged 16 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added backend/graphql_app/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions backend/graphql_app/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class GraphqlAppConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "graphql_app"
5 changes: 5 additions & 0 deletions backend/graphql_app/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class GraphQLAuthMiddleware:
def resolve(self, next, root, info, **kwargs):
if info.context.user.is_authenticated:
return next(root, info, **kwargs)
raise Exception("User is not authenticated")
15 changes: 15 additions & 0 deletions backend/graphql_app/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from graphene import ObjectType, Schema

from source.queries import SourceQueries
from source.mutations.UpdateOrCreateSourceMutation import UpdateOrCreateSourceMutation


class Query(SourceQueries, ObjectType):
pass


class Mutation(ObjectType):
update_or_create_source = UpdateOrCreateSourceMutation.Field()


schema = Schema(query=Query, mutation=Mutation)
58 changes: 58 additions & 0 deletions backend/graphql_app/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from graphene_django.utils.testing import GraphQLTestCase

from source.models import Source
from user.models import User


class GraphQLAuthMiddleWareTestCase(GraphQLTestCase):
"""
Tests for the GraphQLAuthMiddleware
"""

GRAPHQL_URL = "/api/graphql"

SOURCES_QUERY = """
query GET_SOURCES {
sources {
id
}
}
"""

@classmethod
def setUpTestData(cls) -> None:
cls.user = User.objects.create(
username="test", email="test@test.nl", password="test"
)

cls.source = Source.objects.create(
name="Test Source",
medieval_title="Test Medieval Title",
medieval_author="Test Medieval Author",
edition_title="Test Edition Title",
edition_author="Test Edition Author",
)

return super().setUpTestData()

def test_middleware_raises_exception_when_user_is_not_authenticated(self):
response = self.query(self.SOURCES_QUERY)

self.assertResponseHasErrors(response)

content = response.json()

self.assertEqual(content["errors"][0]["message"], "User is not authenticated")

def test_middleware_does_not_raise_exception_when_user_is_authenticated(self):
self.client.force_login(self.user)

response = self.query(self.SOURCES_QUERY)

self.assertResponseNoErrors(response)

content = response.json()

# The first Source in the list is the default MISSING_SOURCE.
self.assertEqual(len(content["data"]["sources"]), 2)
self.assertEqual(content["data"]["sources"][1]["id"], str(self.source.pk))
11 changes: 11 additions & 0 deletions backend/graphql_app/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.conf import settings
from django.urls import path
from graphene_django.views import GraphQLView
from django.views.decorators.csrf import csrf_exempt

# TODO: Handle CSRF correctly.
urlpatterns = [
path(
"graphql", csrf_exempt(GraphQLView.as_view(graphiql=settings.ENABLE_GRAPHIQL))
),
]
11 changes: 11 additions & 0 deletions backend/lettercraft/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@
"source",
"space",
"user",
"graphene_django",
"graphql_app",
]

MIDDLEWARE = [
Expand Down Expand Up @@ -93,6 +95,15 @@
]
}

# GraphQL
GRAPHENE = {
"SCHEMA": "graphql_app.schema.schema",
"MIDDLEWARE": [
"graphql_app.middleware.GraphQLAuthMiddleware",
],
}
ENABLE_GRAPHIQL = DEBUG

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

Expand Down
2 changes: 1 addition & 1 deletion backend/lettercraft/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
path("api", RedirectView.as_view(url="/api/", permanent=True)),
path("api-auth", RedirectView.as_view(url="/api-auth/", permanent=True)),
path("admin/", admin.site.urls),
path("api/", include(api_router.urls)),
path("api/", include("graphql_app.urls")),
path(
"api-auth/",
include(
Expand Down
2 changes: 2 additions & 0 deletions backend/requirements.in
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ pytest-django
pytest-xdist
dj_rest_auth
django-allauth
graphene
graphene-django
33 changes: 31 additions & 2 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
# This file is autogenerated by pip-compile with Python 3.10
# by the following command:
#
# pip-compile
# pip-compile requirements.in
#
--no-binary psycopg2

aniso8601==9.0.1
# via graphene
asgiref==3.7.2
# via django
beautifulsoup4==4.12.2
Expand All @@ -16,6 +18,8 @@ cffi==1.16.0
# via cryptography
charset-normalizer==3.3.2
# via requests
colorama==0.4.6
# via pytest
cryptography==42.0.5
# via pyjwt
defusedxml==0.7.1
Expand All @@ -30,6 +34,7 @@ django==4.2.7
# django-livereload-server
# django-revproxy
# djangorestframework
# graphene-django
django-allauth==0.61.1
# via -r requirements.in
django-livereload-server==0.4
Expand All @@ -46,6 +51,21 @@ execnet==2.0.2
# via pytest-xdist
faker==23.2.0
# via -r requirements.in
graphene==3.3
# via
# -r requirements.in
# graphene-django
graphene-django==3.2.2
# via -r requirements.in
graphql-core==3.2.3
# via
# graphene
# graphene-django
# graphql-relay
graphql-relay==3.2.0
# via
# graphene
# graphene-django
idna==3.7
# via requests
iniconfig==2.0.0
Expand All @@ -56,12 +76,16 @@ packaging==23.2
# via pytest
pluggy==1.3.0
# via pytest
promise==2.3
# via graphene-django
psycopg2==2.9.9
# via -r requirements.in
pycparser==2.22
# via cffi
pyjwt[crypto]==2.8.0
# via django-allauth
# via
# django-allauth
# pyjwt
pytest==7.4.3
# via
# -r requirements.in
Expand All @@ -86,17 +110,22 @@ requests-oauthlib==2.0.0
six==1.16.0
# via
# django-livereload-server
# promise
# python-dateutil
soupsieve==2.5
# via beautifulsoup4
sqlparse==0.4.4
# via django
text-unidecode==1.3
# via graphene-django
tomli==2.0.1
# via pytest
tornado==6.3.3
# via django-livereload-server
typing-extensions==4.8.0
# via asgiref
tzdata==2024.1
# via django
urllib3==2.0.7
# via
# django-revproxy
Expand Down
40 changes: 40 additions & 0 deletions backend/source/mutations/UpdateOrCreateSourceMutation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from graphene import ID, Field, InputObjectType, List, Mutation, ResolveInfo, String

from source.models import Source
from source.types.SourceType import SourceType


class UpdateCreateSourceInput(InputObjectType):
id = ID()
name = String(required=True)
edition_author = String()
edition_title = String()
medieval_author = String()
medieval_title = String()


class UpdateOrCreateSourceMutation(Mutation):
source = Field(SourceType)
errors = List(String)

class Arguments:
input = UpdateCreateSourceInput(required=True)

@classmethod
def mutate(cls, root: None, info: ResolveInfo, input: UpdateCreateSourceInput):
source_id = getattr(input, "id", None)

if source_id:
try:
source = SourceType.get_queryset(Source.objects, info).get(pk=source_id)
except Source.DoesNotExist:
return cls(errors=["Source not found."]) # type: ignore
else:
source = Source()

for field, value in input.items(): # type: ignore
setattr(source, field, value)

source.save()

return cls(source=source) # type: ignore
8 changes: 8 additions & 0 deletions backend/source/queries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from graphene import ObjectType
from graphene_django import DjangoListField

from source.types.SourceType import SourceType


class SourceQueries(ObjectType):
sources = DjangoListField(SourceType)
XanderVertegaal marked this conversation as resolved.
Show resolved Hide resolved
15 changes: 15 additions & 0 deletions backend/source/types/SourceType.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from graphene import ResolveInfo
from django.db.models import QuerySet
from graphene_django import DjangoObjectType
from source.models import Source


class SourceType(DjangoObjectType):
class Meta:
model = Source

@classmethod
def get_queryset(
XanderVertegaal marked this conversation as resolved.
Show resolved Hide resolved
cls, queryset: QuerySet[Source], info: ResolveInfo
) -> QuerySet[Source]:
return queryset.all()
3 changes: 3 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,6 @@ testem.log
# System files
.DS_Store
Thumbs.db

# Generated files
/generated/*.*
28 changes: 28 additions & 0 deletions frontend/codegen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
schema: 'http://localhost:8000/api/graphql',
generates: {
'./generated/graphql.ts': {
plugins: [
'typescript',
'typescript-operations',
'typescript-apollo-angular'
],
config: {
addExplicitOverride: true
}
},
'./generated/schema.graphql': {
plugins: ['schema-ast']
}
},
ignoreNoDocuments: true,
documents: [
"src/**/*.ts",
"src/**/*.graphql",
],
}

export default config

11 changes: 9 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"stop": "lsof -t -i tcp:4200 | xargs kill -9 || echo \"not running\"",
"pretest": "yarn prebuild",
"watch-test": "ng test --watch=true",
"lint": "ng lint"
"lint": "ng lint",
"codegen": "yarn graphql-codegen --verbose --watch"
},
"private": true,
"dependencies": {
Expand All @@ -24,15 +25,18 @@
"@angular/platform-browser": "^16.2.12",
"@angular/platform-browser-dynamic": "^16.2.12",
"@angular/router": "^16.2.12",
"@apollo/client": "^3.0.0",
"@fortawesome/angular-fontawesome": "^0.13",
"@fortawesome/fontawesome-svg-core": "^6.2.1",
"@fortawesome/free-solid-svg-icons": "^6.2.1",
"@ng-bootstrap/ng-bootstrap": "^15.0.0",
"@ngrx/effects": "^16.0.0",
"@ngrx/store": "^16.0.0",
"@popperjs/core": "^2.11.6",
"apollo-angular": "5.0.2",
"bootstrap": "^5.2.3",
"colors": "^1.4.0",
"graphql": "^16",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"underscore": "^1.13.6",
Expand All @@ -48,6 +52,9 @@
"@angular/cli": "~16.2.10",
"@angular/compiler-cli": "^16.2.12",
"@angular/localize": "^16.2.12",
"@graphql-codegen/cli": "^5.0.2",
"@graphql-codegen/typescript-apollo-angular": "^4.0.0",
"@parcel/watcher": "^2.4.1",
"@types/jasmine": "~4.3.0",
"@types/underscore": "^1.11.15",
"@typescript-eslint/eslint-plugin": "5.62.0",
Expand All @@ -61,4 +68,4 @@
"karma-jasmine-html-reporter": "~2.0.0",
"typescript": "~4.9.4"
}
}
}
4 changes: 4 additions & 0 deletions frontend/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { HomeComponent } from './home/home.component';
import { SharedModule } from './shared/shared.module';
import { CoreModule } from './core/core.module';
import { UserModule } from './user/user.module';
import { GraphQLModule } from './graphql.module';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [
Expand All @@ -18,6 +20,8 @@ import { UserModule } from './user/user.module';
SharedModule,
CoreModule,
UserModule,
GraphQLModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
Expand Down
Loading
Loading