import type { WithAbortSignal } from "#Source/abort/index.ts" import { generalFetch } from "#Source/request/index.ts" import type { Lang } from "../base.ts" import type { AirQualityMetadataWithSources, AirQualityPollutant } from "./shared.ts" /** * @description 调用和风天气监测站数据接口时使用的参数。 * * @example * ;``` * const options: AirStationOptions = { * baseUrl: "https://abcxyz.qweatherapi.com", * jwt: "eyJhbGciOiJFZERTQSJ9.payload.signature", * locationId: "P53763", * lang: "zh-hans", * timeout: 5_000, * } * ``` */ export interface AirStationOptions extends WithAbortSignal { /** * @description 和风天气 API Base URL,例如 `https://abcxyz.qweatherapi.com`。 */ baseUrl: string /** * @description 用于 `Authorization: Bearer` 请求头的 JWT。 */ jwt: string /** * @description 空气质量监测站的 LocationID,例如 `P53763`。 */ locationId: string /** * @description 返回结果的多语言代码。 */ lang?: Lang | undefined /** * @description 请求超时时间,单位为毫秒。 */ timeout?: number | undefined } /** * @description 和风天气监测站数据接口的响应结果。 * * @example * ;``` * const result: AirStationResult = { * metadata: { * tag: "station-tag-example", * sources: [ * "https://developer.qweather.com/attribution.html", * ], * }, * pollutants: [ * { * code: "pm2p5", * name: "PM 2.5", * fullName: "Fine particulate matter (<2.5µm)", * concentration: { * value: 11, * unit: "μg/m3", * }, * subIndexes: [], * }, * ], * } * ``` */ export interface AirStationResult { /** * @description 响应元数据。 */ metadata: AirQualityMetadataWithSources /** * @description 当前监测站的污染物浓度数据列表。 */ pollutants: AirQualityPollutant[] } const internalValidateAirStationOptions = ( options: AirStationOptions, ): { baseUrl: string jwt: string locationId: string } => { const baseUrl = options.baseUrl.trim() const jwt = options.jwt.trim() const locationId = options.locationId.trim() if (baseUrl === "") { throw new TypeError("AirStation baseUrl must not be empty.") } if (jwt === "") { throw new TypeError("AirStation jwt must not be empty.") } if (locationId === "") { throw new TypeError("AirStation locationId must not be empty.") } return { baseUrl, jwt, locationId, } } /** * @description 获取指定空气质量监测站的污染物浓度数据。 * * @see {@link https://dev.qweather.com/docs/api/air-quality/air-station/} */ export const airStation = async (options: AirStationOptions): Promise => { const { baseUrl, jwt, locationId } = internalValidateAirStationOptions(options) const { lang, timeout, abortSignal } = options return await generalFetch< { query: { lang?: Lang | undefined } }, { type: "json" data: AirStationResult } >({ baseUrl, path: `/airquality/v1/station/${locationId}`, method: "get", headers: { Authorization: `Bearer ${jwt}`, }, query: { lang, }, responseType: "json", timeout, abortSignal, }).getJson() }