-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDao.ts
72 lines (64 loc) · 2.48 KB
/
Dao.ts
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import AvailableStock from '../state/AvailableStock';
import Portfolio from '../state/Portfolio';
import { storage } from '../../inject';
import CashBalance from '../state/CashBalance';
import Stock from '../state/Stock';
/**
* The Data Access Object lets the app communicate with the backend.
* You may access the Dao methods directly like so: `dao.readStocks();`
* Typically the dao is {@link RealDao} or {@link SimulatedDao}.
*/
export abstract class Dao {
/**
* Read the current list of available stocks from the backend.
* Note: this demonstrates how to get one-off information from the backend.
*/
abstract readAvailableStocks(): Promise<AvailableStock[]>;
/**
* Continuously get stock price updates.
* Note: this demonstrates how to get information from websockets.
*
* @param onUpdate - A callback function that gets the ticker and the new
* price of a stock.
*
* Example:
* listenToStockPriceUpdates((ticker, price) => {
* console.log(`The new price of ${ticker} is $${price}`);
* });
*/
abstract listenToStockPriceUpdates(onUpdate: (ticker: string, price: number) => void): void;
/**
* Stop getting stock price updates.
* Note: this demonstrates how to close websockets.
*/
abstract stopStockPriceUpdates(): void;
/**
* Save the user's portfolio to the local disk of the device.
* Throws an exception if the portfolio cannot be saved.
*
* Note: this demonstrates how to save changing state to the local disk.
*/
async savePortfolio(portfolio: Portfolio): Promise<void> {
const serializedPortfolio = JSON.stringify(portfolio);
await storage.setItem('portfolio', serializedPortfolio);
}
/**
* Load the user's portfolio from the local disk of the device.
* If there's no saved Portfolio, returns a new empty Portfolio.
* Throws an exception if the portfolio cannot be loaded.
*
* Note: this demonstrates how to load some local state from the device,
* when the app opens.
*/
async loadPortfolio(): Promise<Portfolio> {
const serializedPortfolio = await storage.getItem('portfolio');
if (serializedPortfolio === null) {
return new Portfolio();
} else {
const portfolioData = JSON.parse(serializedPortfolio);
const stocks = portfolioData.stocks.map((stock: any) => new Stock(stock.ticker, stock.howManyShares, stock.averagePrice));
const cashBalance = new CashBalance(portfolioData.cashBalance.amount);
return new Portfolio(stocks, cashBalance);
}
}
}