官术网_书友最值得收藏!

  • TypeScript Blueprints
  • Ivo Gabe de Wolff
  • 337字
  • 2021-07-14 10:59:29

Showing a forecast

We still have not shown a forecast yet. We will use data from open weather map (http://www.openweathermap.org). You can create an account on their website. With your account, you can request an API token. You need the token to request the forecast. A free account is limited to 60 requests per second and 50,000 requests per day.

We save the API token in a separate file, lib/config.ts:

export const openWeatherMapKey = "your-token-here"; 
export const apiURL = "http://api.openweathermap.org/data/2.5/"; 

Tip

Add constants to a separate file

When you add constants in separate configuration files, you can easily change them and your code is more readable. This gives you better maintainable code.

Using the API

We will create a new file, lib/api.ts, that will simplify downloading data from open weather map. The API uses URLs such as http://api.openweathermap.org/data/2.5/forecast?mode=json&q=Utrecht,NL&appid=your-token-here. We will create a function that will build the full URL out of forecast?mode=json&q=Utrecht,NL. The function must check whether the path already contains a question mark. If so, it must add &appid=, otherwise ?appid=:

import { openWeatherMapKey, apiURL } from "./config"; 
 
export function getUrl(path: string) { 
  let url = apiURL + path; 
  if (path.indexOf("?") === -1) { 
    url += "?"; 
  } else { 
    url += "&"; 
  } 
  url += "appid=" + openWeatherMapKey; 
  return url; 
} 

Tip

Write small functions

Small functions are easy to reuse. This reduces the amount of code you need to write. The same applies to components—small components are easy to reuse.

Typing the API

You can open the URL in the previous section to get a look at the data you get. We will write an interface for the part of the API that we will use:

export interface ForecastResponse { 
  city: { 
    name: string; 
    country: string; 
  }; 
  list: ForecastItem[]; 
} 
export interface ForecastItem { 
  dt: number; 
  main: { 
    temp: number 
  }; 
  weather: { 
    main: string, 
    description: string 
  }; 
} 

Tip

JSDoc comments

You can add documentation for interfaces and their properties by adding a JSDoc comment before it:

/*** Documentation here */

主站蜘蛛池模板: 信丰县| 辽宁省| 五台县| 绥宁县| 黔东| 洪洞县| 和田市| 富民县| 措勤县| 东兴市| 兖州市| 扬中市| 鄂尔多斯市| 泰兴市| 富平县| 台安县| 贵港市| 金平| 西平县| 盘锦市| 都江堰市| 临清市| 久治县| 济宁市| 江川县| 白山市| 邯郸市| 奉节县| 呼图壁县| 慈利县| 渝中区| 松桃| 灵璧县| 铜山县| 合江县| 永兴县| 蒙城县| 广灵县| 阿尔山市| 浮梁县| 卫辉市|