Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/?q=fetch&page=130&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=fetch

Returns an array of strings in format "username" or "username/projectName"

Found 8641 results for "fetch"(860ms)

twitterCardsmain.tsx2 matches

@nbbaierUpdated 2 weeks ago
1import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=45";
2
3interface TwitterPost {
18 const url =
19 "https://publish.twitter.com/oembed?url=https%3A%2F%2Ftwitter.com%2FInterior%2Fstatus%2F507185938620219395";
20 const res = (await fetchJSON(url)) as TwitterPost;
21
22 return new Response(res.html, { headers: { "content-type": "text/html" } });

utilitiesemptyValUtils.ts3 matches

@nbbaierUpdated 2 weeks ago
1import { fetchPaginatedData } from "https://esm.town/v/nbbaier/fetchPaginatedData";
2import { deleteVal } from "https://esm.town/v/neverstew/deleteVal";
3
4export async function listEmptyVals(id: string) {
5 const token = Deno.env.get("valtown");
6 const res = await fetchPaginatedData(`https://api.val.town/v1/users/${id}/vals`, {
7 headers: { Authorization: `Bearer ${token}` },
8 });
12export async function deleteEmptyVals(id: string) {
13 const token = Deno.env.get("valtown");
14 const res = await fetchPaginatedData(`https://api.val.town/v1/users/${id}/vals`, {
15 headers: { Authorization: `Bearer ${token}` },
16 });

dbToAPI_backupexample.tsx1 match

@nbbaierUpdated 2 weeks ago
4const app = await createServer(db);
5
6export default app.fetch;

FarcasterMiniAppStoreHome.tsx4 matches

@moeUpdated 2 weeks ago
6
7import { Button, Input, Section, ShareButton } from "../components/ui.tsx";
8import { fetchNeynarGet, fetchNeynarGetPages, fetchUsersById } from "../util/neynar.ts";
9import { useQuery } from "../util/useQuery.ts";
10
38function MiniApps() {
39 const { data: miniapps } = useQuery(["miniapps"], async () => {
40 // return await fetch(`/api/miniapps`).then(r => r.json()).then(r => r);
41 // return await fetchNeynarGet(`frame/catalog?limit=100`).then(r => r.frames);
42 return await fetchNeynarGetPages(`frame/catalog?limit=100`, 4, "frames").then(r => r.frames);
43 });
44

perplexityAPImain.tsx2 matches

@nbbaierUpdated 3 weeks ago
1import { PplxRequest, PplxResponse } from "https://esm.town/v/nbbaier/perplexityAPI/pplxTypes.ts";
2import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON";
3
4export const pplx = async (options: PplxRequest & { apiKey?: string }): Promise<PplxResponse> => {
5 const token = options.apiKey ? options.apiKey : Deno.env.get("PERPLEXITY_API_KEY");
6 return await fetchJSON("https://api.perplexity.ai/chat/completions", {
7 method: "POST",
8 headers: {

projectTreemain.tsx1 match

@nbbaierUpdated 3 weeks ago
26});
27
28export default app.fetch;

testmain.tsx50 matches

@salonUpdated 3 weeks ago
7import { Hono } from "npm:hono";
8import { html } from "npm:hono/html";
9import { fetch } from "npm:node-fetch";
10import { z } from "npm:zod";
11// --- Constants ---
70
71/**
72 * Gets data from cache or fetches it if expired/missing.
73 * @param cacheKey - Unique key for the cached data.
74 * @param fetchFn - Async function to fetch data if cache is invalid.
75 * @param apiKey - API key, used to determine if live fetch is possible.
76 * @param steps - Log array.
77 * @returns The fetched or cached data.
78 */
79async function getCachedData<T>(
80 cacheKey: string,
81 fetchFn: () => Promise<T>,
82 apiKey: string | undefined | null,
83 steps: string[],
113
114 if (!apiKey) {
115 steps.push(`API key missing for ${cacheKey}, cannot fetch fresh data.`);
116 if (cachedData) {
117 steps.push(`Returning expired cached data for ${cacheKey} as fallback.`);
123
124 steps.push(`Workspaceing fresh data for ${cacheKey}`);
125 // TODO: error handling: Handle potential errors during the actual fetchFn execution
126 try {
127 const freshData = await fetchFn();
128 const newTimestamp = Date.now();
129 // TODO: error handling: Handle potential SQLite errors during INSERT/REPLACE
133 args: [cacheKey, JSON.stringify(freshData), newTimestamp],
134 });
135 steps.push(`Successfully fetched and cached data for ${cacheKey}`);
136 } catch (e: any) {
137 steps.push(`Error writing to cache for ${cacheKey}: ${e.message}`);
139 }
140 return freshData;
141 } catch (fetchError: any) {
142 steps.push(`Error fetching fresh data for ${cacheKey}: ${fetchError.message}`);
143 if (cachedData) {
144 steps.push(`Returning expired cached data for ${cacheKey} due to fetch error.`);
145 return cachedData; // Return stale data if fetch fails
146 }
147 throw new Error(`Failed to fetch data for ${cacheKey} and no cache available: ${fetchError.message}`);
148 }
149}
150
151/**
152 * Fetches historical stock data from Alpha Vantage.
153 * @param ticker - Stock ticker symbol.
154 * @param apiKey - Alpha Vantage API key.
156 * @returns Parsed Alpha Vantage time series data or null.
157 */
158async function fetchAlphaVantageData(
159 ticker: string,
160 apiKey: string | undefined | null,
162): Promise<AlphaVantageTimeSeriesData | null> {
163 const cacheKey = `alphavantage_${ticker}`;
164 const fetchFn = async () => {
165 steps.push(`Workspaceing Alpha Vantage data for ${ticker}`);
166 // TODO: error handling: Handle potential fetch errors (network, non-200 status)
167 const url =
168 `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${ticker}&outputsize=full&apikey=${apiKey}`;
169 const response = await fetch(url);
170 if (!response.ok) {
171 throw new Error(`Alpha Vantage API error: ${response.statusText} (Status: ${response.status})`);
185 };
186
187 return getCachedData(cacheKey, fetchFn, apiKey, steps);
188}
189
190/**
191 * Fetches previous day's close price from Polygon.io.
192 * @param ticker - Stock ticker symbol.
193 * @param apiKey - Polygon.io API key.
195 * @returns Parsed Polygon previous close data or null.
196 */
197async function fetchPolygonData(
198 ticker: string,
199 apiKey: string | undefined | null,
201): Promise<PolygonPreviousCloseData | null> {
202 const cacheKey = `polygon_${ticker}`;
203 const fetchFn = async () => {
204 steps.push(`Workspaceing Polygon.io data for ${ticker}`);
205 // TODO: error handling: Handle potential fetch errors (network, non-200 status)
206 const url = `https://api.polygon.io/v2/aggs/ticker/${ticker}/prev?adjusted=true&apiKey=${apiKey}`;
207 const response = await fetch(url);
208 if (!response.ok) {
209 let errorBody = await response.text();
225 };
226
227 return getCachedData(cacheKey, fetchFn, apiKey, steps);
228}
229
390 const { ticker, alphaVantageKey, polygonKey } = validatedInput;
391
392 // 2. Fetch Data
393 steps.push("Fetching data");
394 // TODO: error handling: These fetches might return null or throw errors
395 let alphaVantageData: AlphaVantageTimeSeriesData | null = null;
396 let polygonData: PolygonPreviousCloseData | null = null;
397 let fetchError: Error | null = null;
398
399 try {
400 [alphaVantageData, polygonData] = await Promise.all([
401 fetchAlphaVantageData(ticker, alphaVantageKey || null, steps),
402 fetchPolygonData(ticker, polygonKey || null, steps),
403 ]);
404 } catch (error: any) {
405 steps.push(`Error during data fetching: ${error.message}`);
406 fetchError = error;
407 // Attempt to continue if some data was fetched (e.g., from cache fallback)
408 if (!alphaVantageData)
409 alphaVantageData = await fetchAlphaVantageData(ticker, alphaVantageKey || null, steps).catch(() => null); // Try again individually, catch error
410 if (!polygonData) polygonData = await fetchPolygonData(ticker, polygonKey || null, steps).catch(() => null); // Try again individually, catch error
411 }
412
413 if (!alphaVantageData && !polygonData && fetchError) {
414 // If both fetches failed critically and no cache fallback was possible, rethrow
415 throw fetchError;
416 }
417
500 const data = Object.fromEntries(formData.entries());
501
502 // Use the current URL for the fetch endpoint
503 const url = new URL(window.location.href);
504 url.pathname += '/analyze'; // Append /analyze to the current path
505
506 try {
507 const response = await fetch(url.toString(), {
508 method: 'POST',
509 headers: {
559 };
560
561 // Mock fetch to avoid actual API calls and simulate responses
562 const originalFetch = global.fetch;
563 global.fetch = (url: string, options?: any): Promise<any> => {
564 console.log(`Mock fetch called for: ${url}`);
565 let responseData: any = {};
566 let status = 200;
603 statusText: status === 200 ? "OK" : "Error",
604 json: () => Promise.resolve(responseData),
605 text: () => Promise.resolve(JSON.stringify(responseData)), // For error handling in polygon fetch
606 });
607 };
629 console.error("Self-test FAILED with error:", error);
630 } finally {
631 // Restore original fetch
632 global.fetch = originalFetch;
633 console.log("Self-test finished.");
634 }

Futuremain.tsx40 matches

@salonUpdated 3 weeks ago
84 tickerDataMap: Map<string, TickerData>;
85 newsSentiment?: Record<string, "Positive" | "Neutral" | "Negative" | "Error">;
86 fetchErrors?: Record<string, string>;
87}
88interface TaskInput<T> {
306 try {
307  var apiUrl = window.location.pathname + '?action=analyze_goals&format=json';
308  var res = await fetch(apiUrl, {
309   method: 'POST',
310   headers: { 'Content-Type': 'application/json', },
427}
428
429async function fetchTickerDataFromYahoo(
430 ticker: string,
431 range = "1y",
433): Promise<TickerData> {
434 const interval = "1d";
435 const logPfx = `YahooFetch [${ticker}, ${range}]`;
436 internalLog(`${logPfx}: Init fetch...`);
437 try {
438  if (!/^[A-Z0-9.-]+$/.test(ticker)) {
451  url.searchParams.set("includeTimestamps", "true");
452  url.searchParams.set("events", "div,splits");
453  internalLog(`${logPfx}: [INFO] Fetching: ${url}`);
454  const opts = {
455   method: "GET",
463   },
464  };
465  const res = await fetch(url.toString(), opts);
466  const resText = await res.text();
467  let jsonData;
480   const errDet = res.ok ? "Missing chart.result" : `HTTP ${res.status}`;
481   internalLog(`${logPfx}: [ERROR] No valid data. Detail: ${errDet}. Resp: ${resText.substring(0, 100)}...`);
482   return { ticker, error: `Failed fetch: ${errDet}`, dates: [], open: [], high: [], low: [], close: [], volume: [] };
483  }
484  const result = jsonData.chart.result[0];
513   volume: combined.map(d => d.volume),
514  };
515  internalLog(`${logPfx}: [SUCCESS] Fetched ${data.dates.length} valid data points.`);
516  return data;
517 } catch (err: any) {
518  internalLog(`${logPfx}: [CRITICAL ERROR] Unexpected fetch failure: ${err.message}`);
519  console.error(`${logPfx} Error:`, err);
520  return { ticker, error: `Unexpected fetch error: ${err.message}`, dates: [], open: [], high: [], low: [], close: [], volume: [] };
521 }
522}
704}
705
706async function runContextDataFetchingAgent(
707 task: TaskInput<{ tickers: string[]; data_needed: string[] }>,
708 log: LogFunction,
709): Promise<TaskOutput<ContextData>> {
710 const agentName = "ContextDataFetchingAgent";
711 const taskId = task.taskId;
712 const { tickers: reqTickers, data_needed } = task.payload;
715  "INFO",
716  agentName,
717  `Task ${taskId}. Fetching ${data_needed.join(", ")} for ${tickers.length} tickers: ${tickers.join(", ")}`,
718 );
719 const intLog = (msg: string) => log("DEBUG", agentName, `[${taskId}] ${msg}`);
720 const tickerDataMap = new Map<string, TickerData>();
721 const fetchErrs: Record<string, string> = {};
722 let newsSent: Record<string, "Positive" | "Neutral" | "Negative" | "Error"> | undefined;
723 let sysErr: string | undefined;
724 if (data_needed.includes("yahoo_1y")) {
725  const promises = tickers.map(t => fetchTickerDataFromYahoo(t, "1y", intLog));
726  try {
727   const results = await Promise.all(promises);
728   results.forEach(d => {
729    tickerDataMap.set(d.ticker, d);
730    if (d.error) { fetchErrs[d.ticker] = `Yahoo Error: ${d.error}`; }
731   });
732   const successCount = tickers.length - Object.keys(fetchErrs).length;
733   log(
734    "INFO",
735    agentName,
736    `Yahoo fetch completed for ${taskId}. ${successCount} successful, ${Object.keys(fetchErrs).length} errors.`,
737   );
738   if (successCount === 0 && tickers.length > 0) {
739    log("ERROR", agentName, `Yahoo fetch FAILED for ALL tickers in task ${taskId}.`);
740   }
741  } catch (e: any) {
742   log("ERROR", agentName, `Critical error during parallel Yahoo fetch for task ${taskId}`, e);
743   sysErr = `Parallel fetch execution failed: ${e.message}`;
744   fetchErrs["SYSTEM"] = sysErr;
745  }
746 } else { log("WARN", agentName, `Task ${taskId} skipped 'yahoo_1y' data fetch.`); }
747 if (data_needed.includes("market_news_sentiment") && !sysErr) {
748  log("INFO", agentName, `Simulating news sentiment fetch for task ${taskId}...`);
749  newsSent = {};
750  await new Promise(r => setTimeout(r, 50 + Math.random() * 50));
751  for (const t of tickers) {
752   const r = Math.random();
753   if (fetchErrs[t]) {
754    newsSent[t] = "Error";
755    if (!fetchErrs[t]?.includes("News")) fetchErrs[t] += "; News Error: Skipped due to prior error";
756   } else if (r < 0.05) {
757    newsSent[t] = "Error";
758    fetchErrs[t] = (fetchErrs[t] ? `${fetchErrs[t]}; ` : "") + "News Error: Simulated fetch failure";
759   } else if (r < 0.35) { newsSent[t] = "Negative"; }
760   else if (r < 0.75) { newsSent[t] = "Neutral"; }
764 } else if (data_needed.includes("market_news_sentiment") && sysErr) {
765  log("WARN", agentName, `Skipping news sentiment simulation for task ${taskId} due to prior system error.`);
766 } else { log("WARN", agentName, `Task ${taskId} skipped 'market_news_sentiment' data fetch.`); }
767 return {
768  mandateId: task.mandateId,
769  correlationId: taskId,
770  senderRole: "Responsible",
771  payload: { tickerDataMap, newsSentiment: newsSent, fetchErrors: fetchErrs },
772  error: sysErr,
773 };
1245   }
1246   await this.internalLog("SUCCESS", `Received suggested tickers: ${intRes.suggestedTickers.join(", ")}`);
1247   const fetchDataTask: TaskInput<{ tickers: string[]; data_needed: string[] }> = {
1248    mandateId: this.mandateId, taskId: `TSK-Fetch-${Date.now()}`, senderRole: "Orchestrator", recipientRole: "Responsible",
1249    payload: { tickers: intRes.suggestedTickers, data_needed: ["yahoo_1y", "market_news_sentiment"] },
1250   };
1251   await this.internalLog("STEP", `Requesting context data (Yahoo, News Sim). Task ID: ${fetchDataTask.taskId}`);
1252   const fetchDataOut = await runContextDataFetchingAgent(fetchDataTask, this.log);
1253   await this.auditAgentTaskResult("ContextDataFetchingAgent", fetchDataOut);
1254   if (fetchDataOut.error) { throw new Error(`Context Data Fetching Failed (System): ${fetchDataOut.error}`); }
1255   intRes.contextData = fetchDataOut.payload;
1256   const tickersWithData = intRes.suggestedTickers.filter(t =>
1257    !intRes.contextData?.fetchErrors?.[t] &&
1258    intRes.contextData?.tickerDataMap.has(t) &&
1259    (intRes.contextData?.tickerDataMap.get(t)?.close?.length ?? 0) > 0
1260   );
1261   if (tickersWithData.length === 0) {
1262    throw new Error(`Context Data Fetching Failed: No valid data retrieved for any suggested ticker. Errors: ${JSON.stringify(intRes.contextData?.fetchErrors)}`);
1263   }
1264   await this.internalLog("INFO", `Context data retrieved for ${tickersWithData.length} tickers. Failed/Skipped: ${intRes.suggestedTickers.length - tickersWithData.length}`);
1322     const predResult = allPreds.find(p => p.ticker === ticker);
1323     if (!quantResult || quantResult.error) {
1324       const errorMsg = `Skipped due to ${quantResult ? 'Quant failure: ' + quantResult.error : 'Data fetch failure: ' + (intRes.contextData?.fetchErrors?.[ticker] || 'Unknown reason')}`;
1325       if (!interpResult) {
1326         allInterps.push({ ticker, error: `Interpretation ${errorMsg}`, summary: "", indicatorInterpretation: "", volatilityAssessment: "", alignmentWithGoals: "", confidence: "Low", newsContextSentiment: "N/A" });
the-juice

the-juicestill-olive-barnacle4 matches

@jxnblkUpdated 3 weeks ago
22
23 useEffect(() => {
24 fetchWorld();
25 }, []);
26
27 const fetchWorld = async () => {
28 const response = await fetch('/generate');
29 const data = await response.json();
30 setWorld(data.world);
41 </div>
42 ))}
43 <button onClick={fetchWorld}>Generate New World</button>
44 <p><a href={import.meta.url.replace("esm.town", "val.town")}>View Source</a></p>
45 </div>

stevensDemosendDailyBrief.ts1 match

@satcarUpdated 3 weeks ago
135 const lastSunday = today.startOf("week").minus({ days: 1 });
136
137 // Fetch relevant memories using the utility function
138 const memories = await getRelevantMemories();
139

fetchPaginatedData2 file matches

@nbbaierUpdated 3 weeks ago

FetchBasic1 file match

@fredmoonUpdated 3 weeks ago