Cоздадим схему GraphQL, используя Graphene-Django. В том числе создадаим запросы для извлечения данных (аналог GET в REST) и мутации для их обновления/создания (аналог PUT/POST в REST).
pip install graphene-django
INSTALLED_APPS += [
...
'graphene_django',
]
GRAPHENE = {
'SCHEMA': '<your_project>.schema.schema',
}
class SectionType(DjangoObjectType):
class Meta:
model = Section
fields = ('id', 'title', 'description', 'location', 'date', 'instructor', 'duration', 'imageUrl')
class Query(graphene.ObjectType):
section = graphene.Field(SectionType, id=graphene.Int(required=True))
def resolve_section(self, info, id):
return Section.objects.get(pk=id)
class CreateSection(graphene.Mutation):
class Arguments:
title = graphene.String(required=True)
section = graphene.Field(SectionType)
def mutate(self, info, title):
section = Section.objects.create(title=title)
section.save()
return CreateSection(section=section)
class Mutation(graphene.ObjectType):
create_section = CreateSection.Field()
schema = graphene.Schema(query=Query, mutation=Mutation)
from graphene_django.views import GraphQLView
from django.urls import path
urlpatterns = [
path("graphql", GraphQLView.as_view(graphiql=True)),
]
Напишем GQL для запросов и мутаций и заменим им axios.
npm install @apollo/client graphql
import { gql } from '@apollo/client';
export const FETCH_SECTION = gql`
query FetchSection($id: Int!) {
section(id: $id) {
id
title
description
location
date
instructor
duration
imageUrl
}
}
`;
export const CREATE_SECTION = gql`
mutation CreateSection($title: String!) {
createSection(title: $title) {
section {
id
title
description
location
date
instructor
duration
imageUrl
}
}
}
`;
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { FETCH_SECTION, CREATE_SECTION } from './graphql';
const client = new ApolloClient({
uri: '/graphql',
cache: new InMemoryCache(),
});
export const fetchSection = createAsyncThunk(
'section/fetchSection',
async (sectionId: number, { rejectWithValue }) => {
try {
const response = await client.query({
query: FETCH_SECTION,
variables: { id: sectionId },
});
return response.data.section;
} catch {
return rejectWithValue('Не удалось получить секцию по id')
}
}
);
export const createSection = createAsyncThunk(
'section/createSection',
async (title: string, { rejectWithValue }) => {
try {
const response = await client.mutate({
mutation: CREATE_SECTION,
variables: { title: title }
});
return response.data.createSection.section;
} catch {
return rejectWithValue('Не удалось создать секцию')
}
}
);