Alphavantage API在键中具有空格和周期。API没有正式的DOCO,尽管您可以在他们的演示url
中看到它https://www.alphavantage.co/query?function= time_series_intraday& symbol = msft& interval = 5min& papikey = demo
在我的打字稿应用程序中,我为此创建了数据结构(我很高兴任何人复制和使用这些结构 - 也许找到了我的问题的解决方案(:
export class MetaData {
'1. Information': string
'2. Symbol': string
'3. Last Refreshed': string
'4. Output Size': string
'5. Time Zone': string
constructor(one, two, three, four, five) {
this['1. Information'] = one
this['2. Symbol'] = two
this['3. Last Refreshed'] = three
this['4. Output Size'] = four
this['5. Time Zone'] = five
}
}
export interface TimeSeries {
[date: string]: {
'1. open': string;
'2. high': string;
'3. low': string;
'4. close': string;
'5. volume': string;
}
}
export interface AlphaVantage {
'Meta Data': MetaData;
'Time Series (Daily)'?: TimeSeries;
'Time Series (Weekly)'?: TimeSeries;
}
我使用NPM的alphavantage
调用API,然后隐式地将其施放到我的AlphaVantage
:
const av: AlphaVantage = await alpha.data.weekly(options.stocks, 'compact', 'json')
,然后(可能在按摩之后等(我将其持续到mongoDB集合中:
const doc = await this.model.findByIdAndUpdate(proxyModel._id, proxyModel)
(近距离模型是用于定义数据库键的DTO,例如日期,库存符号等...其中一个字段是Alphavantage数据(。
这必须序列化数据,并且它错误地与:
key 1. Information must not contain '.'
是否有一种简单的方法来处理此问题。我的选择是在没有空间的情况下创建等效对象:
export interface TimeSeries {
[date: string]: {
'1_open': string;
'2_high': string;
'3_low': string;
'4_close': string;
'5_volume': string;
}
}
然后施放。在这种情况下,提供了映射...
我可以看到自己创建一个实现。但是,在进行此之前,我想听听任何想法如何最好地处理此数据结构。
我用简单对象键映射函数编写了一个解决方案。
我也尝试使用automapper -ts -https://www.npmjs.com/package/automapper-ts-,以使对所做的更改更清楚。但是,绘制所有案例变得太难了。在分配给它的时间,我无法获得测试(作为DOCO的作用(。我刚刚看到有https://github.com/gonza-lito/automapper,这是最近修改的叉子。但是,它不是开箱即用的npm install
。
这是我想出的课程来解决我的问题:
export class ObjectUtils {
static fixKey(key) {
const upperCaseReplacer = (match: string, g1: string) => {
return g1.toUpperCase()
}
const wordsReplacer = (match: string, g1: string, g2: string) => {
return g1 + g2.toUpperCase()
}
const m1 = key.replace(/^d+ *. *([a-zA-Z])/, upperCaseReplacer)
const m2 = m1.replace(/([a-zA-Z]) +([a-zA-Z])/g, wordsReplacer)
const out = m2.replace(/^([a-zA-Z])/, upperCaseReplacer)
return out
}
static fixObj(obj: any) {
let newObj = null
if (Array.isArray(obj)) {
newObj = []
for (const i of obj) {
newObj.push(ObjectUtils.fixObj(i))
}
return newObj
} else if (typeof obj === 'object') {
newObj = {}
for (const key of Object.keys(obj)) {
newObj[ObjectUtils.fixKey(key)] = ObjectUtils.fixObj(obj[key])
}
return newObj
} else {
return obj
}
}
}
这将创建以下内容:
export class Metadata {
Information: string
Symbol: string
LastRefreshed: string
OutputSize: string
TimeZone: string
}
export interface TimeSeries {
[date: string]: {
Open: string;
High: string;
Low: string;
Close: string;
Volume: string;
}
}
export interface AlphaVantage {
Metadata: Metadata
DailyTimeSeries?: TimeSeries
WeeklyTimeSeries?: TimeSeries
}