Created
November 26, 2018 13:09
-
-
Save dsebastien/1c8173416b5b8013863e57f6f9b1eae3 to your computer and use it in GitHub Desktop.
TS Async await fetch and io-ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async getIndicatorData(indicator: WorldBankApiV2Indicators, country: Country, dateRange: string, perPage: number): Promise<DataPoint[]> { | |
const response: Response = await fetch(`${this.getBaseIndicatorApiUrlFor(indicator, country)}?${WorldBankApiV2Params.FORMAT}=${WorldBankApiV2Formats.JSON}&${WorldBankApiV2Params.PER_PAGE}=${perPage}&${WorldBankApiV2Params.DATE}=${dateRange}`); | |
const checkedResponse: Response = await this.checkResponseStatus(response); | |
let jsonContent: unknown = await this.getJsonContent(checkedResponse); | |
const validationResult = worldBankApiV2IndicatorResponseValidator.decode(jsonContent); | |
ThrowReporter.report(validationResult); | |
// from here on, we know that the validation has passed | |
const dataPoints = (validationResult.value as WorldBankApiV2IndicatorResponse)[1]; | |
let retVal: DataPoint[] = []; | |
if (dataPoints) { // we might not get anything back | |
dataPoints.forEach(dataPoint => { | |
retVal.push(new DataPoint( | |
dataPoint.date, | |
dataPoint.value | |
)); | |
}); | |
} | |
return retVal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment