RPC for Service Workers -- move that heavy computation off of your UI thread!
npm add swarpc arktype
import type { ProceduresMap } from "swarpc"
import { type } from "arktype"
export const procedures = {
searchIMDb: {
// Input for the procedure
input: type({ query: "string", "pageSize?": "number" }),
// Function to be called whenever you can update progress while the procedure is running -- long computations are a first-class concern here. Examples include using the fetch-progress NPM package.
progress: type({ transferred: "number", total: "number" }),
// Output of a successful procedure call
success: type({
id: "string",
primary_title: "string",
genres: "string[]",
}).array(),
},
} as const satisfies ProceduresMap
In your service worker file:
import fetchProgress from "fetch-progress"
import { Server } from "swarpc"
import { procedures } from "./procedures.js"
// 1. Give yourself a server instance
const swarpc = Server(procedures)
// 2. Implement your procedures
swarpc.searchIMDb(async ({ query, pageSize = 10 }, onProgress) => {
const queryParams = new URLSearchParams({
page_size: pageSize.toString(),
query,
})
return fetch(`https://rest.imdbapi.dev/v2/search/titles?${queryParams}`)
.then(fetchProgress({ onProgress }))
.then((response) => response.json())
.then(({ titles } => titles)
})
// ...
// 3. Start the event listener
swarpc.start(self)
Here's a Svelte example!
{#if progress > 0 && progress < 1}
{/if}
{#each results as { id, primary_title, genres } (id)}
- {primary_title} - {genres.join(", ")}
{/each}