Skip to content

Commit

Permalink
feat: caching city uri to reduce amount of calls
Browse files Browse the repository at this point in the history
  • Loading branch information
sheverniskiy committed May 29, 2022
1 parent 60f0371 commit 8ccf12c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/gismeteo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ export class Gismeteo {
'user-agent': new UserAgent().toString(),
},
}
private _city_cache = {
city: '',
city_uri: '' as CityUri,
}

constructor(options?: GismeteoOptions) {
this._base_url = options?.lang === 'en' ? Endpoint.BASE_EN : Endpoint.BASE_RU
Expand Down Expand Up @@ -183,10 +187,18 @@ export class Gismeteo {
}

private async getCityUri(city: string): Promise<CityUri> {
if (city === this._city_cache.city) {
return Promise.resolve(this._city_cache.city_uri)
}

return axios.get(`${Endpoint.SEARCH}${encodeURIComponent(city)}/9/`, this._axios_config).then(({ data }) => {
if (data.data.length === 0 || data.data[0]?.url === undefined) {
throw new GismeteoCityError('Unable to find uri for given city name')
}
this._city_cache = {
city: city,
city_uri: data.data[0].url,
}
return data.data[0].url
})
}
Expand Down
2 changes: 1 addition & 1 deletion test/gismeteo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('Gismeteo', () => {

describe('getTwoWeeks', () => {
test('should not be null and contain 14 items', async () => {
const result = await gismeteo.getTwoWeeks('Москва')
const result = await gismeteo.getTwoWeeks('Moscow')

expect(result).not.toBeNull()
expect(result.length).toBe(14)
Expand Down

0 comments on commit 8ccf12c

Please sign in to comment.