blob: 3472fd0e5c58e4847c3df69b797b01213ea4262d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
import { useEffect, useState } from 'react'
import { fetchDrupalResource } from './lib/drupalClient'
import './App.css'
type DrupalArticle = {
id: string
attributes?: {
title?: string
status?: boolean
created?: string
}
}
type DrupalCollectionResponse<T> = {
data: T[]
}
type DrupalJsonApiEntryPoint = {
links: Record<string, { href: string }>
}
function App() {
const [articles, setArticles] = useState<DrupalArticle[]>([])
const [resourcePath, setResourcePath] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const loadArticles = async () => {
try {
setIsLoading(true)
setError(null)
const entryPoint = await fetchDrupalResource<DrupalJsonApiEntryPoint>('')
const nodeResources = Object.keys(entryPoint.links).filter((key) => key.startsWith('node--'))
if (nodeResources.length === 0) {
throw new Error('No node resources found in JSON:API. Create a content type (for example Article) and ensure JSON:API is enabled.')
}
const selectedNodeResource = nodeResources.includes('node--article') ? 'node--article' : nodeResources[0]
const selectedPath = `/${selectedNodeResource.replace('--', '/')}`
setResourcePath(selectedPath)
const response = await fetchDrupalResource<DrupalCollectionResponse<DrupalArticle>>(selectedPath)
setArticles(response.data)
} catch (loadError) {
const message = loadError instanceof Error ? loadError.message : 'Failed to load articles from Drupal.'
setError(message)
} finally {
setIsLoading(false)
}
}
void loadArticles()
}, [])
return (
<main>
<h1 className="mb-4 text-2xl font-bold">Articles</h1>
{!isLoading && !error && resourcePath && <p>Using resource: {resourcePath}</p>}
{isLoading && <p>Loading articles…</p>}
{error && (
<p role="alert" className="text-red-600">
Could not fetch articles: {error}
</p>
)}
{!isLoading && !error && articles.length === 0 && (
<p>Connected to Drupal, but no articles were returned.</p>
)}
{!isLoading && !error && articles.length > 0 && (
<ul style={{ textAlign: 'left' }}>
{articles.map((article) => (
<li key={article.id}>
<strong>{article.attributes?.title ?? '(Untitled)'}</strong>
<div>ID: {article.id}</div>
<div>Status: {article.attributes?.status ? 'Published' : 'Unpublished'}</div>
{article.attributes?.created && <div>Created: {new Date(article.attributes.created).toLocaleString()}</div>}
</li>
))}
</ul>
)}
</main>
)
}
export default App
|