Skip to content

Instantly share code, notes, and snippets.

@dsebastien
Created November 26, 2018 13:09
Show Gist options
  • Save dsebastien/1c8173416b5b8013863e57f6f9b1eae3 to your computer and use it in GitHub Desktop.
Save dsebastien/1c8173416b5b8013863e57f6f9b1eae3 to your computer and use it in GitHub Desktop.
TS Async await fetch and io-ts
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