import { uniq } from "lodash" ; import TencentStockTransform from "@stocks/tencent/transforms/stock" ; import TencentCommonCodeTransform from "@stocks/tencent/transforms/common-code" ; import fetch from "@utils/fetch" ; import iconv from "@utils/iconv" ; import { DEFAULT_STOCK } from "@utils/constant" ; import { COMMON_SH , COMMON_SZ , COMMON_US , COMMON_HK } from "@stocks/base/utils/constant" ; import Stock from "types/utils/stock" ; import StockApi from "types/stocks/index" ; /**
 * 腾讯股票代码接口
 */ const Tencent = { param code async getStock ( code ) { const transform = ( new TencentCommonCodeTransform ) . transform ( code ) ; const url = `https://qt.gtimg.cn/q=${ transform }` ; const res = await fetch . get ( url ) . responseType ( 'blob' ) ; const body = iconv . decode ( res . body , "gbk" ) ; const rows = body . split ( ";\n" ) ; const row = rows [ 0 ] ; if ( ! row . includes ( transform ) ) { return { ... DEFAULT_STOCK , code } ; } const [ _ , paramsUnformat ] = row . split ( '=' ) ; const params = paramsUnformat . replace ( '"' , '' ) . split ( "~" ) ; const data = ( new TencentStockTransform ( code , params ) ) ; return data . getStock ( ) ; } , param codes async getStocks ( codes ) { codes = uniq ( codes . filter ( i => i !== '' ) ) ; if ( codes . length === 0 ) { return [ ] ; } const transforms = ( new TencentCommonCodeTransform ) . transforms ( codes ) ; const url = `https://qt.gtimg.cn/q=${ transforms . join ( ',' ) }` ; const res = await fetch . get ( url ) . responseType ( 'blob' ) ; const body = iconv . decode ( res . body , "gbk" ) ; const rows = body . split ( ";\n" ) ; return codes . map ( ( code , index ) => { const transform = ( new TencentCommonCodeTransform ) . transform ( code ) ; if ( ! rows . find ( row => row . includes ( transform ) ) ) { return { ... DEFAULT_STOCK , code } ; } const [ _ , paramsUnformat ] = rows [ index ] . split ( '=' ) ; const params = paramsUnformat . replace ( '"' , '' ) . split ( "~" ) ; const data = ( new TencentStockTransform ( code , params ) ) ; return data . getStock ( ) ; } ) ; } , param key async searchStocks ( key ) { const url = `https://smartbox.gtimg.cn/s3/?v=2&t=all&c=1&q=${ encodeURIComponent ( key ) }` ; const res = await fetch . get ( url ) . responseType ( 'blob' ) ; const body = iconv . decode ( res . body , "gbk" ) ; const rows = body . replace ( 'v_hint="' , '' ) . replace ( '"' , "" ) . split ( '^' ) ; const codes = rows . map ( row => { const [ type , code ] = row . split ( '~' ) ; switch ( type ) { case 'sz' : return COMMON_SZ + code ; case 'sh' : return COMMON_SH + code ; case 'hk' : return COMMON_HK + code ; case 'us' : return COMMON_US + code . split ( '.' ) [ 0 ] . toUpperCase ( ) ; default : return '' ; } } ) ; return await Tencent . getStocks ( uniq ( codes . filter ( i => i !== '' ) ) ) ; } } ; export default Tencent ;