INIT Commit
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
__all__ = [
|
||||
'copilots_dataloader'
|
||||
]
|
||||
|
||||
from graphql_schema.dataloaders.copilots import copilots_dataloader
|
||||
@@ -0,0 +1,16 @@
|
||||
from typing import List
|
||||
from sqlalchemy import select
|
||||
from strawberry.dataloader import DataLoader
|
||||
from database import async_session
|
||||
from database.models import Aircraft
|
||||
|
||||
|
||||
async def load(ids: List[int]):
|
||||
async with async_session() as session:
|
||||
models = (await session.scalars(select(Aircraft).filter(Aircraft.id.in_(ids)))).all()
|
||||
|
||||
models_by_id = {model.id: model for model in models}
|
||||
return [models_by_id.get(id_) for id_ in ids]
|
||||
|
||||
|
||||
aircraft_dataloader = DataLoader(load_fn=load)
|
||||
@@ -0,0 +1,16 @@
|
||||
from typing import List
|
||||
from sqlalchemy import select
|
||||
from strawberry.dataloader import DataLoader
|
||||
from database import async_session
|
||||
from database.models import Copilot
|
||||
|
||||
|
||||
async def load(ids: List[int]):
|
||||
async with async_session() as session:
|
||||
models = (await session.scalars(select(Copilot).filter(Copilot.id.in_(ids)))).all()
|
||||
|
||||
models_by_id = {model.id: model for model in models}
|
||||
return [models_by_id.get(id_) for id_ in ids]
|
||||
|
||||
|
||||
copilots_dataloader = DataLoader(load_fn=load)
|
||||
@@ -0,0 +1,121 @@
|
||||
import os
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
import strawberry
|
||||
from strawberry.file_uploads import Upload
|
||||
from sqlalchemy import select
|
||||
from database import models
|
||||
from graphql_schema.sqlalchemy_to_strawberry_type import strawberry_sqlalchemy_type, strawberry_sqlalchemy_input
|
||||
|
||||
|
||||
@strawberry_sqlalchemy_type(models.Aircraft)
|
||||
class Aircraft:
|
||||
photo_url: Optional[str] = strawberry.field(
|
||||
resolver=lambda root: f"http://localhost:8000/uploads/{root.photo_filename}" if root.photo_filename else None
|
||||
)
|
||||
|
||||
|
||||
def get_base_query(user_id: int):
|
||||
return (
|
||||
select(models.Aircraft)
|
||||
.filter(models.Aircraft.created_by_id == user_id)
|
||||
.filter(models.Aircraft.deleted.is_(False))
|
||||
)
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class AircraftQueries:
|
||||
|
||||
@strawberry.field
|
||||
async def aircrafts(root, info) -> List[Aircraft]:
|
||||
query = (
|
||||
get_base_query(info.context.user_id)
|
||||
.order_by(models.Aircraft.id.desc())
|
||||
)
|
||||
|
||||
return (await info.context.db.scalars(query)).all()
|
||||
|
||||
@strawberry.field
|
||||
async def aircraft(root, info, id: int) -> Aircraft:
|
||||
query = (
|
||||
get_base_query(info.context.user_id)
|
||||
.filter(models.Aircraft.id == id)
|
||||
)
|
||||
return (await info.context.db.scalars(query)).one()
|
||||
|
||||
|
||||
def check_directories(path: str):
|
||||
if not os.path.isdir(path):
|
||||
os.makedirs(path)
|
||||
|
||||
|
||||
async def handle_img_upload(file: Upload, path: str, filename: str):
|
||||
check_directories(path)
|
||||
|
||||
content = await file.read()
|
||||
image = open(path + "/" + filename, "wb")
|
||||
image.write(content)
|
||||
image.close()
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class CreateAircraftMutation:
|
||||
@strawberry_sqlalchemy_input(models.Aircraft, exclude_fields=['id', 'photo_filename'])
|
||||
class CreateAircraftInput:
|
||||
photo: Optional[Upload]
|
||||
|
||||
@strawberry.mutation
|
||||
async def create_aircraft(root, info, input: CreateAircraftInput) -> Aircraft:
|
||||
# TODO: kontrola organizace
|
||||
|
||||
filename = None
|
||||
if input.photo:
|
||||
dest_path = "/app/uploads/aircrafts/"
|
||||
filename = f"{uuid.uuid4()}-{input.photo.filename}"
|
||||
await handle_img_upload(input.photo, dest_path, filename=filename)
|
||||
|
||||
return await models.Aircraft.create(
|
||||
info.context.db,
|
||||
data=dict(
|
||||
name=input.name,
|
||||
description=input.description,
|
||||
model=input.model,
|
||||
manufacturer=input.manufacturer,
|
||||
photo_filename=filename,
|
||||
organization_id=input.organization_id,
|
||||
created_by_id=info.context.user_id,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class EditAircraftMutation:
|
||||
@strawberry_sqlalchemy_input(models.Aircraft, exclude_fields=['photo_filename'])
|
||||
class EditAircraftInput:
|
||||
photo: Optional[Upload]
|
||||
|
||||
@strawberry.mutation
|
||||
async def edit_aircraft(root, info, id: int, input: EditAircraftInput) -> Aircraft:
|
||||
# TODO: kontrola organizace
|
||||
# TODO: kontrola opravneni na akci
|
||||
return await models.Aircraft.update(
|
||||
info.context.db,
|
||||
id,
|
||||
data=dict(
|
||||
name=input.name,
|
||||
description=input.description,
|
||||
model=input.model,
|
||||
manufacturer=input.manufacturer,
|
||||
organization_id=input.organization_id,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class DeleteAircraftMutation:
|
||||
|
||||
@strawberry.mutation
|
||||
async def delete_aircraft(self, info, id: int) -> Aircraft:
|
||||
# TODO: kontrola opravneni na akci
|
||||
|
||||
return await models.Aircraft.update(info.context.db, id, data=dict(deleted=True))
|
||||
@@ -0,0 +1,17 @@
|
||||
from typing import List
|
||||
import strawberry
|
||||
from sqlalchemy import select
|
||||
from database.models import Copilot
|
||||
from graphql_schema.sqlalchemy_to_strawberry_type import strawberry_sqlalchemy_type
|
||||
|
||||
|
||||
@strawberry_sqlalchemy_type(Copilot)
|
||||
class CopilotType:
|
||||
pass
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class CopilotQueries:
|
||||
@strawberry.field
|
||||
async def pilots(root, info) -> List[CopilotType]:
|
||||
return (await info.context['db'].scalars(select(Copilot))).all()
|
||||
@@ -0,0 +1,67 @@
|
||||
from typing import List, Optional
|
||||
import strawberry
|
||||
from sqlalchemy import select
|
||||
from database import models
|
||||
from graphql_schema.dataloaders import copilots_dataloader
|
||||
from graphql_schema.dataloaders.aircraft import aircraft_dataloader
|
||||
from graphql_schema.entities.aircraft import Aircraft
|
||||
from graphql_schema.entities.copilot import CopilotType
|
||||
from graphql_schema.sqlalchemy_to_strawberry_type import strawberry_sqlalchemy_type, strawberry_sqlalchemy_input
|
||||
|
||||
|
||||
# Bude se hodit: https://strawberry.rocks/docs/types/lazy
|
||||
|
||||
@strawberry_sqlalchemy_type(models.Flight)
|
||||
class Flight:
|
||||
|
||||
async def load_aircraft(root):
|
||||
return await aircraft_dataloader.load(root.aircraft_id)
|
||||
|
||||
async def load_copilot(root):
|
||||
return await copilots_dataloader.load(root.copilot_id)
|
||||
|
||||
copilot: Optional[CopilotType] = strawberry.field(resolver=load_copilot)
|
||||
aircraft: Aircraft = strawberry.field(resolver=load_aircraft)
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class FlightQueries:
|
||||
@strawberry.input
|
||||
class FlightFilters:
|
||||
takeoff: Optional[int]
|
||||
|
||||
@strawberry.field
|
||||
async def flights(root, info, filters: Optional[FlightFilters] = None) -> List[Flight]:
|
||||
query = (
|
||||
select(models.Flight)
|
||||
.filter(models.Flight.created_by_id == info.context.user_id)
|
||||
.order_by(models.Flight.id) # TODO: desc
|
||||
)
|
||||
|
||||
return (await info.context.db.scalars(query)).all()
|
||||
|
||||
@strawberry.field
|
||||
async def flight(root, info, id: int) -> Flight:
|
||||
query = (
|
||||
select(models.Flight)
|
||||
.filter(models.Flight.id == id)
|
||||
.filter(models.Flight.created_by_id == info.context.user_id)
|
||||
)
|
||||
return (await info.context.db.scalars(query)).fetch_one()
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class CreateFlightMutation:
|
||||
@strawberry_sqlalchemy_input(models.Flight, all_optional=True)
|
||||
class FlightInput:
|
||||
pass
|
||||
|
||||
@strawberry.mutation
|
||||
async def create_flight(self, info, input_: FlightInput) -> Flight:
|
||||
model = models.Flight(name=input_.name)
|
||||
|
||||
db = info.context.db
|
||||
db.add(model)
|
||||
await db.commit()
|
||||
|
||||
return Flight(model)
|
||||
@@ -0,0 +1,25 @@
|
||||
import strawberry
|
||||
from sqlalchemy import select
|
||||
from database.models import User
|
||||
from graphql_schema.sqlalchemy_to_strawberry_type import strawberry_sqlalchemy_type
|
||||
|
||||
|
||||
@strawberry_sqlalchemy_type(User, exclude_fields=['password_hashed'])
|
||||
class UserType:
|
||||
pass
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class LoginResultType:
|
||||
logged_user = UserType
|
||||
access_token: str
|
||||
refresh_token: str
|
||||
|
||||
|
||||
@strawberry.type
|
||||
class UserQueries:
|
||||
|
||||
@strawberry.field
|
||||
async def logged_user(root, info) -> UserType:
|
||||
query = select(User).filter_by(id=info.context.user_id)
|
||||
return (await info.context.db.scalars(query)).first()
|
||||
@@ -0,0 +1,10 @@
|
||||
from strawberry.tools import merge_types
|
||||
from graphql_schema.entities.aircraft import CreateAircraftMutation, EditAircraftMutation, DeleteAircraftMutation
|
||||
from graphql_schema.entities.flight import CreateFlightMutation
|
||||
|
||||
Mutation = merge_types("Mutation", (
|
||||
CreateAircraftMutation,
|
||||
EditAircraftMutation,
|
||||
DeleteAircraftMutation,
|
||||
CreateFlightMutation,
|
||||
))
|
||||
@@ -0,0 +1,15 @@
|
||||
from strawberry.tools import merge_types
|
||||
from .entities.aircraft import AircraftQueries
|
||||
from .entities.copilot import CopilotQueries
|
||||
from .entities.flight import FlightQueries
|
||||
from .entities.user import UserQueries
|
||||
|
||||
# https://github.com/strawberry-graphql/examples/blob/main/fastapi-sqlalchemy/api/schema.py
|
||||
|
||||
|
||||
Query = merge_types('Query', (
|
||||
AircraftQueries,
|
||||
FlightQueries,
|
||||
CopilotQueries,
|
||||
UserQueries
|
||||
))
|
||||
@@ -0,0 +1,42 @@
|
||||
import dataclasses
|
||||
import strawberry
|
||||
from fastapi_jwt import JwtAuthorizationCredentials
|
||||
from fastapi_jwt.jwt import JwtAccessBearerCookie
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from strawberry.extensions import SchemaExtension
|
||||
from strawberry.fastapi import BaseContext
|
||||
from .mutation import Mutation
|
||||
from .query import Query
|
||||
|
||||
|
||||
# Toto se da kdyztak pouzit jako extension do Schema
|
||||
# class SQLAlchemySession(Extension):
|
||||
# def on_request_start(self):
|
||||
# session = async_session()
|
||||
# print(self.execution_context.context)
|
||||
# self.execution_context.context["db"] = session
|
||||
#
|
||||
# async def on_request_end(self):
|
||||
# await self.execution_context.context["db"].close()
|
||||
|
||||
class LoggingExtension(SchemaExtension):
|
||||
def on_request_start(self):
|
||||
print("request start")
|
||||
|
||||
async def on_request_end(self):
|
||||
print("request end")
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class GraphQLContext(BaseContext):
|
||||
db: AsyncSession
|
||||
user_id: int
|
||||
jwt_auth_credentials: JwtAuthorizationCredentials
|
||||
jwt: JwtAccessBearerCookie
|
||||
|
||||
|
||||
schema = strawberry.Schema(
|
||||
query=Query,
|
||||
mutation=Mutation,
|
||||
extensions=[LoggingExtension]
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
import typing
|
||||
from typing import List, Optional
|
||||
import strawberry
|
||||
from sqlalchemy import inspect
|
||||
from database.models import BaseModel
|
||||
|
||||
|
||||
def get_annotations_for_scalars(model: BaseModel, exclude_fields=None, force_optional: bool = False):
|
||||
if exclude_fields is None:
|
||||
exclude_fields = []
|
||||
|
||||
annotations_ = {}
|
||||
for name, column in inspect(model).columns.items():
|
||||
is_optional = column.nullable or force_optional
|
||||
if name in exclude_fields:
|
||||
continue
|
||||
annotations_[name] = column.type.python_type if not is_optional else typing.Optional[column.type.python_type]
|
||||
|
||||
return annotations_
|
||||
|
||||
|
||||
def strawberry_sqlalchemy_type(model, exclude_fields: Optional[typing.Union[List, typing.Tuple]] = None):
|
||||
if exclude_fields is None:
|
||||
exclude_fields = []
|
||||
|
||||
def from_sqlalchemy_model(model: BaseModel):
|
||||
return model
|
||||
|
||||
def wrapper(cls):
|
||||
cls.__annotations__.update(get_annotations_for_scalars(model, exclude_fields=exclude_fields + ["deleted"]))
|
||||
cls.from_sqlalchemy_model = from_sqlalchemy_model
|
||||
return strawberry.type(cls)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def strawberry_sqlalchemy_input(
|
||||
model,
|
||||
exclude_fields: Optional[typing.Union[List, typing.Tuple]] = None,
|
||||
all_optional: bool = False):
|
||||
if exclude_fields is None:
|
||||
exclude_fields = []
|
||||
|
||||
ignored_fields = ["created_at", "created_by_id", "updated_by_id", "updated_at", "deleted"]
|
||||
|
||||
def wrapper(cls):
|
||||
cls.__annotations__.update(get_annotations_for_scalars(
|
||||
model,
|
||||
exclude_fields=exclude_fields + ignored_fields,
|
||||
force_optional=all_optional
|
||||
))
|
||||
return strawberry.input(cls)
|
||||
|
||||
return wrapper
|
||||
Reference in New Issue
Block a user