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

refactor(injection): move serlo code back to editor & add server endpoint for fetch #4192

Merged
merged 2 commits into from
Oct 17, 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
205 changes: 205 additions & 0 deletions apps/web/src/pages/api/frontend/injection-content.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { EditorPluginType } from '@editor/package'
import { parseDocumentString } from '@editor/static-renderer/helper/parse-document-string'
import { EditorExerciseGroupDocument } from '@editor/types/editor-plugins'
import { gql } from 'graphql-request'
import type { NextApiRequest, NextApiResponse } from 'next'

import { endpoint } from '@/api/endpoint'
import { InjectionOnlyContentQuery } from '@/fetcher/graphql-types/operations'

/**
* Allows frontend (and later other) instances to get content of injected entity
* needs cors to work in other instances
*/
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const path = decodeURIComponent(String(req.query.path))
const hash = decodeURIComponent(String(req.query.hash))
if (!path) {
return res.status(401).send('no path provided')
}

try {
void fetch(endpoint, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
method: 'POST',

body: JSON.stringify({
query,
variables: { path },
}),
})
.then((res) => res.json())
.then((data: { data: InjectionOnlyContentQuery }) => {
if (!data.data?.uuid) {
return res.status(404).send('not found')
}

const uuid = data.data.uuid
if (
uuid.__typename === 'Article' ||
uuid.__typename === 'Course' ||
uuid.__typename === 'TaxonomyTerm'
) {
if (!uuid.alias) {
return res.status(404).send('something is wrong with the content')
}
respondWithContent([createFallbackBox(uuid.alias, uuid.title)])
return
}

if (!Object.hasOwn(uuid, 'currentRevision') || !uuid.currentRevision) {
return res.status(404).send('no current revision')
}

if (uuid.__typename === 'Exercise') {
const serloContext = {
licenseId: uuid.licenseId,
uuid: uuid.id,
}
respondWithContent([
{ ...JSON.parse(uuid.currentRevision.content), serloContext },
])
return
}

if (uuid.__typename === 'ExerciseGroup') {
const content = parseDocumentString(
uuid.currentRevision.content
) as EditorExerciseGroupDocument

// use id in hash to load one exercise out of the group
if (hash) {
const exercise = content.state.exercises.find((exercise) =>
exercise.id?.startsWith(hash)
)
if (exercise) {
respondWithContent([exercise])
return
}
}
const contentWithLicenseId = {
...content,
state: {
...content.state,
serloContext: { licenseId: uuid.licenseId },
},
}
respondWithContent([contentWithLicenseId])
return
}

if (uuid.__typename === 'Video') {
const state = {
plugin: EditorPluginType.Video,
state: {
src: uuid.currentRevision.url,
alt: uuid.title ?? 'video',
},
}
respondWithContent([state])
return
}

if (uuid.__typename === 'Applet') {
respondWithContent([
{
plugin: EditorPluginType.Geogebra,
state: uuid.currentRevision.url,
},
parseDocumentString(uuid.currentRevision.content),
])
return
}

if (uuid.__typename === 'Event') {
respondWithContent([
parseDocumentString(uuid.currentRevision.content),
])
return
}
return res.status(422).send('unknown entity type')
})
.catch((e) => {
return res.status(500).send(`${String(e)} at ${path}`)
})
} catch (e) {
return res.status(500).send(`${String(e)} at ${path}`)
}

function respondWithContent(content: any) {
const twoDaysInSeconds = 172800
res.setHeader('Cache-Control', `maxage=${twoDaysInSeconds}`)
res.status(200).json(content)
}
}

const query = gql`
query injectionOnlyContent($path: String!) {
uuid(alias: { path: $path, instance: de }) {
__typename
alias
title

... on AbstractEntity {
id
currentRevision {
content
}
licenseId
}

... on Video {
currentRevision {
url
}
}
... on Applet {
currentRevision {
url
}
}
}
}
`

function createFallbackBox(alias: string, title: string) {
return {
plugin: EditorPluginType.Rows,
state: [
{
plugin: EditorPluginType.Box,
state: {
type: 'blank',
title: { plugin: EditorPluginType.Text },
anchorId: '',
content: {
plugin: EditorPluginType.Rows,
state: [
{
plugin: EditorPluginType.Text,
state: [
{
type: 'p',
children: [
{
type: 'a',
href: alias,
children: [{ text: title, strong: true }],
},
],
},
],
},
],
},
},
},
],
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEditStrings } from '@editor/i18n/edit-strings-provider'
import { SerloAddButton } from '@editor/plugin/helpers/serlo-editor-button'
import { InjectionStaticRenderer } from '@editor/plugins/injection/static'
import { EditorPluginType } from '@editor/types/editor-plugin-type'
import { gql } from 'graphql-request'

Expand All @@ -13,7 +14,6 @@ import {
} from '@/fetcher/graphql-types/operations'
import { getTranslatedType } from '@/helper/get-translated-type'
import { getIconByTypename } from '@/helper/icon-by-entity-type'
import { InjectionSerloStaticRenderer } from '@/serlo-editor-integration/serlo-plugin-wrappers/injection-serlo-static-renderer'

interface ArticleRelatedExercisesProps {
exerciseFolderId: number
Expand Down Expand Up @@ -78,7 +78,7 @@ export function ArticleRelatedExercises({

return (
<div key={id} className="my-5 border-t-2 border-black py-5">
<InjectionSerloStaticRenderer
<InjectionStaticRenderer
plugin={EditorPluginType.Injection}
state={`/${id}`}
/>
Expand Down
10 changes: 5 additions & 5 deletions apps/web/src/serlo-editor-integration/create-renderers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ const BlanksExerciseStaticRenderer = dynamic<EditorBlanksExerciseDocument>(() =>
(mod) => mod.BlanksExerciseStaticRenderer
)
)
const InjectionSerloStaticRenderer = dynamic<EditorInjectionDocument>(() =>
import(
'@/serlo-editor-integration/serlo-plugin-wrappers/injection-serlo-static-renderer'
).then((mod) => mod.InjectionSerloStaticRenderer)
const InjectionStaticRenderer = dynamic<EditorInjectionDocument>(() =>
import('@editor/plugins/injection/static').then(
(mod) => mod.InjectionStaticRenderer
)
)

const DropzoneImageStaticRenderer = dynamic<
Expand Down Expand Up @@ -164,7 +164,7 @@ export function createRenderers(): InitRenderersArgs {
if (!props.state) return null
return (
<Lazy>
<InjectionSerloStaticRenderer {...props} />
<InjectionStaticRenderer {...props} />
<ExtraInfoIfRevisionView>{props.state}</ExtraInfoIfRevisionView>
</Lazy>
)
Expand Down
Loading