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",
},
});
};