-
-
Save jonathanhudak/149c525d7addf1152851cc39fd1faabd to your computer and use it in GitHub Desktop.
Strapi Deno example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="https://deno.land/x/deploy@0.2.0/types/deploy.ns.d.ts" /> | |
/// <reference path="https://deno.land/x/deploy@0.2.0/types/deploy.fetchevent.d.ts" /> | |
/// <reference path="https://deno.land/x/deploy@0.2.0/types/deploy.window.d.ts" /> | |
import * as React from "https://esm.sh/react@17.0.2"; | |
import * as ReactDOMServer from "https://esm.sh/react-dom@17.0.2/server"; | |
import { createElement as h } from "https://esm.sh/react@17.0.2"; | |
// @ts-ignore VSCode occasionally complains that Deno is not defined. | |
const STRAPI_API_URL = Deno.env.get("STRAPI_API_URL") || | |
"http://localhost:1337"; | |
interface Package { | |
name: string; | |
description: string; | |
github: string; | |
stars: number; | |
} | |
interface Props { | |
data: Package[]; | |
} | |
function App({ data }: Props) { | |
return ( | |
<html lang="en"> | |
<head> | |
<meta charSet="utf-8" /> | |
<link | |
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" | |
rel="stylesheet" | |
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" | |
crossOrigin="anonymous" | |
/> | |
<title>Hello from JSX</title> | |
</head> | |
<body> | |
<div className="container"> | |
<h1>Hello, World!</h1> | |
<table className="table"> | |
<thead> | |
<tr> | |
<th scope="col">Name</th> | |
<th scope="col">Description</th> | |
<th scope="col">Stars</th> | |
<th scope="col">URL</th> | |
</tr> | |
</thead> | |
<tbody> | |
{data.map((pkg: Package) => ( | |
<tr> | |
<th scope="row">{pkg.name}</th> | |
<td>{pkg.description}</td> | |
<td>{pkg.stars}</td> | |
<td> | |
<a href={pkg.github}>{pkg.github}</a> | |
</td> | |
</tr> | |
))} | |
</tbody> | |
</table> | |
</div> | |
</body> | |
</html> | |
); | |
} | |
async function getData(path: string) { | |
const url = `${STRAPI_API_URL}${path}`; | |
const response = await fetch(url, { | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
}); | |
return response.json(); | |
} | |
addEventListener("fetch", async (event: FetchEvent) => { | |
// Fetch data. | |
const data = await getData("/packages"); | |
// Render React components to a string. | |
const str = ReactDOMServer.renderToString(<App data={data} />); | |
// Prepend the DOCTYPE for better compatibility. | |
const body = `<!DOCTYPE html>${str}`; | |
const response = new Response(body, { | |
headers: { "content-type": "text/html; charset=utf-8" }, | |
}); | |
event.respondWith(response); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment