1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON";
import { thisWebURL } from "https://esm.town/v/stevekrouse/thisWebURL";
async function alphaVantage(symbol: string) {
let data = await fetchJSON(
`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${symbol}&apikey=${Deno.env.get("alphaVantage")}`,
);
return data;
}
export function getStockData(symbol: string) {
return fetchJSON(
`${thisWebURL()}?symbol=${symbol}`,
);
}
export function getStockPrice(symbol: string) {
return getStockData(symbol).then((data) => data["Global Quote"]["05. price"]);
}
export default async (req: Request) => {
const url = new URL(req.url);
const symbol = url.searchParams.get("symbol");
if (!symbol) {
return new Response(
`
Missing query parameter 'symbol'<br>
Example: <a href="${thisWebURL()}?symbol=AAPL">${thisWebURL()}?symbol=AAPL</a>
`,
{ status: 200, headers: { "content-type": "text/html" } },
);
}
const data = await alphaVantage(symbol);
if (url.searchParams.get("simple")) {
return new Response(JSON.stringify(data["Global Quote"]["05. price"]), {
headers: {
"content-type": "application/json",
},
});
}
return new Response(JSON.stringify(data), {
headers: {
"content-type": "application/json",
},
});
};