diff --git a/src/helper.ts b/src/helper.ts new file mode 100644 index 0000000..6e1aca3 --- /dev/null +++ b/src/helper.ts @@ -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 => { + 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 +} diff --git a/src/index.ts b/src/index.ts index fb70055..f8eb9fc 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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: diff --git a/src/stock_api.ts b/src/stock_api.ts index f654db2..58d3a9b 100644 --- a/src/stock_api.ts +++ b/src/stock_api.ts @@ -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; @@ -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