Skip to content

Instantly share code, notes, and snippets.

@Symbitic
Created July 30, 2021 13:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Symbitic/aee01de4d0ef9b2e44b550b59a132ed8 to your computer and use it in GitHub Desktop.
Save Symbitic/aee01de4d0ef9b2e44b550b59a132ed8 to your computer and use it in GitHub Desktop.
Strapi Deno example.
/// <reference path="https://raw.githubusercontent.com/denoland/deployctl/main/types/deploy.fetchevent.d.ts" />
/// <reference path="https://raw.githubusercontent.com/denoland/deployctl/main/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