Properties 与 templates 实现一个日记模板

第一次发帖,查看 【搭建你的日记本】使用 Properties 与 templates 实现一个日记模板帖子使用了两个平台的API,此处就来用下高德,补充下文档,并优化了代码。

高德使用

https://lbs.amap.com/api/webservice/guide/tools/info,接口报错了可以按照错误码自行排错

天气查询注意extensions的参数:base/all

  • base:返回实况天气
  • all:返回预报天气

<%*

const key = '填入你申请的key,选webapi' 

/**
 * @description 坐标查询
 */
const getIpAddress = () =>
  fetch(`https://restapi.amap.com/v3/ip?&output=json&key=${key}`).then((response) =>
    response.json()
  )

  /**
   * @description 天气查询
   * @param adcode 城市编码
   */
const getWeather = (adcode) =>
  fetch(
    `https://restapi.amap.com/v3/weather/weatherInfo?extensions=all&city=${adcode}&key=${key}`
  ).then((response) => response.json())

/**
 * @description 加载
 * @returns location 省-市
 * @returns weathers 早晚天气
 * @returns temperatures 早晚温度
 */
const loadingData = async () => {
  //Ip
  const addressInfo = await getIpAddress()
  let { province, city, adcode } = addressInfo
  const location = `${province}-${city}`
  //天气
  const weatherInfo = await getWeather(adcode)
  const { casts } = weatherInfo.forecasts[0] //解构未来4天天气预报
  const weathers = `🌅${casts[0].dayweather}/🌃${casts[0].nightweather}`
  const temperatures = `🌅${casts[0].daytemp}/🌃${casts[0].nighttemp}`
  return { location, weathers, temperatures }
}

const { location, weathers, temperatures } = await loadingData()

-%>
---
🌻日期🌻: <% tp.file.creation_date("YYYY MM DD HH:mm:ss") %>
🌙星期🌙: <% tp.file.creation_date("dddd") %>
⌚️时间⌚️: <% tp.file.creation_date("HH:mm:ss") %>
🌍位置🌍: <% location %>
☁️天气☁️: <% weathers %>
🌡️温度🌡️: <% temperatures %>
---

2 个赞

非常感谢,已经搬到自己的日记中。

另:在实际使用过程中,有时候自己的IP莫名其妙的变成国外IP(未使用代理),通过api查询结果是空的,此时通过这个模板创建笔记会报错,想着如果getIpAddress返回的adcode为空,就用一个默认的IP再次查询获取相关信息,但是这个判断试了好多次没成功。如果楼主有实现方法,非常感激分享