Skip to content

src/getAirQuality.ts

55 lines · 1.7 KB · TypeScript
Raw
import { getSnapshot, type GetSnapshotInput } from './getSnapshot'
import type { AirQualitySnapshot, Pollutants } from './types'

export type GetAirQualityResult = {
	place: AirQualitySnapshot['place']
	standard: AirQualitySnapshot['standard']
	source: AirQualitySnapshot['source']
	aqi: number | null
	level: string | null
	pollutants: Pollutants
	updateTime: string | null
	summary: string
	attribution: string
	warnings: string[]
	url: string | null
}

/**
 * Fetch AQI + pollutant concentrations only (PM2.5/PM10/O3/NO2/CO/SO2).
 * Use when you do not need pollen/weather. Same scrape/fallback as getSnapshot.
 *
 * @param input - Same as getSnapshot (`location` / `place` / `standard` / `fallback`)
 * @returns Slim air-quality slice
 *
 * @example
 * import { getAirQuality } from 'kody:@reng/air-quality/getAirQuality'
 *
 * const sh = await getAirQuality({ location: '上海', standard: 'aqi_cn' })
 * // { aqi, level, pollutants: { pm25, pm10, ... } }
 */
export async function getAirQuality(input: GetSnapshotInput = {}): Promise<GetAirQualityResult> {
	const full = await getSnapshot(input)
	const pol = full.pollutants
	const bits = [
		full.place.name,
		full.aqi != null ? `AQI ${full.aqi}${full.level ? `(${full.level})` : ''}` : null,
		pol.pm25 != null ? `PM2.5 ${pol.pm25}` : null,
		pol.pm10 != null ? `PM10 ${pol.pm10}` : null,
	].filter(Boolean)
	return {
		place: full.place,
		standard: full.standard,
		source: full.source,
		aqi: full.aqi,
		level: full.level,
		pollutants: full.pollutants,
		updateTime: full.updateTime,
		summary: bits.join(' · '),
		attribution: full.attribution,
		warnings: full.warnings,
		url: full.url,
	}
}

export default getAirQuality