ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Corsair OpenWeatherMap 插件接入指南:21 个天气 API 操作、凭据管理与本地数据同步

Corsair OpenWeatherMap 插件接入指南:21 个天气 API 操作、凭据管理与本地数据同步 Corsair OpenWeatherMap 插件接入指南21 个天气 API 操作、凭据管理与本地数据同步【免费下载链接】corsairConnect your users to their apps项目地址: https://gitcode.com/GitHub_Trending/corsa/corsair本篇技术指南面向在 Corsair 中集成 OpenWeatherMap 的开发者完整讲解corsair-dev/openweathermap插件的安装注册、API Key 认证机制、21 个类型化端点实时天气、历史天气、空气质量、地理编码、天气地图瓦片与个人气象站管理的调用方式并结合仓库源码剖析其输入校验、底层请求封装、错误重试与本地数据库同步的实现细节。读完本文你将能够在自己的 Corsair 实例上开箱即用地为 AI Agent 或应用注入天气能力。插件概览corsair-dev/openweathermap是 Corsair 的官方 OpenWeatherMap 集成包位于仓库 packages/openweathermap 目录。它把 OpenWeatherMap 的能力封装为21 个类型化 API 操作覆盖六个领域Weather当前天气、One Call 3.0、5 天预报、圆形区域城市天气History历史天气时间机器Summary日汇总、人类可读天气概述Air Pollution空气质量实况、预报、历史Geocoding地名↔坐标、邮编↔坐标MapsWeather Maps 2.0 瓦片图Stations个人气象站完整生命周期管理插件采用API Key 认证api_keyCorsair 会在租户首次使用时提示录入凭据由于 OpenWeatherMap 是纯拉取式pull-basedAPI不提供任何 Webhook见 index.ts 中openWeatherMapWebhooksNested {}与注释 No webhooks — OpenWeatherMap is a pull-based API。插件以 Apache-2.0 协议发布peer 依赖corsair 0.1.0与zod ^4.1.13见 package.json。安装与注册安装包按照 README.md 的说明使用 pnpm 安装pnpm add corsair-dev/openweathermap也可以像官方插件文档 docs/guides/plugins.mdx 中描述的那样将核心 SDK 与插件一起安装npm install corsair corsair-dev/openweathermap # 或 pnpm install corsair corsair-dev/openweathermap注册插件通过createCorsair将openweathermap()工厂函数传入plugins数组完成注册。官方文档 docs/plugins/openweathermap/overview.mdx 给出了完整示例import Database from better-sqlite3; import { createCorsair } from corsair; import { openweathermap } from corsair-dev/openweathermap; export const corsair createCorsair({ plugins: [ openweathermap(), ], database: new Database(corsair.db), kek: process.env.CORSAIR_KEK!, hub: { projectApiKey: process.env.CORSAIR_API_KEY!, signingSecret: process.env.CORSAIR_SIGNING_SECRET!, }, });Corsair 默认启用多租户调用时用corsair.withTenant(id)隔离租户上下文。插件工厂与可选参数从源码 index.ts 可以看到openweathermap()工厂接受一个可选的OpenWeatherMapPluginOptionsexport type OpenWeatherMapPluginOptions { /** Authentication method. Only api_key is supported. */ authType?: PickAuthapi_key; /** Optional: pass the API key directly (bypasses key manager) */ key?: string; /** Optional: lifecycle hooks for endpoints */ hooks?: InternalOpenWeatherMapPlugin[hooks]; /** Optional: custom error handlers (merged with defaults) */ errorHandlers?: CorsairErrorHandler; permissions?: PluginPermissionsConfigtypeof openWeatherMapEndpointsNested; };authType默认即为api_key见 index.ts 的openWeatherMapAuthConfig因此大多数场景直接openweathermap()即可key可绕过密钥管理器直接注入 API KeyerrorHandlers与插件内置错误处理器浅合并{ ...errorHandlers, ...options.errorHandlers }。认证机制API Key 与密钥解析认证方式README 明确说明Auth: API key. Corsair prompts your tenant for credentials on first use.即认证方式是 API KeyCorsair 会在租户首次使用时提示录入凭据无需预配置。keyBuilder 源码解析插件的密钥解析逻辑实现在 index.ts 的keyBuilder中优先级如下显式注入优先若在插件选项中传入了key且调用来源为endpoint直接返回该 key密钥管理器兜底否则通过ctx.keys.get_api_key()从 Corsair 密钥管理器读取租户凭据两者皆无则抛错抛出AuthMissingError(openweathermap, api_key)驱动首用凭据提示流程。也就是说你可以选择让终端用户通过 Hub 连接页录入自己的 OpenWeatherMap API Key推荐的多租户模式也可以在自己的应用里直接注入一把共享密钥。密钥如何随请求发送底层请求封装 client.ts 会将 API Key 以appid查询参数的形式附加到每个请求const queryWithAuth: Recordstring, string | number | boolean | undefined { ...query, appid: apiKey, };这一行为在 client.test.ts 中有明确断言mock 请求 URL 必须同时包含appidtest-key和lat51.5。21 个端点全景README 以表格形式完整列出了全部端点及其操作 ID 与风险等级以下为其完整内容风险等级read/write/destructive对应 Corsair 权限体系见 index.ts 的openWeatherMapEndpointMetaOperationOperation IDRiskDescriptionairPollution.currentopenweathermap.api.airPollution.currentreadGet current air pollution data for a latitude/longitude pairairPollution.forecastopenweathermap.api.airPollution.forecastreadGet forecasted air pollution data for a latitude/longitude pairairPollution.historyopenweathermap.api.airPollution.historyreadGet historical air pollution data for a latitude/longitude pair and time rangegeocoding.byZipopenweathermap.api.geocoding.byZipreadConvert a zip/post code into geographic coordinatesgeocoding.directopenweathermap.api.geocoding.directreadConvert a location name into geographic coordinatesgeocoding.reverseopenweathermap.api.geocoding.reversereadConvert geographic coordinates into location nameshistory.timeMachineopenweathermap.api.history.timeMachinereadGet historical weather data for a specific timestamp (available from 1979-01-01)maps.weatherMapTileopenweathermap.api.maps.weatherMapTilereadFetch a Weather Maps 2.0 tile image for a layer and coordinatesstations.createopenweathermap.api.stations.createwriteRegister a new personal weather station with OpenWeatherstations.getopenweathermap.api.stations.getreadGet details for a registered weather station by IDstations.getMeasurementsopenweathermap.api.stations.getMeasurementsreadGet aggregated measurements from a registered station (minute/hour/day intervals)stations.listopenweathermap.api.stations.listreadList all weather stations registered to your OpenWeather accountstations.removeopenweathermap.api.stations.removedestructiveDelete a registered weather station from your account [DESTRUCTIVE]stations.submitMeasurementsopenweathermap.api.stations.submitMeasurementswriteSubmit weather measurements from a registered stationstations.updateopenweathermap.api.stations.updatewriteUpdate a registered weather station name, location, or external IDsummary.daySummaryopenweathermap.api.summary.daySummaryreadGet aggregated weather summary for a specific date (temperature, wind, precipitation)summary.overviewopenweathermap.api.summary.overviewreadGet a human-readable weather overview text for a location and dateweather.circleCityopenweathermap.api.weather.circleCityreadGet current weather for cities within a circle around a geographic pointweather.currentopenweathermap.api.weather.currentreadGet current weather for a location by city name, city ID, zip code, or coordinatesweather.forecast5Dayopenweathermap.api.weather.forecast5DayreadGet 5-day forecast in 3-hour steps (up to 40 timestamps) for a locationweather.oneCallopenweathermap.api.weather.oneCallreadGet current weather, minutely/hourly/daily forecasts, and weather alerts for a location在代码中这些端点按领域组织为嵌套命名空间index.ts调用时形如tenant.openweathermap.api.weather.oneCall({ ... })。端点实现位于 endpoints 目录下每个文件对应一个领域weather.ts、history.ts、summary.ts、air-pollution.ts、geocoding.ts、maps.ts、stations.ts。六大端点域详解Weather实时天气与预报实现在 endpoints/weather.ts四个端点分别映射到 OpenWeatherMap 的不同接口weather.oneCall→GET /onecallOne Call 3.0默认 base 为https://api.openweathermap.org/data/3.0。返回当前实况、分钟级 1 小时预报、小时级 48 小时预报、日级 8 天预报以及政府天气警报。exclude数组会先被join(,)拼成逗号分隔串再作为查询参数weather.tsweather.current→GET /weatherdata/2.5支持按城市名q、城市 IDid、邮编zip或经纬度查询当前天气weather.forecast5Day→GET /forecastdata/2.55 天预报、每 3 小时一个时间戳最多 40 条可用cnt1–40控制返回条数weather.circleCity→GET /finddata/2.5返回以某点为圆心、半径为cnt1–50默认 10的城市当前天气。以weather.current为例const tenant corsair.withTenant(acme); const london await tenant.openweathermap.api.weather.current({ lat: 51.5074, lon: -0.1278, units: metric, });units三选一standard开尔文、metric摄氏度、imperial华氏度枚举定义在 endpoints/types.ts。History时间机器history.timeMachine对应GET /onecall/timemachineendpoints/history.ts输入lat、lon与 Unix 时间戳dt返回该时刻的逐小时历史天气快照日出日落、温湿度、气压、风速、天气状况等。数据最早可追溯到 1979-01-01。集成测试中即使用了16094592002021-01-01作为历史时间戳api.test.ts。Summary日汇总与概述含本地同步summary域实现在 endpoints/summary.tssummary.daySummary→GET /onecall/day_summary输入lat、lon、dateYYYY-MM-DD格式正则校验返回当日聚合指标各时段温度min/max/afternoon/night/evening/morning、总降水量、最大风速与风向、午后云量/湿度/气压。数据范围从1979-01-02 到未来 1.5 年summary.overview→GET /onecall/overview返回一段人类可读的天气概述文本weather_overviewdate缺省时即当天。本地同步是这两个端点的特色调用成功后若存在ctx.db.daySummaries/ctx.db.overviews插件会以${lat}_${lon}_${date}为实体 ID 将响应 upsert 进本地数据库summary.ts从而支持快速的.search()/.list()查询详见下文本地数据同步。Air Pollution空气质量实现在 endpoints/air-pollution.ts三个端点分别映射到GET /air_pollution、GET /air_pollution/forecast、GET /air_pollution/historydata/2.5。输入均为经纬度历史查询额外要求start/endUnix 时间戳且必须满足start end见 air-pollution-types.ts 的withTimeRangerefine。响应中的list[].components包含 CO、NO、NO₂、O₃、SO₂、PM2.5、PM10、NH₃ 等污染物浓度main.aqi为空气质量指数。Geocoding地理编码实现在 endpoints/geocoding.tsbase 为https://api.openweathermap.org/geo/1.0geocoding.direct→GET /directq如London,UKlimit1–5地名转坐标geocoding.reverse→GET /reverselat/lonlimit1–5坐标转地名geocoding.byZip→GET /zipzip如E14,GB、SW1A,GB邮编转坐标。由 geocoding-types.ts 可见direct/reverse 返回地点数组含local_names多语言地名byZip 返回单一地点对象。Maps天气地图瓦片maps.weatherMapTile实现在 endpoints/maps.ts对应https://maps.openweathermap.org/maps/2.0请求形如GET /weather/{layer}/{z}/{x}/{y}。支持的图层代码WEATHER_MAP_LAYERS定义在 maps-types.tsPAC0、PR0、PA0、PAR0、PAS0、SD0、WS10、WND、APM、TA2、TD2、TS0、TS10、HRD0、CL分别对应降水概率、雷达、气温、风、雷暴、云层等图层。可选参数还包括date预报/历史瓦片时间戳、opacity、palette、fill_bound、arrow_step、use_norm。由于返回的是二进制 PNG该端点使用responseType: binary走专门的分支底层 client.ts 用原生fetch20 秒超时AbortSignal.timeout拉取瓦片校验Content-Type必须为image/png大小写不敏感最终返回{ contentType: image/png, dataBase64: string }方便 Agent 直接消费或转存。Stations个人气象站生命周期实现在 endpoints/stations.ts覆盖 OpenWeather 气象站 API 的完整 CRUD 与测量数据端点HTTP路径说明stations.listGET/stations列出账号下全部站点无输入参数stations.createPOST/stations注册站点需external_id、name、latitude、longitude、altitudestations.getGET/stations/{id}按内部 ID 查询站点stations.updatePUT/stations/{id}更新名称、external ID 或位置stations.removeDELETE/stations/{id}删除站点destructive级操作stations.getMeasurementsGET/measurements按typem/h/d分钟/小时/天聚合from/to/limit拉取聚合测量值stations.submitMeasurementsPOST/measurements批量提交测量记录温度、风速、风向、气压、湿度、降水等两个值得注意的实现细节POST 建站的响应归一化OpenWeather 的POST /stations返回的是大写ID字段插件通过 stations-types.ts 的z.preprocess将其归一化为小写id对外统一返回Station结构删除/提交的空响应处理stations.remove与stations.submitMeasurements使用responseType: empty底层对 204 空响应归一化为{ success: true }client.ts返回类型EmptySuccessSchema为{ success: z.literal(true) }schema-helpers.ts。输入校验Zod Schema 与约束所有端点的输入/输出都由Zod Schema定义zod ^4.1.13统一注册在 endpoints/types.ts 的OpenWeatherMapEndpointInputSchemas/OpenWeatherMapEndpointOutputSchemas并导出供 Agent 通过get_schema自省index.ts。两个可复用的校验辅助函数定义在 schema-helpers.tswithExactlyOneLocation强制q、id、zip、latlon四种定位方式恰好提供一种且禁止只传lat或lon其中一个。weather.current与weather.forecast5Day均使用该校验withTimeRange校验start end用于airPollution.history。schema 单元测试schema.test.ts验证了这些约束的边界行为同时传入q: London与lat/lon会抛错拒绝多定位标识q: 或纯空白字符串会被拒绝start: 2000, end: 1000的非法时间范围会被拒绝mode: xml/mode: html等无效字段不会被透传——schema 解析后输出对象中不存在这些键确保只向 OpenWeather 转发受支持的 JSON 参数21 个端点的 input/output schema 全部注册齐全且断言不存在以uv开头的多余端点。经纬度范围约束贯穿始终lat ∈ [-90, 90]、lon ∈ [-180, 180]。底层请求封装与多 API 基址路由client.ts 是插件的传输层定义了4 个 API 基址client.tsexport const OPENWEATHERMAP_ONE_CALL_3_BASE https://api.openweathermap.org/data/3.0; export const OPENWEATHERMAP_DATA_25_BASE https://api.openweathermap.org/data/2.5; export const OPENWEATHERMAP_GEO_BASE https://api.openweathermap.org/geo/1.0; export const OPENWEATHERMAP_MAPS_2_BASE https://maps.openweathermap.org/maps/2.0;baseUrlFor(api)client.ts负责按端点归属路由One Call 3.0 系列默认走data/3.0current/forecast/空气污染走data/2.5地理编码走geo/1.0瓦片走maps/2.0。这一路由行为在 client.test.ts 中被逐一断言。此外请求封装还会自动压缩掉undefined的查询参数与请求体字段compactQuery/compactBody见 client.ts对 POST/PUT 请求体自动 JSON 序列化将 HTTP 错误包装为携带status、statusText、body、retryAfter等字段的OpenWeatherMapAPIErrorclient.ts。错误处理与重试策略插件内置错误处理器定义在 error-handlers.ts注释中明确了 OpenWeatherMap 的典型错误码语义该文件源码注释401 无效密钥或新密钥未激活最长 2 小时生效延迟404 请求位置/时间无数据429 限流5xx 服务端错误并据此配置重试错误类型匹配条件策略RATE_LIMIT_ERRORHTTP 429 或消息含429/rate limit最多重试3 次exponential_backoff并读取Retry-After头作为等待时间AUTH_ERRORHTTP 401 或消息含invalid api key/unauthorized/401不重试打印提示提醒新密钥最长 2 小时激活NOT_FOUND_ERRORHTTP 404 或消息含404/not found不重试打印位置/时间无数据警告SERVER_ERRORHTTP ≥500最多重试2 次exponential_backoffDEFAULT兜底不重试二进制瓦片请求的 429 错误同样会被设置为status: 429从而正确命中RATE_LIMIT_ERROR处理器client.test.ts。你可以通过插件选项的errorHandlers传入自定义处理器与默认配置合并后生效。本地数据同步可搜索实体插件定义了 2 个同步实体见 schema/index.ts 与 schema/database.tsschema 版本为1.0.0daySummaries由summary.daySummary调用后自动落库扁平化保存该地点/日期的最小/最大/午后/早间/晚间/夜间温度、总降水量、最大风速与风向、午后云量/湿度/气压overviews由summary.overview调用后自动落库保存人类可读的天气概述文本weatherOverview。查询方式见 docs/plugins/openweathermap/database.mdxconst rows await corsair.openweathermap.db.daySummaries.search({ data: { date: 2024-01-01, temperatureMax: { gt: 20 }, // 支持 equals, gt, gte, lt, lte, in }, limit: 100, offset: 0, });数值字段支持equals / gt / gte / lt / lte / in操作符字符串字段支持equals / contains / startsWith / endsWith / increatedAt支持before / after / between。对于 AI Agent 而言这意味着可以离线化、低延迟地查询历史天气而不必每次回源 OpenWeather。权限模型与测试验证风险分级21 个端点的风险元数据openWeatherMapEndpointMetaindex.ts清晰地划分了权限边界read绝大多数端点天气、历史、汇总、空气污染、地理编码、地图瓦片、站点查询类writestations.create、stations.update、stations.submitMeasurementsdestructivestations.remove删除站点。这意味着在多租户场景下你可以通过 Corsair 的permissions配置为不同租户/角色授予差异化能力如只读租户、可写租户、管理员租户。测试与可验证性仓库提供了三层测试作为实现证据schema.test.ts纯单元测试验证所有 Zod 输入/输出 schema 的约束与 21 端点注册完整性无需网络client.test.tsmockfetch验证请求 URL 路由、appid附加、PNG 瓦片内容类型校验拒绝 JPEG/缺失 Content-Type与空响应归一化api.test.ts真实 API 集成测试设置环境变量OPENWEATHERMAP_API_KEY且OPENWEATHERMAP_INTEGRATION_TESTS1时启用以伦敦坐标(51.5074, -0.1278)走查 oneCall、current、forecast5Day、circleCity、timeMachine、daySummary、overview、空气污染三接口、地理编码三接口、瓦片拉取以及气象站完整生命周期创建→查询→更新→提交测量→读取测量→删除。参考与延伸阅读插件包corsair-dev/openweathermap含 endpoints、schema、client.ts、error-handlers.ts插件官方文档Overviewdocs/plugins/openweathermap/overview.mdx、API 参考docs/plugins/openweathermap/api.mdx、数据库同步docs/plugins/openweathermap/database.mdx通用插件接入指南docs/guides/plugins.mdx凭据管理docs/guides/plugin-credentials.mdx多租户隔离docs/concepts/multi-tenancy.mdx如果需要在项目中使用请以官方发布的 npm 包为准通过pnpm add corsair-dev/openweathermap安装并确保核心corsair版本不低于0.1.0peer 依赖约束。【免费下载链接】corsairConnect your users to their apps项目地址: https://gitcode.com/GitHub_Trending/corsa/corsair创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表