From 7e40aa188979311e706154dfcf52e47975f99cde Mon Sep 17 00:00:00 2001 From: Elad Rosenheim Date: Tue, 23 Apr 2024 17:55:24 +0300 Subject: Revalidation & Blobs pages, tweaks (#8) * added blobs.astro page * updated blobs * updated index.astro and npm dependencies * updated api blobs * Revalidation example WIP * Revalidation by tag example * Update revalidation.astro * Image CDN fixes * Text fixes * updated colors (#9) * updated colors * updated README.md * updated Layout.astro bg color * updated template colors * Inline Inter font * Inline noise.png * Remove remaining "Astro.js" --------- Co-authored-by: TomasBankauskas --- src/pages/api/blob.ts | 20 +++++++ src/pages/api/blobs.ts | 27 ++++++++++ src/pages/api/revalidate.ts | 19 +++++++ src/pages/blobs.astro | 8 --- src/pages/blobs/_components/NewShape.tsx | 60 +++++++++++++++++++++ src/pages/blobs/_components/ShapeEditor.tsx | 18 +++++++ src/pages/blobs/_components/ShapePreview.tsx | 19 +++++++ src/pages/blobs/_components/StoredShapes.tsx | 78 ++++++++++++++++++++++++++++ src/pages/blobs/index.astro | 18 +++++++ src/pages/edge/index.astro | 2 +- src/pages/image-cdn.astro | 39 ++++++++------ src/pages/index.astro | 16 ++++-- src/pages/revalidation.astro | 61 ++++++++++++++++++++++ 13 files changed, 356 insertions(+), 29 deletions(-) create mode 100644 src/pages/api/blob.ts create mode 100644 src/pages/api/blobs.ts create mode 100644 src/pages/api/revalidate.ts delete mode 100644 src/pages/blobs.astro create mode 100644 src/pages/blobs/_components/NewShape.tsx create mode 100644 src/pages/blobs/_components/ShapeEditor.tsx create mode 100644 src/pages/blobs/_components/ShapePreview.tsx create mode 100644 src/pages/blobs/_components/StoredShapes.tsx create mode 100644 src/pages/blobs/index.astro create mode 100644 src/pages/revalidation.astro (limited to 'src/pages') diff --git a/src/pages/api/blob.ts b/src/pages/api/blob.ts new file mode 100644 index 0000000..4ff37c4 --- /dev/null +++ b/src/pages/api/blob.ts @@ -0,0 +1,20 @@ +import type { APIRoute } from 'astro'; +import { getStore } from '@netlify/blobs'; + +export const prerender = false; + +export const GET: APIRoute = async (context) => { + const urlParams = new URL(context.url); + const key = urlParams.searchParams.get('key'); + if (!key) { + return new Response('Bad Request', { status: 400 }); + } + + const blobStore = getStore('shapes'); + const blob = await blobStore.get(key, { type: 'json' }); + return new Response( + JSON.stringify({ + blob + }) + ); +}; diff --git a/src/pages/api/blobs.ts b/src/pages/api/blobs.ts new file mode 100644 index 0000000..d11aa58 --- /dev/null +++ b/src/pages/api/blobs.ts @@ -0,0 +1,27 @@ +import type { APIRoute } from 'astro'; +import { getStore } from '@netlify/blobs'; + +export const prerender = false; + +export const POST: APIRoute = async ({ request }) => { + const parameters = await request.json(); + const blobStore = getStore('shapes'); + const key = parameters.name; + await blobStore.setJSON(key, parameters); + return new Response( + JSON.stringify({ + message: `Stored shape "${key}"` + }) + ); +}; + +export const GET: APIRoute = async ({ request }) => { + const blobStore = getStore({ name: 'shapes', consistency: 'strong' }); + const data = await blobStore.list(); + const keys = data.blobs.map(({ key }) => key); + return new Response( + JSON.stringify({ + keys + }) + ); +}; diff --git a/src/pages/api/revalidate.ts b/src/pages/api/revalidate.ts new file mode 100644 index 0000000..0d953a3 --- /dev/null +++ b/src/pages/api/revalidate.ts @@ -0,0 +1,19 @@ +import type { APIRoute } from 'astro'; +import { purgeCache } from '@netlify/functions'; + +export const prerender = false; + +export const POST: APIRoute = async ({ request }) => { + const { tags } = await request.json(); + + if (!Array.isArray(tags)) { + return new Response(`Bad Request: expected tags attribute with array of strings in the body, got ${typeof tags}`, { status: 400 }); + } + + await purgeCache({ tags }); + return new Response( + JSON.stringify({ + invalidated: tags + }) + ); +}; diff --git a/src/pages/blobs.astro b/src/pages/blobs.astro deleted file mode 100644 index 2884c4a..0000000 --- a/src/pages/blobs.astro +++ /dev/null @@ -1,8 +0,0 @@ ---- -import Layout from "../layouts/Layout.astro"; ---- - - -

Blobs x Blobs

-

Get started with Astro.js and Netlify in seconds.

-
diff --git a/src/pages/blobs/_components/NewShape.tsx b/src/pages/blobs/_components/NewShape.tsx new file mode 100644 index 0000000..05f9e6f --- /dev/null +++ b/src/pages/blobs/_components/NewShape.tsx @@ -0,0 +1,60 @@ +import { useState, useEffect } from 'react'; +import type { Dispatch, SetStateAction } from 'react'; +import ShapePreview from './ShapePreview.tsx'; +import { generateBlob } from '../../../utils'; +import type { BlobProps } from '../../../types.ts'; + +interface Props { + setLastMutationTime?: Dispatch>; +} + +export default function NewShape(props: Props) { + const { setLastMutationTime } = props; + const [blobData, setBlobData] = useState(); + const [wasUploaded, setWasUploaded] = useState(false); + + const randomizeBlob = () => { + setBlobData(generateBlob()); + setWasUploaded(false); + }; + + const uploadBlob = async () => { + const response = await fetch('/api/blobs', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(blobData.parameters) + }); + const data = await response.json(); + if (data.message) { + console.log(data.message); + } + setWasUploaded(true); + setLastMutationTime(Date.now()); + }; + + useEffect(() => { + if (!blobData) { + randomizeBlob(); + } + }, [blobData]); + + return ( + <> +

New Random Shape

+
+
+ {blobData && {blobData.parameters?.name}} +
+
{blobData && }
+
+
+ + +
+ + ); +} diff --git a/src/pages/blobs/_components/ShapeEditor.tsx b/src/pages/blobs/_components/ShapeEditor.tsx new file mode 100644 index 0000000..9a339cc --- /dev/null +++ b/src/pages/blobs/_components/ShapeEditor.tsx @@ -0,0 +1,18 @@ +import { useState } from 'react'; +import NewShape from './NewShape.tsx'; +import StoredShapes from './StoredShapes.tsx'; + +export default function ShapeEditor() { + const [lastMutationTime, setLastMutationTime] = useState(null); + + return ( +
+
+ +
+
+ +
+
+ ); +} diff --git a/src/pages/blobs/_components/ShapePreview.tsx b/src/pages/blobs/_components/ShapePreview.tsx new file mode 100644 index 0000000..a00d2bc --- /dev/null +++ b/src/pages/blobs/_components/ShapePreview.tsx @@ -0,0 +1,19 @@ +import { randomInt } from '../../../utils.ts'; +import type { BlobProps } from '../../../types.ts'; + +export default function ShapePreview(props: BlobProps) { + const { svgPath, parameters } = props; + const gradientId = `gradient-${randomInt(10_000_000, 100_000_000)}`; + + return ( + + + + + + + + + + ); +} diff --git a/src/pages/blobs/_components/StoredShapes.tsx b/src/pages/blobs/_components/StoredShapes.tsx new file mode 100644 index 0000000..e870ef5 --- /dev/null +++ b/src/pages/blobs/_components/StoredShapes.tsx @@ -0,0 +1,78 @@ +import { useState, useEffect } from 'react'; +import ShapePreview from './ShapePreview.tsx'; +import { generateBlob } from '../../../utils'; +import type { BlobProps } from '../../../types.ts'; + +interface Props { + lastMutationTime: number; +} + +export default function StoredShapes(props: Props) { + const { lastMutationTime } = props; + const [keys, setKeys] = useState([]); + const [selectedKey, setSelectedKey] = useState(null); + const [previewData, setPreviewData] = useState(null); + + const getBlobKeyList = async () => { + console.log('Fetching keys...'); + const response = await fetch('/api/blobs', { + method: 'GET', + headers: { 'Content-Type': 'application/json' } + }); + const data = await response.json(); + if (data.keys) { + setKeys(data.keys); + } + }; + + const getBlobByKey = async (key: string) => { + setSelectedKey(key); + const params = new URLSearchParams({ key }); + const response = await fetch(`/api/blob/?${params}`, { + method: 'GET' + }); + const data = await response.json(); + if (data.blob) { + setPreviewData(generateBlob(data.blob)); + } + }; + + useEffect(() => { + getBlobKeyList(); + }, [lastMutationTime]); + + return ( + <> +

Objects in Blob Store

+
+
+ {keys?.length ? ( +
+ {keys.map((keyName) => ( + + ))} +
+ ) : ( + Please upload some shapes! + )} +
+ {previewData && ( +
+ +
+ )} +
+ + ); +} diff --git a/src/pages/blobs/index.astro b/src/pages/blobs/index.astro new file mode 100644 index 0000000..5630d6b --- /dev/null +++ b/src/pages/blobs/index.astro @@ -0,0 +1,18 @@ +--- +import Layout from '../../layouts/Layout.astro'; +import Markdown from '../../components/Markdown.astro'; +import ShapeEditor from './_components/ShapeEditor.tsx'; + +const explainer = ` +[Netlify Blobs](https://docs.netlify.com/blobs/overview/) provides an object store for any kind of data, be it JSON, binary, +or [really](https://mk.gg/projects/chalkstream) anything else ([really!](https://mk.gg/projects/turbofan)). In this example, the blob store is used to **hold the data of user-generated random blobby shapes**. + +Below is an Astro island with a React component for editing, uploading and viewing blobs to the blob store 🙂. +`; +--- + + +

