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

Open
wants to merge 10 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Empty file added backend/api/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions backend/api/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions backend/api/apps.py
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this app seem to be specifically handling the graphql portion of the API, perhaps graphql would be a more appropriate name than api.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class ApiConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "api"
Empty file added backend/api/graphql/__init__.py
Empty file.
18 changes: 18 additions & 0 deletions backend/api/graphql/schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from graphene import ObjectType, Schema

from source.mutations.DeleteSourceMutation import DeleteSourceMutation
from source.queries import SourceQueries

from source.mutations.UpdateOrCreateSourceMutation import UpdateOrCreateSourceMutation


class Query(SourceQueries, ObjectType):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not everyone is a fan of inheritance like this. We can also write all the queries (and their resolvers here), but that usually ends up being a very long list.

pass


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


schema = Schema(query=Query, mutation=Mutation)
Empty file.
3 changes: 3 additions & 0 deletions backend/api/models.py
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This app includes some files generated by startapp which aren't used (admin, models, views, tests). Can you remove them?

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
3 changes: 3 additions & 0 deletions backend/api/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
11 changes: 11 additions & 0 deletions backend/api/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))
),
]
3 changes: 3 additions & 0 deletions backend/api/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.shortcuts import render

# Create your views here.
5 changes: 5 additions & 0 deletions backend/lettercraft/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"source",
"space",
"user",
"graphene_django",
]

MIDDLEWARE = [
Expand Down Expand Up @@ -93,6 +94,10 @@
]
}

# GraphQL
GRAPHENE = {"SCHEMA": "api.graphql.schema.schema"}
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("api.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
21 changes: 21 additions & 0 deletions backend/source/mutations/DeleteSourceMutation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from graphene import Mutation, ID, Boolean, ResolveInfo, String
from source.models import Source


class DeleteSourceMutation(Mutation):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation of this looks fine, but deleting sources is quite destructive, so it may be better to restrict this to the admin interface.

ok = Boolean(required=True)
error = String()

class Arguments:
id = ID(required=True)

@classmethod
def mutate(cls, root: None, info: ResolveInfo, id: str):
try:
source = Source.objects.get(pk=id)
except Source.DoesNotExist:
return cls(ok=False, error="Source not found.") # type: ignore

source.delete()

return cls(ok=True) # type: ignore
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)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DjangoListField is a handy util from graphene_django that has a built-in resolver. By default it returns all objects in the database. When we start to add filtering/sorting, we will have to write resolve_sources() ourselves.

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(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I usually define get_queryset() on every type. It is used to filter the queryset, most often based on the user making the request (obtainable via info.context.user). It's not necessary (and in fact return queryset.all() is the default implementation), but it is nice to be explicit about returning all objects of a particular type.

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
24 changes: 24 additions & 0 deletions frontend/src/app/graphql.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { APOLLO_OPTIONS, ApolloModule } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { NgModule } from '@angular/core';
import { ApolloClientOptions, InMemoryCache } from '@apollo/client/core';

const uri = 'http://localhost:8000/api/graphql'; // <-- add the URL of the GraphQL server here
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This URL is now hardcoded. I can move it to environment.ts and environment.prod.ts, but how does this work when we start deploying? What URL should I pick for the production backend?

I'm sure you have run into this issue before in other projects, so any advice would be helpful!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In most cases, you use absolute URLs without a hostname (+ port), e.g. '/api/graphql'.

If you're accessing the frontend development server on https://localhost:4200, this will resolve as https://localhost:4200/api/graphql. The development server includes a proxy configuration, which will redirect that to https://localhost:8000/api/graphql, i.e. the backend port.

On production, you don't have this kind of proxying, as the endpoints for the frontend client and the backend API will have the same origin (e.g. https://myproject.org and https://myproject.org/api/graphql).

The example in the apollo-angular documentation uses a URL like this, did you try that?

export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
return {
link: httpLink.create({ uri }),
cache: new InMemoryCache(),
};
}

@NgModule({
exports: [ApolloModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink],
},
],
})
export class GraphQLModule {}