Skip to content

Commit

Permalink
Merge pull request #212 from kodadot/chore/price-cache-daily
Browse files Browse the repository at this point in the history
chore: cache daily
  • Loading branch information
preschian authored Dec 2, 2023
2 parents 1d858f0 + 5831bc0 commit 9233363
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 15 deletions.
9 changes: 8 additions & 1 deletion price/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ app.on(['GET', 'OPTIONS'], '/price/:chain', async (c) => {

const key = `${cacheKey()}-${token}`;
const value = await c.env.TOKENPRICE.get(key);
const latestPrice = await c.env.TOKENPRICE.get(chain);

console.log(key, value);

Expand All @@ -28,11 +29,17 @@ app.on(['GET', 'OPTIONS'], '/price/:chain', async (c) => {
console.log(chain, usd);

c.executionCtx.waitUntil(c.env.TOKENPRICE.put(key, usd));
c.executionCtx.waitUntil(c.env.TOKENPRICE.put(chain, usd));

return c.json(formatPrice(chain, usd));
} catch (error) {
console.log(error);
return c.json({ error }, 500);

if (latestPrice) {
return c.json(formatPrice(chain, latestPrice));
}

return c.json({ error: (error as Error).message }, 500);
}
}

Expand Down
36 changes: 22 additions & 14 deletions price/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,18 @@ export async function getPrice(
// fetch sub.id API
const subid = await fetch('https://sub.id/api/v1/prices');
if (subid.status === 200) {
const data = await subid.json();
const findToken = (data as { id: string; current_price: number }[]).find(
(p) => p.id === chain,
);
const price = findToken?.current_price;

if (price) {
return price.toString();
try {
const data = (await subid.json()) as {
prices: { id: string; current_price: number }[];
};
const findToken = data.prices.find((p) => p.id === chain);
const price = findToken?.current_price;

if (price) {
return price.toString();
}
} catch (error) {
console.log('skip sub.id', error);
}
}

Expand All @@ -47,13 +51,17 @@ export async function getPrice(
`https://api.kraken.com/0/public/Ticker?pair=${pair}`,
);
if (kraken.status === 200) {
const data = (await kraken.json()) as {
result: { [key: string]: { a: [string] } };
};
const price = data.result[pair].a[0];
try {
const data = (await kraken.json()) as {
result: { [key: string]: { a: [string] } };
};
const price = data.result[pair].a[0];

if (price) {
return price;
if (price) {
return price;
}
} catch (error) {
console.log('skip kraken', error);
}
}

Expand Down

0 comments on commit 9233363

Please sign in to comment.