Blobs x Blobs

+ + +
diff --git a/src/pages/edge/index.astro b/src/pages/edge/index.astro index f49f3a9..8bf4a85 100644 --- a/src/pages/edge/index.astro +++ b/src/pages/edge/index.astro @@ -9,7 +9,7 @@ This page is using a [Netlify Edge Function](https://docs.netlify.com/edge-funct For it to be invoked, please either run this site locally with \`netlify dev\` or deploy it to Netlify. -Edge Functions are framework-agnostic, but are also used behind the scenes to run Next.js Middleware on Netlify. +Edge Functions are framework-agnostic, but are also used behind the scenes to run Astro Middleware on Netlify. There are advatanges to using Edge Functions directly, such as the ability to access & transform the response body. [See more examples](https://edge-functions-examples.netlify.app) diff --git a/src/pages/image-cdn.astro b/src/pages/image-cdn.astro index 8847536..dbb8822 100644 --- a/src/pages/image-cdn.astro +++ b/src/pages/image-cdn.astro @@ -10,18 +10,25 @@ const sampleImage = '/images/corgi.jpg'; const ctx = getNetlifyContext(); const forceWebP = ctx === 'dev'; -const sampleImageNetlify = `/.netlify/images?url=${sampleImage}${forceWebP ? '&fm=webp' : ''}`; +const sampleImageSrcSet = [640, 1280, 2048] + .map((size) => { + return `/.netlify/images?url=${sampleImage}&w=${size}${forceWebP ? '&fm=webp' : ''} ${size}w`; + }) + .join(', '); +const sizes = '(max-width: 1024px) 100vw, 1024px'; const astroImageSnippet = ` -## Using built-in Astro <Image /> component +## Using the built-in Astro <Image /> component -When running on Netlify, \`next/image\` is automatically set-up to use Netlify Image CDN for optimized images. +Astro's \`Image\` component will automatically use Netlify Image CDN to serve optimized images. ~~~jsx -import Image from 'next/image'; - -// In your component -Corgi +--- +import { Image } from 'astro:assets'; +import corgi from '../assets/corgi.jpg'; +--- +// Later in your markup... +Corgi ~~~ `; @@ -29,7 +36,7 @@ const originalVsCdnSnippet = ` ## Original vs. optimized image: can you tell the difference? In the code below, a regular \`\` tag is used in both cases for a framework-agnostic example. -Other than using \`next/image\` or rolling your own \`\` tags, you can also use the excellent [unpic-img](https://unpic.pics/). +Note that aside from Astro's \`Image\` or rolling your own \`\` tags, you can also use the excellent [unpic-img](https://unpic.pics/) package. ~~~jsx // <== On the left, the original image @@ -37,8 +44,8 @@ Other than using \`next/image\` or rolling your own \`\` tags, you can also // ==> On the right, explicitly using Netlify Image CDN endpoint for a responsive image Corgi ~~~ @@ -53,11 +60,11 @@ detection, so format is set to WebP.
- { - return ctx === "dev" ? devModeWarning : null; - } - } /> + { + return ctx === 'dev' ? devModeWarning : null; + }} + />

