239
240 // Inject data to avoid extra round-trips
241 const initialData = await fetchInitialData();
242 const dataScript = `<script>
243 window.__INITIAL_DATA__ = ${JSON.stringify(initialData)};
286
2875. **API Design:**
288 - `fetch` handler is the entry point for HTTP vals
289 - Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
290
291
105
106Writing a proxy in Val Town (or any functions platform with the
107['fetch handler' interface](https://blog.val.town/blog/the-api-we-forgot-to-name/))
108is a delight:
109
112export async function proxy(req: Request): Promise<Response> {
113 const url = new URL(req.url);
114 return fetch(OLD_BLOG_HOST + url.pathname + url.search, {
115 method: req.method,
116 headers: req.headers,
30 setIsLoading(true);
31 try {
32 const response = await fetch('/api/artworks/my');
33 const data = await response.json();
34
83 const thumbnail = generateThumbnail(currentCanvas);
84
85 const response = await fetch('/api/artworks', {
86 method: 'POST',
87 headers: { 'Content-Type': 'application/json' },
144
145 try {
146 const response = await fetch(`/api/artworks/${artworkId}`, {
147 method: 'DELETE'
148 });
31 : formData;
32
33 const response = await fetch(endpoint, {
34 method: 'POST',
35 headers: { 'Content-Type': 'application/json' },
51 const handleLogout = useCallback(async () => {
52 try {
53 await fetch('/api/auth/logout', { method: 'POST' });
54 setAppState(prev => ({ ...prev, user: undefined }));
55 // Reload page to clear any cached data
6 app.get("/", () => serveFile("/index.html", importMetaURL));
7 app.get("/**/*", c => serveFile(c.req.path, importMetaURL));
8 return app.fetch;
9}
1export {
2 fetchTranspiledJavaScript,
3 listFiles,
4 readFile,
8 let text;
9 try {
10 text = await fetchTranspiledJavaScript(esmURL);
11 } catch (err) {
12 throw new Error("Failed to fetch file " + esmURL);
13 }
14 return text;
35}
36
37export async function fetchTranspiledJavaScript(url: string) {
38 if (!url.startsWith("https://esm.town")) throw Error("Can only fetch from https://esm.town");
39 const res = await fetch(url, {
40 headers: {
41 // Always transpile TS to JS
46 });
47 if (!res.ok) {
48 throw new Error("Failed to fetch " + url);
49 }
50 return await res.text();
1import { fetchText } from "https://esm.town/v/stevekrouse/fetchText@6-main/main.tsx";
2import { parseProject } from "https://esm.town/v/std/utils@71-main/index.ts";
3import remarkFrontmatter from "npm:remark-frontmatter";
22 let text;
23 try {
24 text = await fetchText(esmURL);
25 } catch (_err) {
26 throw new Error("Failed to fetch file " + esmURL);
27 }
28 return text;
9 }
10
11 // Use the VALTOWN_API_TOKEN to fetch all vals
12 const apiToken = Deno.env.get("VALTOWN_API_TOKEN");
13
39 // Try the authenticated user's vals endpoint
40 apiUrl = `https://api.val.town/v2/me/vals`;
41 response = await fetch(apiUrl, {
42 headers: {
43 "Authorization": `Bearer ${apiToken}`,