Skip to content

Commit

Permalink
Merge pull request #2 from reshortt/Cleaner_API_Example
Browse files Browse the repository at this point in the history
- Some small changes to showcase a bit of a cleaner API with some err…
  • Loading branch information
reshortt authored Jan 28, 2022
2 parents 7c57b53 + 803497d commit 0fc6cb3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
14 changes: 10 additions & 4 deletions src/APIService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,12 @@ export const lookupTicker = async (
}
};

export const buyAsset = async (symbol: string, shares: number, price:number) => {
export type BuyAssetResponse = {
successful:boolean;
remainingCash?:number;
}

export const buyAsset = async (symbol: string, shares: number, price:number): Promise<BuyAssetResponse> => {
// TODO: credentials not needed for stocklookup.remove
const requestOptions = createRequestAuthorization();

Expand All @@ -265,13 +270,14 @@ export const buyAsset = async (symbol: string, shares: number, price:number) =>
switch (response.status) {
case 200: {
const userResponseObj = await response.json();
return userResponseObj;
const cashRemainingAfterPurchase: number = userResponseObj.cash;
return {successful: true, remainingCash: cashRemainingAfterPurchase};
}

default:
// 500 is possible for critical server erropr
console.log("unexpected getAssets response");
return false;
console.log("unexpected buyAsset response");
return { successful: false };
}
};

Expand Down
22 changes: 12 additions & 10 deletions src/components/Buy.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ChangeEvent, useEffect, useState, useRef } from "react";
import { buyAsset, getCash, getStockPrice, lookupTicker } from "../APIService";
import { buyAsset, BuyAssetResponse, getCash, getStockPrice, lookupTicker } from "../APIService";
import { formatCurrency } from "../Calculations";
import { COMMISSION, StockPrices } from "../types";

Expand Down Expand Up @@ -110,19 +110,21 @@ export default function Buy() {
".";
const isOK: boolean = window.confirm(msg);
if (isOK) {
const response = await buyAsset(
buyAsset(
typedSymbol,
sharesToBuy,
askPrice || 0
);
if (response) {
window.alert("Purchase confirmed. New cash is " + formatCurrency(response.cash))
window.location.assign("/positions")

} else {
window.alert("Purchase failed");
).then((buyAssetResponse: BuyAssetResponse)=>{
const { successful, remainingCash } = buyAssetResponse
if(successful){
window.alert(`Purchase executed! You have ${remainingCash} remaining.`);
}
}, ()=>{
window.alert("Purchase was not executed due to critical server error");
});
}
} else alert("Purchase cancelled");
} else{
window.alert("Purchase cancelled");
}
};

Expand Down

0 comments on commit 0fc6cb3

Please sign in to comment.