Image CDN

@@ -77,7 +84,7 @@ detection, so format is set to WebP.
- Corgi + Corgi
diff --git a/src/pages/index.astro b/src/pages/index.astro index 8955471..6e73e14 100644 --- a/src/pages/index.astro +++ b/src/pages/index.astro @@ -1,13 +1,21 @@ --- import Layout from '../layouts/Layout.astro'; -import Card from '../components/Card.astro'; +import ContextAlert from '../components/ContextAlert.astro'; +import Markdown from '../components/Markdown.astro'; + +const explainer = ` +An Astro website can go way beyond static pages - on the right platform. + +Netlify supports not only [Streaming SSR](https://docs.astro.build/en/guides/server-side-rendering/) and fast [Edge Middleware](https://docs.astro.build/en/guides/middleware/), but also [on-demand revalidation](https://www.netlify.com/blog/cache-tags-and-purge-api-on-netlify/) and [stale-while-revalidate](https://www.netlify.com/blog/swr-and-fine-grained-cache-control/). +Any page or data can be rebuilt only when needed, without site visitors ever getting a performance hit. +`; --- -

Netlify Platform Starter - Astro.js

-

Get started with Astro.js and Netlify in seconds.

+ +

Netlify Platform Starter for Astro

+

Read the Docs

-
diff --git a/src/pages/revalidation.astro b/src/pages/revalidation.astro new file mode 100644 index 0000000..f7d4f6e --- /dev/null +++ b/src/pages/revalidation.astro @@ -0,0 +1,61 @@ +--- +import Layout from '../layouts/Layout.astro'; +import ContextAlert from '../components/ContextAlert.astro'; +import Markdown from '../components/Markdown.astro'; +import { cacheHeaders, randomInt } from '../utils'; + +export const prerender = false; + +const tags = ['/revalidation', 'cats-related', 'all-pets-related']; +const headers = cacheHeaders(365, tags); + +Object.entries(headers).map(([k, v]) => { + Astro.response.headers.set(k, v); +}); + +const explainer = ` +This is a server-rendered page, last created at \`${new Date().toUTCString()}\` with a few extra response headers: + +~~~js +${JSON.stringify(headers, null, 2)} +~~~ + +Meaning: **for browsers,** this is a non-cacheable page. At the **CDN level,** it *is* cacheable for up to a year (and Netlify also automatically busts the cache on new deployments, by default). + +But there's something more: the \`Cache-Tag\` header, in tandem with the [purge API](https://docs.netlify.com/platform/caching/#on-demand-invalidation), allows a developer to invalidate at will any +pieces of content (pages, JSON responses, or whatnot) based on the tags associated with them. Tags are completely up to you to decide on, and allow for very powerful patterns. + +In real-world applications, you may want to use [stale-while-revalidate](https://docs.netlify.com/platform/caching/#stale-while-revalidate-directive) as well, so that end-users don't experience +a performance hit as pages are being rebuilt. + +Use the button below to invlidate a random tag out of this page's tags, then refresh the page. +`; + +const exampleTag = tags[randomInt(0, tags.length - 1)]; +--- + + +

Revalidating Server Content

+ + + +
+ + -- cgit v1.2.3