connector-weatherapi
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWeather data with weatherapi-client
weatherapi-client使用 weatherapi-client
获取天气数据
weatherapi-clientMotoko bindings for WeatherAPI.com, generated
from its OpenAPI spec. All nine operations live in a single module,
, and all nine are read-only s.
Apis/APIsApiGETBackend
后端
A canister that reads the current temperature and a three-day maximum series.
Non-replicated is the default, so you only supply the key:
motoko
import { realtimeWeather; forecastWeather } "mo:weatherapi-client/Apis/APIsApi";
import { type Config; defaultConfig } "mo:weatherapi-client/Config";
import Array "mo:core/Array"; // in scope so `days.map(…)` dot notation resolves
persistent actor {
// The key is a query-string credential. Hold it in a stable variable set by
// an admin call; never hard-code it in source.
func config(apiKey : Text) : Config = { defaultConfig with auth = ?#apiKey apiKey };
// `q` is any WeatherAPI location query: "Zurich", "47.37,8.55", a postcode,
// an IATA code, or "auto:ip".
public func currentTempC(apiKey : Text, q : Text) : async ?Float {
let res = await* realtimeWeather(config apiKey, q, "");
do ? { res.current!.temp_c! };
};
// Daily maxima for the next three days.
public func maxTempsC(apiKey : Text, q : Text) : async [?Float] {
let res = await* forecastWeather(config apiKey, q, #_3_, "", 0, 0, "", "no", "no", 0);
let ?forecast = res.forecast else return [];
let ?days = forecast.forecastday else return [];
days.map(func(d) = do ? { d.day!.maxtemp_c! });
};
}一个读取当前温度和三日最高温度序列的 canister。默认采用非复制模式,因此只需提供 key:
motoko
import { realtimeWeather; forecastWeather } "mo:weatherapi-client/Apis/APIsApi";
import { type Config; defaultConfig } "mo:weatherapi-client/Config";
import Array "mo:core/Array"; // in scope so `days.map(…)` dot notation resolves
persistent actor {
// The key is a query-string credential. Hold it in a stable variable set by
// an admin call; never hard-code it in source.
func config(apiKey : Text) : Config = { defaultConfig with auth = ?#apiKey apiKey };
// `q` is any WeatherAPI location query: "Zurich", "47.37,8.55", a postcode,
// an IATA code, or "auto:ip".
public func currentTempC(apiKey : Text, q : Text) : async ?Float {
let res = await* realtimeWeather(config apiKey, q, "");
do ? { res.current!.temp_c! };
};
// Daily maxima for the next three days.
public func maxTempsC(apiKey : Text, q : Text) : async [?Float] {
let res = await* forecastWeather(config apiKey, q, #_3_, "", 0, 0, "", "no", "no", 0);
let ?forecast = res.forecast else return [];
let ?days = forecast.forecastday else return [];
days.map(func(d) = do ? { d.day!.maxtemp_c! });
};
}The nine operations
九项操作
| Function | Endpoint | Returns |
|---|---|---|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
daysForecastWeatherDaysParameter#_1_#_14_MarineWeatherDaysParameter#_1_#_7_#_3_#_33| 函数 | 端点 | 返回值 |
|---|---|---|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
daysForecastWeatherDaysParameter#_1_#_14_MarineWeatherDaysParameter#_1_#_7_#_3_#_33API key setup
API key 设置
- Sign up at weatherapi.com — the free tier covers current weather, 3-day forecast, astronomy, timezone, search and IP lookup. History, future, marine and 14-day forecasts need a paid plan and return 403 on free keys.
- Copy the key from the dashboard and pass it as .
auth = ?#apiKey key - The client appends it as (WeatherAPI takes no
?key=…header), so it appears in the request URL. Keep it in a stable variable written by an admin-only call, and never log the built URL.Authorization
- 在 weatherapi.com 注册——免费套餐支持当前天气、三日预报、天文、时区、搜索和 IP 查询。历史、未来、海洋和十四日预报需要付费套餐,使用免费 key 时会返回 403。
- 从 dashboard 复制 key,并按 的形式传入。
auth = ?#apiKey key - 客户端会将其作为 附加(WeatherAPI 不接受
?key=…header),因此它会出现在 request URL 中。应将其保存在由仅限管理员调用的方法写入的稳定变量中,绝不要记录构建后的 URL。Authorization
Calls are non-replicated by default
调用默认采用非复制模式
The package ships in , and that is a
correctness requirement here, not just a cost saving. Every response carries
per-request clocks — / ,
/ — which change second to second. A
replicated outcall has every subnet node issue its own request and demands
bit-identical bodies, so those fields would break consensus on most calls while
burning ~13× the cycles. You don't set it yourself; the default is correct.
is_replicated = ?falsedefaultConfigLocation.localtimelocaltime_epochCurrent.last_updatedlast_updated_epochOverride with only together with a that
strips the volatile fields.
is_replicated = ?truetransform该 package 在 中提供了 ,在这里这是正确性要求,不仅仅是节省成本。每个响应都包含按请求生成的时钟信息—— / 、 / ——这些值每秒都会变化。replicated outcall 会让每个 subnet 节点分别发出请求,并要求响应正文逐位一致,因此这些字段会在大多数调用中破坏共识,同时消耗约 13× 的 cycles。你不需要自行设置,默认值是正确的。
defaultConfigis_replicated = ?falseLocation.localtimelocaltime_epochCurrent.last_updatedlast_updated_epoch只有在同时使用会去除这些易变字段的 时,才应将 覆盖为 。
transformis_replicated?trueEverything is optional
所有字段均为可选
WeatherAPI marks no response field required, so the generated models are
all-optional: ,
, and so on. Reach through them with a block
() rather than nested es, and decide what
an absent field means for your caller — the API omits fields your plan does not
cover (for example without the parameter).
RealtimeWeather200Response.current : ?CurrentCurrent.temp_c : ?Floatdo ?do ? { res.current!.temp_c! }switchair_qualityaqi=yesWeatherAPI 未将任何响应字段标记为 required,因此生成的模型全部为 optional,例如 、。应使用 block()访问这些字段,而不是嵌套使用 ,并明确字段缺失对调用方意味着什么——API 会省略当前套餐不涵盖的字段(例如未设置 参数时不会返回 )。
RealtimeWeather200Response.current : ?CurrentCurrent.temp_c : ?Floatdo ?do ? { res.current!.temp_c! }switchaqi=yesair_qualityEmpty string and zero mean "omit"
空字符串和零表示“不提供”
Optional query parameters are dropped when they are or , because
WeatherAPI rejects empty and zero-valued numerics. So passing for
, , , and for , is how you say "not
supplied" — there is no parameter to leave .
""0lang=""langdtalertsaqi0unixdttp?TextnullOne consequence worth knowing: does not select midnight, it omits
the filter entirely and you get the whole day's hourly array. Filter the
returned yourself if you need
00:00.
hour = 0hourhour : ?[ForecastForecastdayInnerHourInner]当可选查询参数为 或 时会被省略,因为 WeatherAPI 会拒绝值为空的 和数值为零的参数。因此,为 、、、 传入 ,并为 、 传入 ,就是表示“不提供”;不存在可保持 的 参数。
""0lang=langdtalertsaqi""unixdttp0null?Text有一个值得注意的结果: 并不会选择午夜,而是完全省略 filter,并返回整天的 hourly array。如果需要 00:00,请自行过滤返回的 。
hour = 0hourhour : ?[ForecastForecastdayInnerHourInner]Errors
错误
Non-2xx responses and decode failures . The client is
generated with , so the message is
— enough to tell a 401
(bad key) from a 403 (endpoint not on your plan) from a 400 ( not resolvable)
without extra logging. Catch with / and surface
.
throw Error.reject(…)diagnosticsHTTP <status> body[<n>B]=<first 100 chars>: <reason>qtrycatchError.message(err)非 2xx 响应和解码失败会 。客户端在生成时启用了 ,因此消息格式为 ——无需额外 logging,就足以区分 401(key 无效)、403(套餐不包含该端点)和 400(无法解析 )。使用 / 捕获错误,并通过 返回错误信息。
throw Error.reject(…)diagnosticsHTTP <status> body[<n>B]=<first 100 chars>: <reason>qtrycatchError.message(err)