Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
g-viet committed Apr 25, 2019
1 parent 4ef401d commit 3d35912
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 21 deletions.
33 changes: 33 additions & 0 deletions src/helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Stock } from "./stock";
const request = require('request');

const BASE_API_URL = 'https://api.vietstock.vn/ta/history';
const buildApiUrl = (stockCode: string): string => {
const to = Math.floor(Date.now() / 1000);
const from = to - 864000; // 10 days
return `${BASE_API_URL}?symbol=${stockCode}&resolution=D&from=${from}&to=${to}`;
}

const fetchStock = async (stockCode: string): Promise<Stock> => {
const apiCall = () => {
return new Promise((resolve, reject) => {
const options = {
url: Helper.buildApiUrl(stockCode),
method: 'GET',
json: true
};
request(options, (err: any, _res: any, body: any) => {
if (err) reject(err);
resolve(body);
});
})
}
return apiCall().then((body: any) => {
return new Stock(stockCode, JSON.parse(body));
})
}

export const Helper = {
buildApiUrl: buildApiUrl,
fetchStock: fetchStock
}
5 changes: 5 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ program
}
Stock.gets(stocks);
case "stream":
if (stocks.length == 0) {
console.log("You must include stock code!! For example: ");
console.log("`stocknode stream VCB`");
return;
}
Stock.stream(stocks[0]);
break;
default:
Expand Down
26 changes: 5 additions & 21 deletions src/stock_api.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
import { Stock } from './stock';
const request = require('request');

const BASE_API_URL = 'https://api.vietstock.vn/ta/history';
import { Helper } from './helper';

const gets = (stockCodes: string[]) => {
console.log(`Stock\tPrice\t\tVolume\t\tOpenPrice\tHighestPrice\tLowestPrice\tTime`);
try {
return Promise.all(stockCodes.map(code => {
const options = {
url: buildApiUrl(code),
method: 'GET',
json: true
}
return request(options, (_err: any, _res: any, body: any) => {
const stockPrice = new Stock(code, JSON.parse(body));
stockPrice.printf();
return true;
});
return Promise.all(stockCodes.map(async (code) => {
const stock = await Helper.fetchStock(code);
stock.printf();
return true;
}));
} catch (err) {
throw err;
Expand All @@ -27,12 +17,6 @@ const stream = (stockCode: string) => {
return;
}

const buildApiUrl = (stock: string): string => {
const to = Math.floor(Date.now() / 1000);
const from = to - 864000; // 10 days
return `${BASE_API_URL}?symbol=${stock}&resolution=D&from=${from}&to=${to}`;
}

export {
gets,
stream
Expand Down

0 comments on commit 3d35912

Please sign in to comment.