<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Chilfish’s Blog</title><description>Chilfish’s Blog</description><link>https://chilfish.top/</link><language>zh-cn</language><follow_challenge><feedId>57645530191768577</feedId><userId>41455408951018496</userId></follow_challenge><item><title>「迷子近况」一直消失但疯狂的两个月氵</title><link>https://chilfish.top/posts/2024-missing-2-months/</link><guid isPermaLink="true">https://chilfish.top/posts/2024-missing-2-months/</guid><pubDate>Mon, 27 May 2024 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;染上邦多利这辈子就完蛋了 😤&lt;/h3&gt;
&lt;p&gt;究竟是什么让嗜码如命的我连着几个星期一点东西都不写的？这完全是进入到了一个前所未有的着迷状态，每天不是邦多利 &lt;sup&gt;&lt;a href=&quot;#user-content-fn-1&quot; id=&quot;user-content-fnref-1&quot; data-footnote-ref=&quot;&quot; aria-describedby=&quot;footnote-label&quot;&gt;1&lt;/a&gt;&lt;/sup&gt; 就是女省油，不是刷推就是窥看 Q 群……&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/2024-Apr-time.webp&quot; alt=&quot;还真是0产出的“空窗期”……&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;还真是0产出的“空窗期”……&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;4月10号 MyGO 要上国服了，于是抱着试试的想法下回了日服）但因为错过了活动，抽卡上基本都没有谁出现，这时候还没补邦的剧情，对其他团也不太感冒 (当然后来都基本补完了剧情，ksm：大家我都喜欢哦。jpg)。一开始苦手于绿条的尾判时机，但突然想着用粉键的手法——用上滑来结束绿条，居然能行，后面也就慢慢适应了该怎么应对了 😎&lt;/p&gt;
&lt;p&gt;因为要抽卡，还是得屯资源准备，于是国服日服两边都速过剧情一起练。但现实是都两百抽了还没凑齐全员，最后还是用抽卡次数换来的任选卡……&lt;/p&gt;
&lt;p&gt;对了，这期的活动相当火爆，一堆人不要命地冲排行榜，分数线超级膨胀。这段时间我也是在不停地打，准度熟练度也不断上来了，能 fc 一些 25 难度，但最后结算的时候少打了几场，被拉出了 5k 名开外……&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/bd-god.webp&quot; alt=&quot;打了几百首后，越发顺手了，就是准度不大行&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;打了几百首后，越发顺手了，就是准度不大行&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;游戏邦的事大概就水这些&lt;/p&gt;
&lt;h3&gt;染上嘎女省油这辈子就有了&lt;/h3&gt;
&lt;p&gt;想起来，上次对声优及其周边活动这个痴迷还是孤独摇滚时的 193 和 yoppi (5月21号已经是 “恒星” Live 的一周年了)，但从未有过像现在这样嗑大了的似的。&lt;/p&gt;
&lt;p&gt;看 MyGO 那天是 23 年的12月31号，正好是请了青木阳菜和立石凛过来的北京 IDO 动漫节，看到返图后我也就打个 haha 转发过了，完全想不到未来返回来考古时的那种感受 hhh，虽然正如 [24 年前半总结] 里谈到的，这会一直在补着 mygo 相关的，第一步痴迷状态，但也最多看看切片之类的，队员的推都还全 fo 完&lt;/p&gt;
&lt;p&gt;虽然不大记得了，但转变应该还得是看了她们的 Live、场内外的小互动，和一场场邦 TV，不经意间就 gachi 了 😭&lt;/p&gt;
&lt;p&gt;疯狂的开端还是突然想加一下各 q 群，然后就几乎改变了之后的日常，一下子又多了个可讨论的地方，虽然说后来来看这是不大好的……之后就是先爬下 go 相关的一堆照片、活动视频等等，甚至整理了一份 &lt;a href=&quot;https://www.kdocs.cn/l/cuGrkERZnByi&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;MyGO 史记&lt;/a&gt;，收集了一些活动时间线、访谈等等。期间还顺手改写了一下下载图片等一些脚本 hhh&lt;/p&gt;
&lt;p&gt;犯瘾最大的一会就是做翻译 😎 虽然不懂多少、只能猜出一些意思，然后靠 &lt;a href=&quot;https://memo.ac/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;MemoAI&lt;/a&gt; 做听写打轴、交给 GPT 翻译，我再来校对改错……好在之前看过了一些基本的语法之类的，最近也在猛学汉字单词的意思，有很多 AI 听不出来的还是能根据上下文来改过来。新法的蜜柑回差不多就是这样，还好这是比较简单的同轨单人在说话）&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/24-bili-trans.webp&quot; alt=&quot;我在干嘛啊😅&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;我在干嘛啊😅&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;接着就是一直在考古时，翻到了份好像没人翻译过的杂志访谈，于是也想着烤一下。前两篇是跟着照抄手打出来的 (后面就 OCR 了)，也是为了习惯日语键盘 (虽然也是敲罗马音出单词，但好多规则要适应)，然后再交给 GPT 烤一层，我再上下文润色一层）虽然方法挺蠢的，但也逐渐好理解多了&lt;/p&gt;
&lt;p&gt;期间收到了好多关注之类的，看到很多熟悉的烤肉 id，有种恍惚的感觉 hhh&lt;/p&gt;
&lt;p&gt;在素世世生日(27号)的前一天晚上，bestdori 照常偷跑了生日卡面信息）看完了特别爱素的故事剧情后，突然地特别想搬到b站去，于是就下了资源文件、导出台词翻译，再用 bestdori 地故事编辑器替换台词😎 但好像没找到导出下载故事的选项，就只好录屏了&lt;/p&gt;
&lt;p&gt;不愧是cp顶流，一晚上就一万播放了，消息简直看不过来……然后果然地在很多熟悉人中看到自己的id和作品，又是种奇妙的感觉）终将成为自己仰慕的人了&lt;/p&gt;
&lt;h3&gt;哎总的来说&lt;/h3&gt;
&lt;p&gt;哎最近越是考古邦邦的视频，就越觉得应该再早一些看才对的）bocchi 是22年的10月番来着，我想那时的我肯定会喜欢这种类型的 😫 老团以前的活动都好欢乐，Live 都很给力，ksm 形态的爱美太勾魂了 😭😭&lt;/p&gt;
&lt;p&gt;说到底一直在找的感觉都是那种 “音乐性” 吧，迷上了摇滚乐之后，音乐中带来的东西就更多了&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;这一篇从5月2号新建文件，一直拖到了27号才差不多写好一点……唉懒鬼&lt;/p&gt;
&lt;/blockquote&gt;
&lt;section data-footnotes=&quot;&quot; class=&quot;footnotes&quot;&gt;&lt;h2 class=&quot;sr-only&quot; id=&quot;footnote-label&quot;&gt;Footnotes&lt;/h2&gt;
&lt;ol&gt;
&lt;li id=&quot;user-content-fn-1&quot;&gt;
&lt;p&gt;&lt;a href=&quot;https://game.bilibili.com/bangdream&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;BanG Dream！新大少女乐队时代音游&lt;/a&gt; &lt;a href=&quot;#user-content-fnref-1&quot; data-footnote-backref=&quot;&quot; aria-label=&quot;Back to reference 1&quot; class=&quot;data-footnote-backref&quot;&gt;↩&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</content:encoded><author>Chilfish</author></item><item><title>(2) Weibo-archiver 存档你的微博 | 开发记录</title><link>https://chilfish.top/posts/weibo-archiver-2/</link><guid isPermaLink="true">https://chilfish.top/posts/weibo-archiver-2/</guid><description>将你的新浪微博存档备份，为号被完全夹没前绸缪 😭。支持导出为 HTML 文件、包含所有的图片、前15条评论</description><pubDate>Wed, 07 Feb 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;项目地址：&lt;a href=&quot;https://github.com/chilfish/Weibo-archiver&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Chilfish/Weibo-archiver&lt;/a&gt;，&lt;a href=&quot;weibo-archiver/&quot;&gt;前一集&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;最认真的一集&lt;/h2&gt;
&lt;p&gt;在忙完烦人的期末作业后，总算是想着拾起这个项目了 😅 随着用的人多了起来，以及竞品 (雾) &lt;a href=&quot;https://speechless.fun/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;speechless&lt;/a&gt; 大重构了，还用 Electron 发了桌面版，就想着应该也动手了起来&lt;/p&gt;
&lt;p&gt;一个有趣的现象是，脚本已经有好几百的下载量了，但 preview.zip 却没什么人下载，虽然已经在文档说得较为清楚了 hhh。于是加了个导出时顺带自动下载它&lt;/p&gt;
&lt;p&gt;最受宠若惊的是，想着试着把赞赏码放上去时，第二天就收到 ￥50 的打赏了……连忙把赞赏列表给刻在网站上了 &lt;a href=&quot;https://chilfish.top/sponsors&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;sponsors&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;再见了，饿了么&lt;/h3&gt;
&lt;p&gt;一开始图方便，就用了饿了么的组件库。但到后面，有时候太多的 hack 方法，和实在是看着不是很顺眼，于是就迁移到了 &lt;a href=&quot;https://www.naiveui.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;naive-ui&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;但没想到的是，麻烦事又多了起来 hhh 还是因为油猴的部分，在打包到外部引用时，一开始我用的是 auto-import 来自动导入组件，但最终打包的时候它总会打进很多没用上的组件和函数。最终的解决方式还是在 monkey 的 monorepo 中手动全局注册用到的组件&lt;/p&gt;
&lt;p&gt;但它用起来实在是舒服太多了，虽然还是有一些要手动修复的 hack bug&lt;/p&gt;
&lt;h3&gt;噢我的路由参数们&lt;/h3&gt;
&lt;p&gt;很多 bug 还是我自己平时要用的时候才发现的，开发时就没想到……&lt;/p&gt;
&lt;p&gt;在加功能的时候，想着将分页的状态 (pageSize、page) 添加到 url 中，这样不论是刷新还是什么都能保持了。组合式的 composable 函数是真的舒服，虽然不知道这么写 Pinia 对不对&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// stores/post.ts
const route = useRoute()
const router = useRouter()

const curPage = computed({
  get: () =&amp;gt; Number(route.query.page) || 1,
  set: (val: number) =&amp;gt; router.push({
    query: {
      ...route.query,
      page: val,
    },
  }),
})

const pageSize = computed({
  get: () =&amp;gt; Number(route.query.pageSize) || 10,
  set: (val: number) =&amp;gt; router.push({
    query: {
      ...route.query,
      pageSize: val,
    },
  }),
})
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;更现代的 monorepo&lt;/h3&gt;
&lt;p&gt;因为要开桌面版，于是先搜了一堆 electron 相关的最佳实践，发现它们的目录结构都是 &lt;code&gt;/packages&lt;/code&gt; 放共用、核心的部分，在 &lt;code&gt;/apps&lt;/code&gt; 则是最终的应用，如官网、web 版、桌面版等等&lt;/p&gt;
&lt;p&gt;于是我也学着重构了一番：[pull：refactor：monorepo directory structure #8]，换了些更有意义的文件夹命名&lt;/p&gt;
&lt;h3&gt;麻烦的图片&lt;/h3&gt;
&lt;p&gt;才发现图片懒加载一直都没凑效过，于是还是手动用经典的 &lt;code&gt;IntersectionObserver&lt;/code&gt; 来为所有的图片懒加载了：&lt;a href=&quot;https://github.com/Chilfish/Weibo-archiver/blob/39bd46f/packages/core/src/utils/dom.ts#L26&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;lazyLoadImages&lt;/a&gt;。默认的 src 是一张占位图，滑动到它时再动态更换到 &lt;code&gt;data-src&lt;/code&gt; 里的链接&lt;/p&gt;
&lt;p&gt;再就是 Gallery 的宫格图片了，样式是真的难调…… CSS 好难 hhh&lt;/p&gt;
&lt;h3&gt;规划项目&lt;/h3&gt;
&lt;p&gt;写了好几个小东西过后，逐渐意识到尽早规划的重要性 😅 边写边改、后续回过头来再改实在是太痛苦了，以及为了提醒自己、告知用户 (画饼)，完善了 README 的说明、加了一个&lt;a href=&quot;https://github.com/Chilfish/Weibo-archiver/issues/7&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;项目规划&lt;/a&gt;，并用 &lt;a href=&quot;https://todoist.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;todoist&lt;/a&gt; 来写好代办&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/dev-log/weibo-todo.webp&quot; alt=&quot;暂时列下的 todos&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;暂时列下的 todos&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;同时，在每次完成之后的划掉它的感觉是真的舒服 🥳 成就感超大，超可视化。接下来就是先试手 Electron 开发，之后再迁移过去了&lt;/p&gt;
&lt;h2&gt;最注重用户体验的改动&lt;/h2&gt;
&lt;p&gt;后知后觉地意识到现在地操作实在是有些复杂，下载完图片之后，把数据文件 &lt;code&gt;data.mjs&lt;/code&gt; 复制到 web 页面打包的 assets 文件夹里，然后启动 vite 服务器 😅&lt;/p&gt;
&lt;h3&gt;改为在线服务平台的形式&lt;/h3&gt;
&lt;p&gt;突然地想到了 &lt;a href=&quot;https://chatkit.app%EF%BC%8C%E5%AE%83%E4%B9%9F%E6%98%AF%E4%B8%80%E4%B8%AA%E5%9F%BA%E6%9C%AC%E6%B2%A1%E5%90%8E%E7%AB%AF%E6%95%B0%E6%8D%AE%E5%BA%93&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;https://chatkit.app，它也是一个基本没后端数据库&lt;/a&gt; (抛开接口代理和在线分享来说)，所有的交互、数据都存在用户浏览器本地中。或许我也可以改成这样的形式？详见&lt;a href=&quot;https://github.com/Chilfish/Weibo-archiver/discussions/26&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;讨论 #26&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;我将 web 页面部署到了 vercel 上，用户只要将脚本页导出的数据 &lt;code&gt;weibo-data.json&lt;/code&gt; 导入 weibo.chilfish.top 就能够在线查看了。然后我找了个解析微博图片的 &lt;a href=&quot;https://cdn.ipfsscan.io/weibo/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;ipfs 图床&lt;/a&gt;，这样图片也不必一定要下载了 🥳&lt;/p&gt;
&lt;p&gt;这简直就是天才想法 hhh 而且这么做最大的一个好处就是，我经常改 web 的一些 ui 和逻辑，要发布的时候就不会像以前一样都要开 release (用户迁移的时候也很麻烦，要复制替换原先的数据文件)，而是直接 push 给 vercel 自动部署，只要刷新一下缓存就能体验到改动&lt;/p&gt;
&lt;p&gt;而分享给其他人的时候，只需要将数据文件一同发送过去、导入就行了 😎 (感觉可以选择范围到导出数据)&lt;/p&gt;
&lt;h3&gt;数据都存在 indexedDB 里&lt;/h3&gt;
&lt;p&gt;相对地，数据使用 indexedDB 存在浏览器里，它是 NoSQL 的一种，能实现很多像是建立索引、游标分页等操作，这比以前全加载到内存里操作 json 好多了。记在了 [pr：indexedDB #23]&lt;/p&gt;
&lt;p&gt;使用的是 &lt;a href=&quot;https://github.com/jakearchibald/idb&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;jakearchibald/idb&lt;/a&gt; 强大的 indexedDB 库，对原生操作基本都完整封装拓展了。只不过在全文搜索时，还是没想好怎么做比较好，毕竟 indexedDB 还是 key-val 式的数据库，一开始还想着先中文分词然后建索引，但最终还是用经典的 &lt;a href=&quot;https://www.fusejs.io/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;fusejs&lt;/a&gt; 来实现了&lt;/p&gt;
&lt;p&gt;代码在 [core：storage.ts]。越看越觉得写得太厉害了 😎&lt;/p&gt;
&lt;h3&gt;设置页&lt;/h3&gt;
&lt;p&gt;想着，既然都能够切换图床 (用 cdn 或是本地图片)，那就顺便把设置页面也做了，毕竟 header 没地方放了 hhh&lt;/p&gt;
&lt;p&gt;还得是 chatkit.app，抄了它的夜间模式切换的组件 ui、弹窗式的 settings、tab 来切换 setting 和 about 这些类别&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/weibo/settings.webp&quot; alt=&quot;简单的设置页&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;简单的设置页&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3&gt;多用户支持&lt;/h3&gt;
&lt;p&gt;难免会有要备份多个用户的需求，以前都是每个用户都要复制 web 的 dist，再 cd 到对应的目录来启动 vite。但现在既然都存到浏览器里了，那就应该利用上 indexedDB 多表 (类似) 的功能。详见 [pr：multi user #36]&lt;/p&gt;
&lt;p&gt;一些元数据都存在 localStorage 里，监听 curUid 的变化，然后改变对应的表名 (每个用户就是一张数据表)，同时页面上的微博数据也跟着改变。一切都是响应变化的，速度也超级快&lt;/p&gt;
&lt;h3&gt;按时间范围筛选&lt;/h3&gt;
&lt;p&gt;一开始觉得这个不是很必要就没想起要做，但在最近要写总结报告翻微博看看发生了什么时，才意识到漏了什么 (然后总结报告又拖了几天……)&lt;/p&gt;
&lt;p&gt;首先我对微博的创建时间建立了索引，这样插入、查询的时候就能按时间来排序了，然后配合上分页的的游标查询、持久化在 url 中，也不难实现。只是处理边界条件的时候有些棘手了 (鉴定为没有熟练掌握 vue 导致的)&lt;/p&gt;
&lt;p&gt;例如范围 a 里有 300 条微博，用户切换到了第 25 页，这是他想切到只有 10 条微博的时间范围 b 时，这时候还是第 25 页，就导致游标越界了。所以应该改为只要切换时间范围，就把页码设为 1 就好了 😅&lt;/p&gt;
&lt;h3&gt;CI/CD 与自动部署&lt;/h3&gt;
&lt;p&gt;因为这是一个 monorepo，而我仅需要部署里面的 apps/web 部分，同时也只应该下载与它有关的依赖 (总不能让它连 electron 都下了吧)&lt;/p&gt;
&lt;p&gt;部署到 vercel 时首先遇到的是找不到输出了，尽管已经指定了输出目录，但却不能识别框架类别，上线全 404……然后才发现要把 project root directory 设为 apps/web，这样就能一键识别了&lt;/p&gt;
&lt;p&gt;同时要改一下构建的条件，现在每次推送都会触发构建，有时改的就没涉及到 web 的部分，但好在可以设置 &lt;a href=&quot;https://vercel.com/guides/how-do-i-use-the-ignored-build-step-field-on-vercel&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;vercel ignored build step&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-js&quot;&gt;const {
  VERCEL_GIT_COMMIT_REF,
  VERCEL_GIT_COMMIT_MESSAGE,
} = process.env

// 在 main 分支，commit message 包含 web，或是 release、update deps
// 在包含 web 的任何分支
// 若不在 main 或 web 分支，则只要 commit message 包含 web
const messages = [
  &apos;release&apos;,
  &apos;update deps&apos;,
  &apos;web&apos;,
]
const shouldProceed = messages.some(message =&amp;gt; VERCEL_GIT_COMMIT_MESSAGE.includes(message))
const isMainBranch = VERCEL_GIT_COMMIT_REF === &apos;main&apos;
const isWebBranch = VERCEL_GIT_COMMIT_REF.includes(&apos;web&apos;)

if (
  (isMainBranch &amp;amp;&amp;amp; shouldProceed)
  || isWebBranch
  || shouldProceed
) {
  console.log(&apos;✅ - Build can proceed&apos;)
  process.exit(1)
}
else {
  console.log(&apos;🛑 - Build cancelled&apos;)
  process.exit(0)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;而我还希望能够每次 push 都构建一份 beta 版本，于是学了一下 GitHub Actions，将构建的产物上传到 artifact 工件里&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-yml&quot;&gt;name: beta Build

on:
  workflow_dispatch:
  push:
    branches-ignore:
      - monkey
    paths-ignore:
      - &apos;**.md&apos;
      - &apos;.github/**&apos;
      - &apos;!.github/workflows/**&apos;
      - &apos;apps/desktop/**&apos;
      - packages/database

jobs:
  install-and-build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - uses: pnpm/action-setup@v3
        name: Install pnpm
        with:
          version: 8
          run_install: false

      - name: Get pnpm store directory
        shell: bash
        run: |
          echo &quot;STORE_PATH=$(pnpm store path --silent)&quot; &amp;gt;&amp;gt; $GITHUB_ENV

      - uses: actions/cache@v4
        name: Setup pnpm cache
        with:
          path: ${{ env.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-store-${{ hashFiles(&apos;**/pnpm-lock.yaml&apos;) }}
          restore-keys: |
            ${{ runner.os }}-pnpm-store-

      - name: Install monkey
        run: pnpm install:monkey

      - name: Install Web
        run: pnpm install:web

      - name: build and zip
        run: pnpm release

      - name: upload monkey
        uses: actions/upload-artifact@v4
        with:
          name: weibo-archiver.user.js
          path: dist/weibo-archiver.user.js

      - name: upload web
        uses: actions/upload-artifact@v4
        with:
          name: weibo-archiver-webapp
          path: dist/weibo-archiver-webapp.zip

      - name: upload scripts
        uses: actions/upload-artifact@v4
        with:
          name: weibo-archiver-scripts
          path: dist/weibo-archiver-scripts.zip
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;CLI 版本&lt;/h3&gt;
&lt;p&gt;收到了个 CLI 版本的功能请求，要可以在命令行里调用，就能够实现定时运行了。正好也一直很想做一份 CLI，之前重构 core 就是为了能够以库的形式单独运行爬虫，或是在 electron 的 Node 进程里调用&lt;/p&gt;
&lt;p&gt;用的是 &lt;a href=&quot;https://github.com/unjs/citty/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;unjs/citty&lt;/a&gt; 库来构建，&lt;a href=&quot;https://github.com/unjs/unbuild&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;unjs/unbuild&lt;/a&gt; 来打包，又一次地和 rollup 打包器斗智斗勇了好一会 😹&lt;/p&gt;
&lt;p&gt;发现为了引用并打包 monorepo 下的其他 package，应该将它放在 devDependencies 下，并将它的依赖放在 peerDependencies 中，这样打包时就能够 tree-shake 地将它们打包在一起了&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>2024上 记录</title><link>https://chilfish.top/posts/2024-1/</link><guid isPermaLink="true">https://chilfish.top/posts/2024-1/</guid><pubDate>Thu, 08 Feb 2024 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;音一会，Go 一辈子&lt;/h3&gt;
&lt;p&gt;咱以 2023 年最后一天补完 &lt;a href=&quot;https://bgm.tv/subject/428735&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;MyGo!!!!!&lt;/a&gt; 作为 2024 的开端，曾未想过在这之后的一个多月里，几乎每天每时每刻都在 MyGo!!!!! 相关 😭😭&lt;/p&gt;
&lt;p&gt;看完了 Staff A 官号的全部视频，下载了全部的 Live、有趣的二创视频、游戏剧情、音乐等等，士大夫们居然还有 &lt;a href=&quot;https://bang-dream.com/mygo_inst&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;MyGo instrumental&lt;/a&gt; 的纯音乐版 (tomorin 不在场系列)，台词场景什么的都快倒背如流了，但还是觉得实在不满足 😭 但还得等年中猫猫专场的剧场版、2025 年的母鸡卡……现在就靠着补充的游戏剧情 ([〖BanG Dream！It&apos;s MyGO!!!!!〗活动剧情〖中字〗])、最喜欢的二创 (&lt;a href=&quot;https://space.bilibili.com/7477105/channel/collectiondetail?sid=1948104&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;经典灵魂互换，但是爱音和睦&lt;/a&gt;)、每日一溜的迷跡波等等来度日 😹😹&lt;/p&gt;
&lt;p&gt;可以说在这之前完全没有什么作品能给我带来如此巨大的感觉、戒断感，里面的每一个人都能找到喜欢的角度，很多时候都能感觉 “天啊这简直就是我”，所以赶快端上来罢 ∑🍺&lt;/p&gt;
&lt;p&gt;也第一次决定要买相关的周边了，生日时被送了单专 &lt;strong&gt;“迷星叫”&lt;/strong&gt;，简直太让人触动了。同时又发了 &lt;a href=&quot;https://gekkan-bushi.com/topics/mygofootprints/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;mygo!!!!! 设定集&lt;/a&gt;的附带广播剧试听的视频，直接就是脑子热地下载萌购、查一堆相关事项之后，￥190+ 下单了 😎&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;过去了两个半月的现在，食粮就是声优们了 😭 想了想，应该是从孤独摇滚后粉上主唱长谷川育美 193 和第一次听声优广播——青山吉能的孤独广播开始，逐渐地关注上这方面的内容。恒星 live、孤独舞台剧过后，更加地对这样 2.5 次元企划感到不可自拔，活着就是为了看这个的。jpg。我现在就是噶起的状态了&lt;/p&gt;
&lt;p&gt;我是从真夜中开始接触到 jpop、rock 相关的音乐，所以乐队的感觉实在是太喜欢了 😭 好在 mygo 的歌都十分地对胃口，羊也特别地对电波的感觉，这才有机会看起了早期被劝退的 mygo 动漫 hhh&lt;/p&gt;
&lt;p&gt;现在甚至重拾了久违的&lt;a href=&quot;https://res.wokanxing.info/jpgramma/index.html&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;日语语法书&lt;/a&gt;，虽然目前听了很多的声优广播、关注了很多的声优推，理解大致的意思的程度还算可以，但还是很日本语下脚 desu。设定集毕竟还是全生肉，也是想圆个搁置很久的日语梦）&lt;/p&gt;
&lt;h3&gt;Astro yes&lt;/h3&gt;
&lt;p&gt;前些时候看到了个博客 &lt;a href=&quot;https://github.com/nexxeln/nexxel.dev&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;nexxel.dev&lt;/a&gt;，果然酷，astro+vue+soild 揉在一起，也想着找时间重构一下了。期间还去看了 &lt;code&gt;@nuxt/content&lt;/code&gt;，稍微试了一下，还是感觉很麻烦&lt;/p&gt;
&lt;p&gt;感受到了 &lt;a href=&quot;https://github.com/remarkjs/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;remark.js&lt;/a&gt; 实在是太强了，靠着它的生态库实现了很多好久就想做的功能——自定义解析 markdown。像是外链前的 icon、将 &lt;code&gt;![alt](src)&lt;/code&gt; 的 markdown 图片语法转为 &lt;code&gt;&amp;lt;figure&amp;gt;&lt;/code&gt;，然后再配合 naive-ui 来实现图片预览、懒加载等等。详见：&lt;a href=&quot;../remarkjs-diy-md/&quot;&gt;使用 Remark.js 自定义渲染 MD&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;相较于之前的 vuepress，自定义程度超级高，不限于纯 markdown，SSR + SSG 的构建也很舒服，所有的 markdown 都在构架期间就都编译成 HTML 了，部分页面 (如要动态 fetch 数据) 可设为 SSR&lt;/p&gt;
&lt;p&gt;近期 (3月中) 还将原先按文件夹做路由的形式，统一打平到 &lt;code&gt;/posts/{slug}&lt;/code&gt; 了。文件夹还是不变，这只是让作者区分的，映射到 url 的就不包含文件夹了，而是用文件名来区分，这样短了很多。并为了迁移兼容，还会尝试将 404 的链接重定向到新的 url&lt;/p&gt;
&lt;p&gt;还稍微更新了下拖了很久的 about 页，也是因为 “音乐性” 的关系，听歌总榜很多歌都不怎么再听了，也将它换到了最近的红心音乐 😇&lt;/p&gt;
&lt;h3&gt;其他&lt;/h3&gt;
&lt;p&gt;这第一个月可以说是相当活跃充实的一月，闲下来的时候全在 Go!!!!!，然后就是 Github 修这个那个的。学了老早想做的 Astro，看了 React 的文档，Electron 入门徘徊着，参与社区讨论等等 😇&lt;/p&gt;
&lt;h3&gt;再尝试开源社区&lt;/h3&gt;
&lt;p&gt;在日常逛着 Discord 的时候，看到了这么一篇 [Lazy Load for images received via API in Markdown component？]，这不正好在折腾着的图片懒加载嘛，于是抱着试一下的想法写了个最小实现的方法给他&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/discord-astro-0.webp&quot; alt=&quot;好欸&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;好欸&lt;/figcaption&gt;&lt;/figure&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/discord-astro-1.webp&quot; alt=&quot;另一篇随手答的求助&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;另一篇随手答的求助&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;这种随手帮助的感觉还是很爽的 😎😎&lt;/p&gt;
&lt;p&gt;其中还向仰慕已久的 unjs 组织交了一个 docs 修改的 pr：&lt;a href=&quot;https://github.com/unjs/mdbox/pull/14&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;unjs/mdbox #14&lt;/a&gt;，虽然过了好几天才合并，但看到作者发的 &lt;a href=&quot;https://github.com/pi0/tired-maintainer&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;pi0/tired-maintainer&lt;/a&gt;，直接一个敬礼理解 🤯&lt;/p&gt;
&lt;h3&gt;rip 网易云音乐 api&lt;/h3&gt;
&lt;p&gt;最终这些搞 api 逆向都没能逃过的一劫：&lt;a href=&quot;https://github.com/Binaryify/NeteaseCloudMusicApi&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Binaryify/NeteaseCloudMusicApi&lt;/a&gt; 还是被发律师函删光代码 archive 了 😭 但好在没删仓库，issue 什么的都在、在删前不久同步了 fork&lt;/p&gt;
&lt;p&gt;最近 (3月中) 突然想来研究一下 (因为 /music 用到了它，也因为 @DIYGod 把 RSShub 从 express.js 全部迁移到了 hono.js：&lt;a href=&quot;https://diygod.cc/6-year-of-rsshub&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;一个六岁开源项目的崩溃与新生&lt;/a&gt;)，于是也想着升级重写一下这个网易云 api (当然仅限于用到的这几个路由)&lt;/p&gt;
&lt;p&gt;先一通 update 依赖到新版本、装 &lt;code&gt;@antfu/eslint-config&lt;/code&gt; 格式化代码，然后感受到了来自历史遗留的翔味，这是怎么保持维护的啊）他们之前用的 lint 太宽松了，现在就基本每个文件都爆红 hhh。在一边手动改格式，一边尝试阅读理解，虽乱但强&lt;/p&gt;
&lt;p&gt;因为网易云的策略就是客户端加密请求的参数，服务端再解密，所以单纯地复制网络请求是不行的，得逆向出它的加密算法……好在原仓库早就做好了这些，只要复制粘贴就好）&lt;/p&gt;
&lt;p&gt;一开始也想着用最近的明星 hono.js 来写，快是很快了，但是部署到 vercel 上时有很多大问题……最大的责任就是，vercel 的 serverless function 不能完整地支持 ESM + Typescript。也是因为这一点，新版的 RSSHub 也不能在 vercel 中部署，会直接 500 报错……&lt;/p&gt;
&lt;p&gt;期间我折腾了一堆的 hack 方法来解决这个问题，如用 rollup 将 src 的 hono 代码打包成 cjs 格式，再让 vercel.json 配置来启动它。同时我发觉到一个相同的地方：hono 也是替代 express.js 的方案之一，于是能用 express 的那一套方法来部署 hono&lt;/p&gt;
&lt;p&gt;使用 express 的原网易云项目和旧版 RSShub 也能部署到 vercel 上，但因为它是 CJS + js 的，所以能很顺畅地运行 😤 于是我就在想，为什么不用完美多平台运行时开箱即用的 &lt;a href=&quot;https://nitro.unjs.io/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;nitro.unjs.io&lt;/a&gt; 捏……？这是 Nuxt 的 server 实现，我更加熟悉才是 😭&lt;/p&gt;
&lt;p&gt;然后就是复制代码迁移的过程了，要把原本的 CJS 换成 ts+ESM，把 axsio 换成 nitro 自带的 ofetch，更好的最佳实现写法……&lt;/p&gt;
&lt;p&gt;尽量按原文档将模块路由还原到 /server 目录下 (文件式路由)，接口使用什么的都没变，再加上一些固定的缓存，基本就好了。写在了 &lt;a href=&quot;https://github.com/Chilfish/nitro-ncm&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;nitro-ncm&lt;/a&gt;，但只有两个路由，因为目前我就用到这些）&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>使用 Remark.js 自定义渲染 MD</title><link>https://chilfish.top/posts/remarkjs-diy-md/</link><guid isPermaLink="true">https://chilfish.top/posts/remarkjs-diy-md/</guid><description>使用 remark.js 和 remark-rehype 来自定义渲染 markdown，实现外链网站的图标、图片懒加载、阅读时间等</description><pubDate>Thu, 14 Mar 2024 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;Astro.js yes&lt;/h3&gt;
&lt;p&gt;迁移到 Astro 的原因之一是，尽管 vuepress 有许多插件可以扩展 Markdown 的功能，但自定义程度仍然太低。虽然也可以编写相应的插件，但既然选择了 Astro 并手动编写主题样式，那也少不了自定义解析 Markdown。&lt;/p&gt;
&lt;p&gt;Astro.js 使用 &lt;a href=&quot;https://github.com/remarkjs/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;remark.js&lt;/a&gt; 进行 Markdown 解析并转换为 HTML，然后使用 &lt;a href=&quot;https://github.com/remarkjs/remark-rehype&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;remark-rehype&lt;/a&gt; 修改编译后的 HTML，在配置文件中体现在 [config：markdown.remarkPlugins] 中。&lt;/p&gt;
&lt;p&gt;本次打算实现以下内容：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;为外部链接添加对应网站图标，类似前面几个链接；&lt;/li&gt;
&lt;li&gt;统一图片格式，将 &lt;code&gt;![alt](src)&lt;/code&gt; 的 Markdown 语法转换为用 &lt;code&gt;&amp;lt;figcaption&amp;gt;&lt;/code&gt; 包裹的 img 标签，并将 alt 属性作为图片注释；&lt;/li&gt;
&lt;li&gt;对图片设置懒加载：将所有 src 替换为占位符，在滚动到视图时再替换回原始 src；&lt;/li&gt;
&lt;li&gt;解决引用本地文件和在 Astro 构建时表现不一致的问题；&lt;/li&gt;
&lt;li&gt;计算大约阅读时间和字数。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;所有源码实现可见于 &lt;a href=&quot;https://github.com/Chilfish/chilfish.top/tree/e420f60/src/plugins&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;plugins&lt;/a&gt;。&lt;/p&gt;
&lt;h3&gt;注意的点&lt;/h3&gt;
&lt;p&gt;图标方案使用 Unocss 提供的图标库，在匹配到对应 hostname 后会添加相应的 &lt;code&gt;&amp;lt;i class={icon-class}/&amp;gt;&lt;/code&gt;。由于这是动态生成的内容，在构建时 Unocss 不会输出相关图标 CSS。&lt;/p&gt;
&lt;p&gt;需要预先准备好一个包含图标信息的数组，并将其添加到 &lt;a href=&quot;https://unocss.dev/guide/extracting#safelist&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;unocss safelist&lt;/a&gt; 中。(同时要注意在导入至 &lt;code&gt;unocss.config.ts&lt;/code&gt; 时，在配置阶段不能导入与 Astro 相关无关包，需要单独处理：&lt;a href=&quot;https://github.com/Chilfish/chilfish.top/tree/e420f60/src/constant/hostIcons.ts&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;constant/hostIcons.ts&lt;/a&gt;)。&lt;/p&gt;
&lt;p&gt;此外，在 remark 阶段似乎没有直接访问 Astro 上下文信息。因此无法使用任何 Astro 函数；但可以导入类型。&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>(1) Weibo-archiver 存档你的微博 | 开发记录</title><link>https://chilfish.top/posts/weibo-archiver/</link><guid isPermaLink="true">https://chilfish.top/posts/weibo-archiver/</guid><description>将你的新浪微博存档备份，为号被完全夹没前绸缪 😭。支持导出为 HTML 文件、包含所有的图片、前15条评论</description><pubDate>Thu, 31 Aug 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;项目地址：&lt;a href=&quot;https://github.com/chilfish/Weibo-archiver&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Chilfish/Weibo-archiver&lt;/a&gt;，&lt;a href=&quot;weibo-archiver-2/&quot;&gt;第二集&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;还得自己写一份&lt;/h2&gt;
&lt;p&gt;之前微博号莫名被夹过一次 (&lt;a href=&quot;../diary/2023-s.md#2023-03-13&quot;&gt;2023-03&lt;/a&gt;) 后，才意识到是不是该先手备份一份才对，还好只是禁言禁动作，那三千多条微博还是能看。那时翻遍了都没找到几个用得舒服的，特别是我想将它存为 HTML 之类的，图片存到本地，还能做全文搜索、OCR 搜索等等&lt;/p&gt;
&lt;p&gt;倒是看到个看着还行的插件，虽然它目的是导出成 PDF，但它是将结果重绘过后重新渲染到本页的 innerHTML 里的，然后再用浏览器的打印来导出 PDF。但这样有很多问题，图片查看不了，毕竟得裁切；最终的 UI 也很简洁；再就是暴力地 innerHTML 的结果就是，当数据量特别大的时候，特别他还是一边获取一边插入渲染的，CPU 快被干爆了 hhh&lt;/p&gt;
&lt;p&gt;于是当天 fork 后改了改 UI，并将图片全替换成本地的，导出图片链接的数组，再就是手动分页，&lt;a href=&quot;https://github.com/chilfish/weibo-backup/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;backup&lt;/a&gt;。虽然也还是特别难用，也是能用就行，但手动分页实在是太麻烦了，也不支持按时间范围获取，一直想着什么时候重构一遍&lt;/p&gt;
&lt;p&gt;于是就冒出了个想法：用 Vue 来写油猴脚本 (后续原作者也用 Vue + Axios 重写了遍)。然后一直拖到了最近才想起来，好在一搜就找到了个 vite 插件 &lt;a href=&quot;https://github.com/lisonge/vite-plugin-monkey&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;monkey-vite&lt;/a&gt;，只要是 vite build 的都能写到油猴中，那这太好了呀&lt;/p&gt;
&lt;p&gt;后续写着写着也顺便用 todo 了好久的 monorepo 结构、element-plus、前端分页等等。发了稳定版的 Release，后续应该不大想加新功能了，自用已经够用太多了&lt;/p&gt;
&lt;h2&gt;开始&lt;/h2&gt;
&lt;p&gt;写到中间时才又再次想到，又忘记先完整规划再下手......到后面就是边磨蹭边改，然后突然想明白再推翻重做 😅😅&lt;/p&gt;
&lt;h3&gt;一开始的想法&lt;/h3&gt;
&lt;p&gt;脚本在个人主页运行，于是就匹配 &lt;code&gt;/u/:uid&lt;/code&gt; 和 &lt;code&gt;/n/:name&lt;/code&gt; 这两个路径，但一开始非常蠢地想都没想就用启动模板的 &lt;code&gt;vite-plugin-pages&lt;/code&gt; 文件即路由来创建了个 &lt;code&gt;/pages/u/[id]&lt;/code&gt; 的文件）虽然也能跑是吧，然后觉得有些麻烦就用了 vue-router 来匹配 id。到这一步都还是处于能跑的状态，但直到 build 了才发现 router-view 就是不显示。这时候才拍脑袋想到，用 &lt;code&gt;document.URL.match&lt;/code&gt; 是不是更简单一些......&lt;/p&gt;
&lt;p&gt;再就是一个比较糟的 DX，vite 的热重载是用 ws 来保持连接的，但配合上 monkey 的插件之后在火狐中就连接成了 wss，导致证书问题和 404 而连不上......只好到 edge 来开发）后来想到可能是因为我是在 &lt;code&gt;https://weibo.com&lt;/code&gt; 这个 host 下运行的，被 vite 判断成 &lt;code&gt;importMetaUrl.protocol === &apos;https:&apos; ? &apos;wss&apos; : &apos;ws&apos;&lt;/code&gt; 了 wss。但很玄学的是只有火狐是这样的，edge 连的还是 ws......到头来就是开了好几个 Chromium，15G 小内存被吃爆了好几次&lt;/p&gt;
&lt;p&gt;可能是要延续做法 (懒得再动脑)，也要一个预览按钮。于是当时的做法是渲染 VNode，然后清空微博 Vue #app 的 innerHTML，再 appendChild 进去。还想着分页，用 pinia 维护了当前页和微博数组，但蠢的是，虽然每次的翻页都是对应地改变当前页就行，但我的做法居然是又再调用渲染插入那一套......后来遇到 bug 时才想到这样做直接丢失了先前的状态，而由于翻页的同时又改了 pinia 的当前页，所以一直感觉良好。但菜后知后觉地想到当前页的数组已经是 &lt;code&gt;computed(() =&amp;gt; postStore.get())&lt;/code&gt; 了，所以只要改了 pinia 里的当前页就能响应地改过来 hhh&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;后续是直接取消在油猴中的预览了&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;数据获取部分，偷懒就用了 vueuse 的 useFetch，设好 createFetch 的 baseUrl 就行 (后来再想，应该设置 base 为 &lt;code&gt;/ajax&lt;/code&gt; 而不是 &lt;code&gt;https://weibo.com/ajax&lt;/code&gt;，这样 localhost 跨域的时候至少还能设置代理之类的)&lt;/p&gt;
&lt;p&gt;最难受的部分之一就是数据清洗......先写好想要的类型，然后就是从返回的 json 捡垃圾了。但历史遗留的问题吧，微博的接口实在是太混乱了 hhh，同个东西换个地方就换字段名了、同一个接口里的字段有不同的名称写法，驼峰和下划线混用就算了，复数的 s 有时在前有时在后 hhh。反正到最后这个 parser 写了快两百行，才算是写了个能用的&lt;/p&gt;
&lt;h3&gt;图片预览&lt;/h3&gt;
&lt;p&gt;其中，图片防盗链的问题，b 站 (转发卡片的图片) 和微博的策略不同，只好在油猴预览时就按原链接用 weibo 的 referer，本地预览就换为 &lt;code&gt;/assets/img&lt;/code&gt; 这样的本地图片 (但存在数据里的还是原图链接)。插曲是，为了能够解析带图转发的图片，想法是将它转换为自定义协议 &lt;code&gt;[img://${src}]&lt;/code&gt;，而后显示的时候再解析成一个 &lt;code&gt;&amp;lt;button data-src=&quot;${path}&quot;&amp;gt;查看图片&amp;lt;/button&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;const retweetImg = /&amp;lt;a[^&amp;gt;]*href=&quot;([^&quot;]*)&quot;[^&amp;gt;]*&amp;gt;查看图片&amp;lt;\/a&amp;gt;/.exec(text)

if (retweetImg &amp;amp;&amp;amp; retweetImg[1]) {
  const img = retweetImg[1]
  text = text.replace(retweetImg[0], `[img://${img}]`)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这样就需要一个全局的图片预览器，这里用了一个比较取巧的方式来实现。在 &lt;code&gt;&amp;lt;Text/&amp;gt;&lt;/code&gt; 组件中，先获取所有文本中的 button (只有这种行内图片才用 button，当然也能换成别的选择器)&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;const parsedText = parseProtocol(props.text)

// 或许不该这么写......
onMounted(async () =&amp;gt; {
  const btns = await waitForElement(&apos;button&apos;)

  btns?.forEach((e) =&amp;gt; {
    e.onclick = (_) =&amp;gt; {
      const url = e.dataset.src
      if (url)
        usePostStore().viewImg = url
    }
  })
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;用 pinia 来存要预览的图片链接。然后这个 viewer 就 watch 它，借用 el-image 的相册预览功能，有变化时就自动点击预览它&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-vue&quot;&gt;&amp;lt;script setup lang=&quot;ts&quot;&amp;gt;
const postStore = usePostStore()

watch(
  () =&amp;gt; postStore.viewImg,
  async () =&amp;gt; {
    if (postStore.viewImg === imgViewSrc)
      return
    const img = await waitForElement&amp;lt;HTMLImageElement&amp;gt;(&apos;#img-viewer img&apos;)
    img?.[0]?.click()
  },
)
&amp;lt;/script&amp;gt;

&amp;lt;template&amp;gt;
  &amp;lt;div id=&quot;img-viewer&quot; class=&quot;absolute right-0 top-0&quot;&amp;gt;
    &amp;lt;el-image
      class=&quot;h-0 w-0&quot;
      :src=&quot;replaceImg(postStore.viewImg)&quot;
      :lazy=&quot;true&quot;
      :hide-on-click-modal=&quot;true&quot;
      :preview-teleported=&quot;true&quot;
      :preview-src-list=&quot;[postStore.viewImg]&quot;
      @close=&quot;() =&amp;gt; (postStore.viewImg = imgViewSrc)&quot;
    /&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/template&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;其中，默认情况下是用一个 1x1 的透明占位图，以免图片 404 后 el-image 的 img 标签就变成了 &lt;code&gt;&amp;lt;p&amp;gt;Failed&amp;lt;/p&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export const imgViewSrc
  = &apos;data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7&apos;
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;糟糕的开始——数据导出&lt;/h3&gt;
&lt;p&gt;快收工时又才发现没考虑一个问题：数据导出？&lt;/p&gt;
&lt;p&gt;导出了清洗后的微博。json 和图片链接。csv，但本地预览的 HTML 怎么办捏。因为都是 vue，肯定得先编译才会有生产版本的 HTML 嘛，但脑瓜不精灵总想着在浏览器中完成 (也就是在 build 中再 build 另一份 vue hhh)。睡醒后才又拍脑瓜，只要手动 build 出预览的部分，然后一同打包到 Release 里就好了嘛&lt;/p&gt;
&lt;p&gt;同时又遇到个难题，在预览中是要导入用户数据的，也就是最后打包的时候要让这部分与 index 分离 (因为 vite 的打包都是 Bundle 到一个文件里的)，这时候就要手动配置 vite build 的逻辑了&lt;/p&gt;
&lt;p&gt;首先将 pinia 的 posts 不设为默认的空数组，而是导入另起的文件 data.js&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import _posts from &apos;../static/data.js&apos; // 后来显式地改为了 data.mjs

// in defineStore
// 必须是外部导入优先, 这样才能在 build 中直接引用
const posts = ref(
  (_posts as unknown as Post[]).sort((a, b) =&amp;gt; Number(b.id) - Number(a.id)), // 按 id 也就是发布时间降序排列
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后在 vite.config.ts 中设置，将 data.js 单独出来，并将 js|css 都打包到 assets 文件夹下，同时要出掉他们的 hash 命名，这样就能直接覆盖源文件了&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;const dataJs = path_to_data

export default defineConfig({
  ...config,
  build: {
    rollupOptions: {
      input: {
        index: path_to_index_html,
        data: dataJs,
      },
      output: {
        entryFileNames: &apos;assets/[name].mjs&apos;,
        globals: {
          [dataJs]: &apos;data&apos;,
        },
      },
    },
  },
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;也就是在这时候，意识到了打包 monkey 和预览的 vue 是冲突的，必须手动注释掉其中一个才能打包另一个......于是想到了 monorepo，将共同的部分抽离到 /core 中，/preview 和 /monkey 分离来开，单独配置&lt;/p&gt;
&lt;p&gt;还是在当晚，看了会 pnpm + monorepo 的组成和使用，逐渐理解起来，并顺利迁移了过去 😇&lt;/p&gt;
&lt;p&gt;其中，需要单独设置各自的 vite.config，只要&lt;del&gt;继承&lt;/del&gt; (解构赋值) 自共同的根目录的配置就行 (像是 vue、UnoCSS 那些的)。以 /monkey 为例：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// /packages/monkey/vite.config.ts
export default defineConfig({
  ...config,
  build: {
    outDir: path.resolve(root, &apos;dist&apos;),
    rollupOptions: {
      output: {
        plugins: [terser()], // 压缩输出，打包直接少一半的体积
      },
    },
  },
  plugins: [
    ...config.plugins!, // 一定要先声明这个，否则就相当于覆盖了根配置的 plugins 数组
    monkey({
      entry: &apos;src/main.ts&apos;,
      userscript: {
        name: &apos;Weibo Archiver&apos;,
      },
      // ... 等等其他配置
    }),
  ],
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后在根 package.json 配置 scripts 就好：&lt;code&gt;&quot;dev:preview&quot;: &quot;pnpm -F preview dev&quot;, &quot;dev:monkey&quot;: &quot;pnpm -F monkey dev&quot;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;重构完睡醒后就发了第一个能跑的 Release，后续几天就是在完善功能了&lt;/p&gt;
&lt;h3&gt;全文搜索&lt;/h3&gt;
&lt;p&gt;想着还是得写一个搜索功能，好找一点。据我的一点点了解，这部分似乎需要先中文分词，然后建立与 id 的索引，于是没多想就这么做了）&lt;/p&gt;
&lt;p&gt;但搜出来的包都是需要 node 环境，以及鉴于词库的存在，分词是不会在浏览器完成的，于是需要一个后端&lt;/p&gt;
&lt;p&gt;但同时要打包出来，就搜到了 vite-express-plugin 的插件，能跑&lt;/p&gt;
&lt;p&gt;就这么写了好一会能出结果了，build 的时候才想到，那依赖怎么办......它要么是打进单文件里，要么是 resolver 出来，但既不提供 package.json，也不会复制 node_module 过去&lt;/p&gt;
&lt;p&gt;因为还真没想过像是 express 的 node 服务要怎么 “打包”，再就是服务端直接 &lt;code&gt;node main.js&lt;/code&gt; 就行了，似乎也用不上打包这个动作）一般都是上传代码，然后运行 pnpm i 之类的就行。只有浏览器才需要这么一个 “可执行” 入口，才要将依赖打包进单文件里&lt;/p&gt;
&lt;p&gt;于是苦心研究了下 rollup，最终的结果是手动复制一份非 dev 的依赖的 package.json 进 dist，再手动 npm i 和 node main ......&lt;/p&gt;
&lt;p&gt;实在是麻烦......于是又睡醒后拍大脑，不考虑性能什么的，用正则岂不是更快实现......？&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;async function searchText(p: string): Promise&amp;lt;Post[]&amp;gt; {
  const res = posts.value.filter((post) =&amp;gt; {
    const word = p.toLowerCase().trim().replace(/ /g, &apos;&apos;)
    const regex = new RegExp(word, &apos;gim&apos;)
    return (
      regex.test(post.text)
      || (post.card &amp;amp;&amp;amp; regex.test(post.card?.title))
      || (post.retweeted_status &amp;amp;&amp;amp; regex.test(post.retweeted_status?.text))
    )
  })

  resultPosts.value = res
  return res
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;心酸历程：&lt;a href=&quot;https://github.com/Chilfish/Weibo-archiver/pull/2&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;pr/search&lt;/a&gt;。写服务期间，还是没想明白 ts-node 与 module 的共存写法，最后还是换成了 js 来写，瞬间舒服极了&lt;/p&gt;
&lt;h3&gt;添加更多的 fetch 选项&lt;/h3&gt;
&lt;p&gt;一想到也许有些人的微博有数万条，要是不能筛选就麻烦了，于是就连忙加了一些 options 来给用户选择&lt;/p&gt;
&lt;h3&gt;还得是用 Vite 来预览结果&lt;/h3&gt;
&lt;p&gt;在有人反馈之前，我都没意识到之前的 server.py 有着直接打不开的致命问题……尝试了很久，但还是很难解决 serve 一个 vue SPA 的一系列问题。最终还是改为 Vite 来预览了，顺便把下载图片也转一手 Node 版本，最后连同 node_modules 一起打包到 Release 里。这样用户只需要下载 node 就行了&lt;/p&gt;
&lt;p&gt;并加了个说明：&lt;a href=&quot;https://github.com/Chilfish/Weibo-archiver/issues/5&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;issues/#5&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;最后……？&lt;/h3&gt;
&lt;p&gt;完成搜索后，可以说就完结了，不大再想新增功能，够用就行......改改 bug 就好&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;实际上并没有 hhh&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;总的来讲，还是学了挺多的，虽然弯路和坑太多了 😅😅&lt;/p&gt;
&lt;h2&gt;在这之后&lt;/h2&gt;
&lt;p&gt;最近在自搜的时候发现这个项目被人推荐了：&lt;a href=&quot;https://weibo.com/1684197391/NncPS3sud&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;小众软件&lt;/a&gt;，还有一百多的转发，瞬间觉得两股战战 hhh）多了好多 stars&lt;/p&gt;
&lt;p&gt;吓得立刻改了几个地方，然后才发现导出按钮没反应是因为 jsZip 的新版本与油猴有些冲突了，但在开发环境是没问题了，这只好降级解决了。并添加了几个导出的选项，毕竟他们可能有几万、十几万条微博，不过滤像是转发、评论区等的话，这实在是太不合理了&lt;/p&gt;
&lt;p&gt;还有一点，用的人多起来后 (恰逢微博准备开始前端实名制，这会有更多的用户有需求存档他们的微博)，意识到了一点是，应该降低使用门槛、简化操作，这样才能让更多人能用得上&lt;/p&gt;
&lt;p&gt;于是接下来打算打包到 Tauri 上，数据的处理等等全都自动化，用户只要简单地登录、设置、导出就好了。查看结果也可以很简单地直接打开 app 就能加载了，还能很方便地支持多用户&lt;/p&gt;
&lt;p&gt;下载图片这部分还能尝试一下 Rust 的加速），用户就不需要额外的环境配置。而且像是分词索引这部分也就能很合理地存在用户电脑上，不用再正则暴力搜索了&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>2023 末？</title><link>https://chilfish.top/posts/2023-years/</link><guid isPermaLink="true">https://chilfish.top/posts/2023-years/</guid><pubDate>Sat, 13 Jan 2024 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;TODO&lt;/h3&gt;
&lt;p&gt;忘光光了捏&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/2023-2024.webp&quot; alt=&quot;只是过了12个月而已😎&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;只是过了12个月而已😎&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3&gt;一些记录&lt;/h3&gt;
&lt;h4&gt;动漫们&lt;/h4&gt;
&lt;p&gt;整理了下，今年看得不是很多，但基本都是要看一辈子的了 😎&lt;/p&gt;
&lt;p&gt;这个列表还是从 &lt;a href=&quot;https://bgm.tv/anime/browser/airtime/2023?sort=rank&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;bgm.tv&lt;/a&gt; 上手动 F12 筛出来的，补番的话就是搜索出来，复制卡片的 HTML 再 append 回去 😹 忘了好像有个很方便地筛年度动漫的工具，也就凑合着看吧 hhh&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/23-anime.webp&quot; alt=&quot;From bgm.tv&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;From bgm.tv&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;年底前突然想着听 MyGo!!!!! 的歌 (当然是从春日影开始 😎)，之后就一发不可收拾。在 31 号完成了大部分的大作业和考试之后，那种感觉来了，起床之后立马启动了起来，还是带 b 站弹幕的存档&lt;/p&gt;
&lt;p&gt;后劲真的很足，连忙去官号补了一堆的切片、翻唱、live，还有无数的二创和泛鸽的吐槽，现在就是纯生活必需品了 😫&lt;/p&gt;
&lt;p&gt;我觉得它给我最大的情绪感的是灯宝，其次是祥子 (特别是在众多二创中所表达的情感)，最喜欢的还是猫猫 (以及圣青木)。发现即便知道是 🐏 在唱，但带入 tomorin 来想的话，可以说完全是另一种感觉 😭&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/mygo-meme.webp&quot; alt=&quot;还得等一年的母鸡卡😫&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;还得等一年的母鸡卡😫&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;2022 年末还在 bocchi 感的时候，欧尼酱来了……完后接了个大魔境，看一半直接第一次地将漫画给补完了 😣 全是特别让人共鸣的&lt;/p&gt;
&lt;p&gt;暑假很拼命地补了 90 集的巨人，不愧是名著，后劲也特别大……最爱的当然是衝撃这首 ED&lt;/p&gt;
&lt;p&gt;听了很久的 Avid，和冲着长谷川育美的想法，国庆补了 86，很喜欢 😚&lt;/p&gt;
&lt;p&gt;总的来说，我看番几乎都是音乐驱动型+芳文，吸引我的更多在于音乐、角色和声优上。MyGo 爆火的那段时间尝试看了下，但第一集的 3D 和架子是在太劝退了 hhh 但把歌听完后 (灯宝立功 😎)、看到第三集，基本就确诊为染上 MyGo 了&lt;/p&gt;
&lt;h4&gt;Coding&lt;/h4&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/diary/2023-time.webp&quot; alt=&quot;Activities&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;Activities&lt;/figcaption&gt;&lt;/figure&gt;
&lt;figure&gt;&lt;embed style=&quot;width: 70%&quot; src=&quot;https://wakatime.com/share/@Chilfish/171112ac-ec19-44f7-a3df-d3c8626cdccb.svg&quot;&gt;&lt;/figure&gt;
&lt;p&gt;相对地来讲，2023 年是特别活跃的一年。给别人项目交了第一个重构的 pr、提了一些 bug issues，自用的一个小工具也赚了 30+ 的 stars🥳&lt;/p&gt;
&lt;figure&gt;
  &lt;img src=&quot;https://opengraph.githubassets.com/1/Chilfish/Weibo-archiver&quot; alt=&quot;weibo-archiver&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;
  &lt;figcaption&gt;
    好欸！&lt;a href=&quot;https://github.com/Chilfish/Weibo-archiver&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Repo&lt;/a&gt;
  &lt;/figcaption&gt;
&lt;/figure&gt;
&lt;figure&gt;
  &lt;img src=&quot;https://opengraph.githubassets.com/1/un-pany/v3-admin-vite/pull/133&quot; alt=&quot;pr for v3-admin-vite&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;
  &lt;figcaption&gt;
    输出了我的代码洁癖：&lt;a href=&quot;https://github.com/un-pany/v3-admin-vite/pull/133&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;#133&lt;/a&gt;
  &lt;/figcaption&gt;
&lt;/figure&gt;
</content:encoded><author>Chilfish</author></item><item><title>应该使用 GET/POST 获取返回 200 的状态码的 API</title><link>https://chilfish.top/posts/return-all-http200-api/</link><guid isPermaLink="true">https://chilfish.top/posts/return-all-http200-api/</guid><pubDate>Tue, 12 Dec 2023 12:12:12 GMT</pubDate><content:encoded>&lt;h3&gt;似乎所有人都这么做&lt;/h3&gt;
&lt;p&gt;经常做爬虫的时候总会观察到这么一个现象，很多网站的 API 都会只会返回 200 的状态码，即使是请求失败了，也会返回 200 的状态码，然后在返回的数据中会有一个 &lt;code&gt;code&lt;/code&gt; 字段，用来表示请求是否成功，比如：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;code&quot;: &quot;not_found_user&quot;,
  &quot;data&quot;: null,
  &quot;message&quot;: &quot;用户不存在&quot;,
  &quot;success&quot;: false,
  &quot;statusCode&quot;: 404
}
&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/api200_example.webp&quot; alt=&quot;看似全都是 200，但实际有些是未登录的状态&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;看似全都是 200，但实际有些是未登录的状态&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;正好也看到知乎的一个讨论：&lt;a href=&quot;https://www.zhihu.com/question/513865370/answer/2338966743&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;为什么那么多公司做前后端分离项目后端响应的 HTTP 状态一律 200？&lt;/a&gt;&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/api200_zhihu.webp&quot; alt=&quot;&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;感觉确实很对，从运维的角度来看，这样做确实会方便很多。例如 vercel 的 log 对于大于 400 的状态码都会标黄或是标红，但很多时候都是只业务层面的错误，而不是系统层面的错误，这样的话就会造成很多误解，而且也不方便排查问题&lt;/p&gt;
&lt;p&gt;而对于开发来讲，有些 fetch 客户端对于大于 400 的状态码都会抛出异常，这样的话就需要在每个请求的地方都去捕获异常……&lt;/p&gt;
&lt;p&gt;再就是，面对复杂的业务逻辑，HTTP 状态码的表达能力实在是不足。虽然也能塞业务 code 到 body 里，但还是有些麻烦 hhhh&lt;/p&gt;
&lt;p&gt;当然，还有个月经问题是，GET/POST 比 RESTful API 会舒服、直观很多，把操作方法放在 url 而不是 Method&lt;/p&gt;
&lt;p&gt;所以再见了，RESTful API😹&lt;/p&gt;
&lt;h3&gt;实现&lt;/h3&gt;
&lt;p&gt;先说后端，我们可以继承自 Error 的类 MyError，然后设定一系列的业务错误码，然后在业务层面抛出 MyError 的实例，然后在中间件中捕获这个错误，以 200 的状态码返回&lt;/p&gt;
&lt;p&gt;这里还涉及到了一个思想，就是不再使用频繁地使用 try-catch 来捕获异常，而是只用 throw 掉它，再在全局的地方去捕获它，这样的话就可以减少很多重复的代码&lt;/p&gt;
&lt;h4&gt;Nuxt Server&lt;/h4&gt;
&lt;p&gt;以 Nuxt.js/Nitro 为例，它支持手动配置全局的异常处理函数：&lt;a href=&quot;https://nitro.unjs.io/config#errorhandler&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;errorHandler&lt;/a&gt;。需要现在 nuxt.config.ts 中添加：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export default defineNuxtConfig({
  nitro: {
    errorHandler: &apos;~/error/nitroErrorHandler.ts&apos;,
  },
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后捕获函数：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export default &amp;lt;NitroErrorHandler&amp;gt; async function (error: MyError, event) {
  const code = (error.cause as any)?.code || error.code
  const err = newError(code, undefined, error) // 根据 code 生成新的错误

  const { message, ...rest } = err

  if (err.statusCode &amp;gt;= 500)
    consola.error({ ...error })

  const res = event.node.res
  res.setHeader(&apos;Content-Type&apos;, &apos;application/json&apos;)
  res.statusCode = 200

  res.end(JSON.stringify({ message, ...rest }))
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;其中，对于错误码的定义，可以这么写&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export const Errors = [
  {
    code: &apos;unknown error&apos;,
    message: &apos;Server error&apos;,
    statusCode: 500,
    data: {},
  },
] as const // as const 在类型系统中特别好用

// the handled error codes
export const errorCode = Errors.map(e =&amp;gt; e.code)[0]

export type ErrorCode = typeof errorCode
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;得益于 &lt;code&gt;as const&lt;/code&gt;，这里的 ErrorCode 的类型全是字面量字符串，提供了很好的类型补全。这样就不用使用枚举来实现了，只需要输入特定的字符串即可完成类型检查&lt;/p&gt;
&lt;p&gt;对于返回的类型，可以这么写&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export type ErrorReturn = Omit&amp;lt;ApiReturn, &apos;code&apos;&amp;gt; &amp;amp; {
  code: ErrorCode
}

/**
 * the api return type
 */
export interface ApiReturn&amp;lt;T = any&amp;gt; {
  code: ErrorCode | &apos;ok&apos;
  statusCode: number
  message: string
  data?: T
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Nest.js&lt;/h4&gt;
&lt;p&gt;Nest.js 是支持自定义异常处理的，实现 ExceptionFilter 即可&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// /common/filters/any-exception.filter.ts
@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse&amp;lt;Response&amp;gt;()

    const code = exception.code || &apos;unknown error&apos;
    const error = newError(code, null, exception)

    response.status(200).json(error)
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后在全局模块中添加：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import { Module } from &apos;@nestjs/common&apos;
import { APP_FILTER } from &apos;@nestjs/core/constants&apos;

import { AnyExceptionFilter } from &apos;./common/filters/any-exception.filter&apos;

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: AnyExceptionFilter,
    },
  ],
  // ...
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Spring Boot&lt;/h4&gt;
&lt;p&gt;SB 可以捕获在 Controller 中抛出的异常，然后在全局的地方去处理它，这里需要用到 &lt;code&gt;@ControllerAdvice&lt;/code&gt; 注解，然后在类中添加 &lt;code&gt;@ExceptionHandler&lt;/code&gt; 注解&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@ControllerAdvice
class GlobalExceptionHandler :
    BasicErrorController(DefaultErrorAttributes(), ErrorProperties()) {

    @ExceptionHandler(Exception::class)
    fun handleException(ex: Exception): ResponseEntity&amp;lt;ApiReturn&amp;lt;Nothing?&amp;gt;&amp;gt; {
        if (ex !is MyError) {
            ex.printStackTrace()
            return response(ErrorCode.UNKNOWN_ERROR, 500, ex.toString(), null)
        }
        return response(ex.code, ex.statusCode, ex.message, null)
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;但是，对于在 controller 层之前抛出的错误，如 Filter 等，就需要在 Filter 中手动捕获，然后重定向到一个特定的 error url，然后在这个 url 中再抛出错误，这样才能被 &lt;code&gt;@ControllerAdvice&lt;/code&gt; 捕获到&lt;/p&gt;
&lt;p&gt;其中，包装的统一 api response 的函数：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;data class ApiReturn&amp;lt;T&amp;gt;(
    val code: ErrorCode = ErrorCode.OK,
    val statusCode: Int = 200,
    val message: String = &quot;ok&quot;,
    val data: T? = null
)

fun &amp;lt;T&amp;gt; response(
    code: ErrorCode = ErrorCode.OK,
    statusCode: Int = 200,
    message: String = &quot;ok&quot;,
    data: T
) = ResponseEntity.ok(
    ApiReturn(code, statusCode, message, data)
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;而一系列的错误码可以通过一个枚举类来定义&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;enum class ErrorCode {
    OK,
    UNKNOWN_ERROR,
    // ...
}

data class MyError(
    val code: ErrorCode = ErrorCode.UNKNOWN_ERROR,
    val statusCode: Int = 500,
    override val message: String = &quot;Internal Server Error&quot;,
) : Exception()

val Errors = listOf(
    MyError(ErrorCode.NOT_FOUND_USER, 404, &quot;User not found&quot;),
    // ...
)

fun newError(code: ErrorCode) = Errors.firstOrNull { it.code == code } ?: MyError()
&lt;/code&gt;&lt;/pre&gt;
</content:encoded><author>Chilfish</author></item><item><title>Chilpost Spring Boot Kotlin 后端实现</title><link>https://chilfish.top/posts/chilpost-sb/</link><guid isPermaLink="true">https://chilfish.top/posts/chilpost-sb/</guid><pubDate>Tue, 12 Dec 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;咱还是因为 Web 的大作业要求 Spring Boot，有些看不起 Node 后端，那还是写一份 SB 的实现吧 😹 当然，得是 Kotlin 的 😇&lt;/p&gt;
&lt;p&gt;咱放在了 &lt;a href=&quot;https://github.com/Chilfish/chilpost-sb&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;chilpost-sb&lt;/a&gt; 这个 repo 里&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;咱写着写着 Kotlin 版本的后端成了主线，Nuxt 得拖拖了，找个较好的 Node 后端技术栈
实在是因为 Kotlin 太甜了，让人很难推掉它 hhh&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;工具选择&lt;/h3&gt;
&lt;p&gt;除了 Spring Boot 外，还是用 Kotlin 友好的 &lt;a href=&quot;https://github.com/JetBrains/Exposed&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;JetBrains/Exposed&lt;/a&gt; 作为 SQL 框架，&lt;a href=&quot;https://bitbucket.org/b_c/jose4j/wiki/Home&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;org.bitbucket.b_c:jose4j&lt;/a&gt; 作为 JWT/JWS 的支持，和要求的 MySQL。依赖如下&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val exposedVersion = &quot;0.44.0&quot;

dependencies {
    implementation(&quot;org.jetbrains.exposed:exposed-core:$exposedVersion&quot;)
    implementation(&quot;org.jetbrains.exposed:exposed-dao:$exposedVersion&quot;)
    implementation(&quot;org.jetbrains.exposed:exposed-jdbc:$exposedVersion&quot;)
    implementation(&quot;org.jetbrains.exposed:exposed-json:$exposedVersion&quot;)
    implementation(&quot;org.jetbrains.exposed:exposed-java-time:$exposedVersion&quot;)
    implementation(&quot;org.jetbrains.exposed:exposed-spring-boot-starter:$exposedVersion&quot;)

    implementation(&quot;org.bitbucket.b_c:jose4j:0.9.3&quot;)
    implementation(&quot;org.springframework.boot:spring-boot-starter-web&quot;)

    implementation(&quot;org.jetbrains.kotlin:kotlin-reflect&quot;)
    implementation(&quot;org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.1&quot;)

    developmentOnly(&quot;org.springframework.boot:spring-boot-devtools&quot;)
    runtimeOnly(&quot;com.mysql:mysql-connector-j&quot;)
    testImplementation(&quot;org.springframework.boot:spring-boot-starter-test&quot;)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;开始&lt;/h3&gt;
&lt;p&gt;因为之前有写过 Nest.js (反过来了 hh)，所以还算是比较熟练 hhhh 且算是在 Nuxt 中写了还算好的后端最佳实践，现在要做的只是迁移到 SB 而已&lt;/p&gt;
&lt;p&gt;例如抛弃 Restful Api，改用 &lt;a href=&quot;../return-all-HTTP200-api.md#spring-boot&quot;&gt;all 200 api&lt;/a&gt;、统一的异常处理、JWS 等等&lt;/p&gt;
&lt;p&gt;比较惊艳的还是 Exposed 写 DAO，以及 Kotlin 语法的优雅。例如：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun getUserByEmail(email: String) = (UserTable innerJoin UserStatusTable)
    .select { UserTable.email eq email }
    .map(::toUserDetail)
    .firstOrNull() ?: throw newError(ErrorCode.NOT_FOUND_USER)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;虽然它不直接支持视图，但也能通过 Kotlin 来间接实现&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;fun postWithOwner() = PostTable
    .innerJoin(PostStatusTable)
    .join(
        UserTable,
        JoinType.INNER,
        PostTable.ownerId,
        UserTable.id
    )

fun postQuery() = postWithOwner().selectAll()
    .orderBy(PostTable.createdAt to SortOrder.DESC)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这些函数都是返回 &lt;code&gt;Query&lt;/code&gt;，可以继续链式调用，最后再 &lt;code&gt;map&lt;/code&gt; 到 DTO&lt;/p&gt;
&lt;h3&gt;不该返回自增 id 给前端&lt;/h3&gt;
&lt;p&gt;一直都是下意识地将主键 id 作为返回的 id，但其实这有很多的弊端，和不安全的地方。b 站将自增 AV 号换为了较为随机的 BV 号，uid 也改为固定长度的随机数字。这部分也是属于老生常谈的问题了，后续我都改为了 uuid 字符串&lt;/p&gt;
&lt;h3&gt;携用户信息的接口&lt;/h3&gt;
&lt;p&gt;有些接口对于登录用户是另一种表现，例如该推文是否点赞，这部分应该交由后端来查好了再返回给前端，而不是返回一个点赞的 id 数组。且不说实际上这个点赞数组在内部使用主键的自增 id 来存的，把超大的数组传过去似乎不是很合理 hhhh&lt;/p&gt;
&lt;p&gt;于是也还是使用携带的 token 中解析出用户信息，那这样就要改一下后端中间件的逻辑了，不在白名单列表 (如搜索、推文详情这些不强求登录后才能请求的路径) 并出错时才报错&lt;/p&gt;
&lt;p&gt;同时，为了更易读，应该将这个解析出来的用户命名为像是 ctxUser，表示这个接口 context 的 user，就不会和像是要关注别人的另一个 user 弄混了&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val token = req.getHeader(&quot;Authorization&quot;)?.trim()?.split(&quot; &quot;)
if (
    !isInWhiteList(path) &amp;amp;&amp;amp;
    (token.isNullOrEmpty() || token.size != 2 || token[0] != &quot;Bearer&quot;)
)
    throw newError(ErrorCode.INVALID_TOKEN)

val userInfo = verifyToken&amp;lt;TokenData&amp;gt;(token?.lastOrNull())

if (userInfo == null &amp;amp;&amp;amp; !isInWhiteList(path))
    throw newError(ErrorCode.INVALID_TOKEN)

req.setAttribute(&quot;ctxUser&quot;, userInfo)

chain.doFilter(request, response)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;外部文件支持&lt;/h3&gt;
&lt;p&gt;用户上传的文件应该放在专门的 OSS 服务器，或是本机中的某个地方，总之不是 resources，这是会被打包进 jar 中的&lt;/p&gt;
&lt;p&gt;于是为了 serve 外部文件，就得专门写一下文件路由：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;@Controller
@RequestMapping(&quot;/files&quot;)
class FileController {
    fun emptyFile(): File {
        val ba = ByteArray(0)
        val file = File.createTempFile(&quot;empty&quot;, &quot;file&quot;)
        file.writeBytes(ba)
        return file
    }

    @GetMapping(&quot;/**&quot;)
    fun getFile(): ResponseEntity&amp;lt;FileSystemResource&amp;gt; {
        val req = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request
        val filePath = req.servletPath.substringAfter(&quot;/files/&quot;)

        var file = File(&quot;files/$filePath&quot;)
        if (!file.exists()) {
            file = emptyFile()
        }
        val headers = HttpHeaders()
        headers.contentType = MediaType.APPLICATION_OCTET_STREAM
        headers.contentDisposition = ContentDisposition.builder(&quot;inline&quot;)
            .filename(file.name)
            .build()

        val resource = FileSystemResource(file)
        return ResponseEntity(resource, headers, HttpStatus.OK)
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;文件将保存在 &lt;code&gt;$pwd/files&lt;/code&gt; 下，同时它支持深度路径，即 &lt;code&gt;/files/a/b/c/d.png&lt;/code&gt;&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>锈化你的命令行工具</title><link>https://chilfish.top/posts/rustify-terminal/</link><guid isPermaLink="true">https://chilfish.top/posts/rustify-terminal/</guid><pubDate>Tue, 21 Nov 2023 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Rust 作为一门系统级语言，在命令行工具的开发上有着天然的优势。于是就在 Github 的 Rust topic 下找到了一些有意思的项目，并通过 &lt;a href=&quot;https://scoop.sh&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;scoop&lt;/a&gt; 安装到了 Windows 上&lt;/p&gt;
&lt;p&gt;这些工具通常都是系统自带软件的替代品，它们都使用 Rust 来重写，更现代、更快、更好用 😍，特别是 git 等的支持&lt;/p&gt;
&lt;h3&gt;bat&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/sharkdp/bat&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;sharkdp/bat&lt;/a&gt; 是一个 cat 的替代品，它的特点是语法高亮和 Git 集成&lt;/p&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/bat&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;eza&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/eza-community/eza&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;eza-community/eza&lt;/a&gt; 是一个 ls 的替代品，有更好看的输出、gitignore 支持、更多的排序方式等特性。这是我的一个配置&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-powershell&quot;&gt;function lss {
  eza -lnhaa --git-ignore --time-style &quot;+%m-%d %H:%m&quot; --no-quotes --sort type $args
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/eza&lt;/code&gt;&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/rustify_eza.webp&quot; alt=&quot;图片描述&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;图片描述&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3&gt;zoxide&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/ajeetdsouza/zoxide&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;ajeetdsouza/zoxide&lt;/a&gt; 是一个 cd 的替代品，它会记录你的 cd 历史，然后根据你的输入进行模糊匹配。可以把 cd alias 到它：&lt;code&gt;New-Alias Set-LocationWithFnm z&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/zoxide&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;fd&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/sharkdp/fd&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;sharkdp/fd&lt;/a&gt;。fd 是 find 的快速且用户友好的替代方案，find 是 Unix/Linux 中用于遍历文件层次结构的内置命令行程序。fd 为最常见的用例提供固执己见的默认值。要按名称查找特定文件，请编写 fd PATTERN 而不是 &lt;code&gt;find -iname ‘*PATTERN*’&lt;/code&gt;。fd 也非常快，并且它带有大量选项，例如默认忽略。gitignore 中的隐藏目录、文件和模式&lt;/p&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/fd&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;starship&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/starship/starship&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;starship/starship&lt;/a&gt; 是一个适用于任何 shell 的快速、高度可定制的提示符。它的特点是快速、可定制、跨 shell、跨平台、内置模块化、多语言支持、高度可定制、支持所有主流的 shell。这是我的一个配置，在 &lt;code&gt;~/.config/starship.toml&lt;/code&gt; &lt;a href=&quot;https://gist.github.com/Chilfish/ddd52f779d87c648374178b6c341bd55&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;gist&lt;/a&gt;。同时需要安装额外的字体：&lt;a href=&quot;https://www.fontmirror.com/meslo-lg&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;meslo-lg&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/starship&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;ripgrep&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/BurntSushi/ripgrep&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;BurntSushi/ripgrep&lt;/a&gt; 是一个面向行的搜索工具，它递归地搜索当前目录中的正则表达式模式。默认情况下，ripgrep 将遵守 gitignore 规则并自动跳过隐藏文件/目录和二进制文件&lt;/p&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/ripgrep&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;fnm&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/Schniz/fnm&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Schniz/fnm&lt;/a&gt; 是一个更好用的 node 版本管理器，可以随意地下载、切换 node 的版本&lt;/p&gt;
&lt;h3&gt;tokei&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/XAMPPRocky/tokei&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;XAMPPRocky/tokei&lt;/a&gt; 是一个非常强非续快的代码行数统计工具，默认通过 gitignore 来排除文件，基本支持所有主流的语言，甚至连 Vue、markdown 的内嵌语言都统计了&lt;/p&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/tokei&lt;/code&gt;&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/rustify_tokei.webp&quot; alt=&quot;&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3&gt;nushell&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/nushell/nushell&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;nushell/nushell&lt;/a&gt; 是一个现代的 shell，它使用 Rust 编写，具有友好的语法和强大的自动补全功能。它使用 nu 语言来作为其脚本语言，它是一种数据导向的 shell，它的语法类似于 SQL，但是它的数据类型是动态的，并完全地支持管道和函数式编程。更多详见其文档&lt;/p&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/nushell&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;miniserver&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/svenstaro/miniserve&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;svenstaro/miniserve&lt;/a&gt; 是一个通过 http(s) 启动文件服务器的工具，默认支持局域网访问、文件树、认证等功能，甚至能通过发起请求来上传文件 (差个按钮)。可以抛弃 live-server 或是 vite 了）&lt;/p&gt;
&lt;p&gt;下载：&lt;code&gt;scoop install main/miniserve&lt;/code&gt;&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>用 createVNode 封装一个 Toast</title><link>https://chilfish.top/posts/vnode-sfc-toast/</link><guid isPermaLink="true">https://chilfish.top/posts/vnode-sfc-toast/</guid><pubDate>Sun, 20 Aug 2023 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;开始&lt;/h3&gt;
&lt;p&gt;一直很想封装一个 Toast 来着，但想到用函数的形式来调用 &lt;code&gt;Toast(&apos;hello&apos;)&lt;/code&gt;，才意识到这似乎有一点难搞，于是就去翻看了 element-plus 的实现：&lt;a href=&quot;https://github.com/element-plus/element-plus/tree/dev/packages/components/message/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;el-message&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;果然还是要用到函数式渲染的 createVNode 来调用组件 SFC，完整可见：&lt;a href=&quot;https://github.com/Chilfish/learn-vue/tree/vue/src/components/Toast&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Github&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Vue Plugin&lt;/h3&gt;
&lt;p&gt;我们按 “它是怎么被导入并调用” 的思路来理解源码&lt;/p&gt;
&lt;p&gt;先从&lt;a href=&quot;https://element-plus.org/zh-CN/guide/quickstart.html&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;引入 element-plus&lt;/a&gt; 的文档开始，它只要 import 并 &lt;code&gt;app.use(ElementPlus)&lt;/code&gt; 就能使用了，而 &lt;a href=&quot;https://cn.vuejs.org/api/application.html#app-use&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;vue app.use&lt;/a&gt; 指的是安装一个插件，&lt;a href=&quot;https://cn.vuejs.org/guide/reusability/plugins.html&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;vue Plugin&lt;/a&gt; 是一个有 &lt;code&gt;install()&lt;/code&gt; 方法的用在 Vue 全局的工具代码&lt;/p&gt;
&lt;p&gt;element-plus 是一个 monorepo，在 /packages 下是项目各个包的根目录，从 &lt;code&gt;import ElementPlus from &apos;element-plus&apos;&lt;/code&gt; 在仓库中找到 &lt;a href=&quot;https://github.com/element-plus/element-plus/tree/dev/packages/element-plus&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;/packages/element-plus&lt;/a&gt; 这就是它的入口处。在 index.ts 中可以看出它导出了将所有组件和插件设为 vue installer 插件&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import Components from &apos;./component&apos;
// /packages/element-plus/default
import { makeInstaller } from &apos;./make-installer&apos;
import Plugins from &apos;./plugin&apos;

export default makeInstaller([...Components, ...Plugins])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;顺着过去找到 makeInstaller 的定义，它的作用就是将这些组件们打包成一个 element-plus 插件，然后就可以在 vue 入口处使用了 (app.use())&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;/**
 * Create a component installer that installs all the components
 * @param components the components or plugins to install
 * @returns the plugin installer
 */
export function makeInstaller(components: Plugin[] = []) {
  return {
    install(app: App) {
      // already installed the plugin
      if ((this as any)[INSTALLED_KEY])
        return;
      (this as any)[INSTALLED_KEY] = true

      // install all components
      components.forEach((component) =&amp;gt; {
        app.use(component)
      })
    },
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;上面是它简化后的样子，其实他还有一个前置步骤是将组件包装成 vue 插件，然后再在这里全部导入 (从 forEach 就可以看出，这就是文档说的全量导入)。这时候我们再点进 &lt;code&gt;/packages/components&lt;/code&gt; 里的一个组件 (如 Message)，可以看出它是这样写的&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// 这其实引用的是本仓库的包，这就是 monorepo 的应用之一，用类似别名的方式，告别费脑子的相对路径
import { withInstallFunction } from &apos;@element-plus/utils&apos;
import Message from &apos;./src/method&apos;

export const ElMessage = withInstallFunction(Message, &apos;$message&apos;)
export default ElMessage
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;重点就是这个 &lt;code&gt;withInstallFunction&lt;/code&gt;，它是将函数组件打包成可调用的关键，但我们先看看远处的组件引用再回过头来看就能更好地李姐了&lt;/p&gt;
&lt;h3&gt;Component With Install&lt;/h3&gt;
&lt;p&gt;我们先换一个常规点的组件来看，例如 button，它的使用方式就是简单的 &lt;code&gt;&amp;lt;el-button/&amp;gt;&lt;/code&gt; 就好了。在 button 的定义中，简化一下就是 &lt;code&gt;export const ElButton = withInstall(Button) // Button.vue&lt;/code&gt;，这个 &lt;code&gt;withInstall&lt;/code&gt; 写法如下&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;/**
 * @description mark a component as installable
 */
export type SFCWithInstall&amp;lt;T&amp;gt; = T &amp;amp; Plugin

/**
 * add install method to a component to register it globally
 * @param main the component (SFC.vue)
 * @returns the component with install method
 */
export function withInstall&amp;lt;T extends Component&amp;gt;(main: T) {
  const cp = main as SFCWithInstall&amp;lt;T&amp;gt;
  cp.install = (app: App) =&amp;gt; {
    app.component(cp.name!, cp)
  }
  return cp
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;首先定义的类型是因为，其实有 &lt;a href=&quot;https://cn.vuejs.org/guide/components/registration.html#global-registration&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;vue app.component()&lt;/a&gt; 这样全局注册组件的方式，也就是说其实每个组件 SFC (*.vue 文件) 都是可 install 的，但又不是每个 SFC 都是组件 (defineComponent())，所以需要显示声明它的类型为 Plugin，同时必须要在 SFC 中指定它的名字&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-vue&quot;&gt;&amp;lt;script lang=&quot;ts&quot; setup&amp;gt;
// 注意不要和 HTML 标签重名了，大小写不敏感，毕竟推崇的是 &amp;lt;my-button/&amp;gt; 的使用方法
defineOptions({
  name: &apos;MyButton&apos;,
})
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;所以这个函数做的就是全局注册这些组件，然后只要 &lt;code&gt;export const MyButton = withInstall(Button)&lt;/code&gt; 就好，然后再统一在 components.ts 中导入并导出给 installer，最后只需要在 vue 的入口 main.ts 中 &lt;code&gt;app.use(installer)&lt;/code&gt; 就完成了组件注册&lt;/p&gt;
&lt;p&gt;这么做的原因是为了可以直接在入口处统一导入，而不用一次次地 &lt;code&gt;app.component()&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;Function With Install&lt;/h3&gt;
&lt;p&gt;如果想要以函数的方式来召唤组件，就要使用 createVNode 来创建组件。与组件注册不同的是，它是注册到全局方法中，并要为它指定全局上下文 context，以访问一些全局的信息 (如依赖注入或是其他的 app.config.globalProperties 方法)&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;/**
 * @description mark a function as installable and add a context property
 */
export type SFCInstallWithContext&amp;lt;T&amp;gt; = SFCWithInstall&amp;lt;T&amp;gt; &amp;amp; {
  _context: AppContext | null
}

/**
 * @description add a function as a globalProperties and installable
 */
export function withInstallFunction&amp;lt;T&amp;gt;(fn: T, name: string) {
  const fnWithContext = fn as SFCInstallWithContext&amp;lt;T&amp;gt;;

  (fn as SFCWithInstall&amp;lt;T&amp;gt;).install = (app: App) =&amp;gt; {
    fnWithContext._context = app._context
    app.config.globalProperties[name] = fn // use $name to access the function
  }

  return fnWithContext
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;至此，全局组件的封装大致就是这些了，接下来是如何用函数来调用组件&lt;/p&gt;
&lt;h3&gt;createVNode&lt;/h3&gt;
&lt;p&gt;我们先写好 &lt;code&gt;Toast.vue&lt;/code&gt;，并为了方便管理，将 props 抽离出来，以 &lt;a href=&quot;https://cn.vuejs.org/guide/typescript/composition-api.html#typing-component-props&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;props 运行时声明&lt;/a&gt;的形式来写，再在 SFC 中 import&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export const definePropType = &amp;lt;T&amp;gt;(val: any): PropType&amp;lt;T&amp;gt; =&amp;gt; val

export const toastDefault = {
  id: &apos;&apos;,
  message: &apos;&apos;,
  type: &apos;info&apos;,
  appendTo: isClient ? document.body : (undefined as never),
  offset: 16,
  onClose: undefined,
} as const

export const toastProps = {
  message: {
    type: String,
    default: toastDefault.message,
  },

  type: {
    type: String,
    default: toastDefault.type,
  },

  onClose: {
    type: definePropType&amp;lt;() =&amp;gt; void&amp;gt;(Function),
  },
  // ...
} as const
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;其中，为了能够给它完整的一生...命周期，用 &lt;code&gt;transition&lt;/code&gt; 和 &lt;code&gt;v-show&lt;/code&gt; 的形式绑定 hooks，这样就能在 Toast 消失后回收它，而不只是 &lt;code&gt;v-if&lt;/code&gt;。毕竟每一个 Toast 都是一个新的实例，没用了就要销毁，不然可能会内存堆积 (好像是吧)&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-vue&quot;&gt;&amp;lt;template&amp;gt;
  &amp;lt;transition name=&quot;fade&quot; @before-leave=&quot;onClose&quot; @after-leave=&quot;onDestroy&quot;&amp;gt;
    &amp;lt;div
      v-show=&quot;show&quot;
      ref=&quot;toastRef&quot;
      class=&quot;toast&quot;
      :class=&quot;type&quot;
      :style=&quot;{ top: `${offset}px` }&quot;
    &amp;gt;
      {{ message }}
    &amp;lt;/div&amp;gt;
  &amp;lt;/transition&amp;gt;
&amp;lt;/template&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;那么要怎么调用这个生命 hook 呢？因为我们把它写在了 props 中，于是就要在调用方声明它&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import ToastConstructor from &apos;./Toast.vue&apos;

function createToast(
  { appendTo, ...options }: ToastParamsNormalized,
  context?: AppContext | null,
): ToastInstance {
  const container = document.createElement(&apos;div&apos;)
  const id = `toast-${id_++}`

  const props = {
    ...options,
    id,
    onClose: () =&amp;gt; {
      rmInstance(id) // 会有一个专门的 instance.ts 来管理这些实例
    },
    onDestroy: () =&amp;gt; {
      render(null, container) // 这样就能从 body 中移除这个标签了
    },
  }

  const vnode = createVNode(ToastConstructor, props)
  vnode.appContext = context || toast._context // 上文说的要指定它的 context

  render(vnode, container) // 渲染成 HTML

  // 当 destroy 的时候，gc 会自动回收这个 div 的
  appendTo.appendChild(container.firstElementChild!)

  // Toast.vue 组件本身，目的是为了能够获取它的一些信息
  // 如高度和 offset，这样才能让 Toast 们那位置排列好而不是叠在一起
  const vm = vnode.component!
  const instance: ToastInstance = {
    id,
    vm,
    vnode,
    props: (vnode.component as any).props,
  }
  instances.push(instance) // 先进先出，后来者在最下面

  return instance
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Toast Offset&lt;/h3&gt;
&lt;p&gt;Toast 通常是 &lt;code&gt;position: fix;&lt;/code&gt;，为了不让创建出来的组件全堆在一起，我们需要为它指定 &lt;code&gt;top: ${offset}px&lt;/code&gt;。这时候就需要维护一个 Toast 实例的数组，获取当前显示的 Toasts 中最后一个的 offset。并且这一切都得是响应式的，在先出的组件消失之后，后续的 offset 也要随之减少以适应位置&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export const instances: ToastInstance[] = shallowReactive([])

export function getInstance(id: string) {
  const idx = instances.findIndex(item =&amp;gt; item.id === id)
  const curr = instances[idx]
  let prev: ToastInstance | undefined
  if (idx &amp;gt; 0)
    prev = instances[idx - 1]

  return { curr, prev }
}

export function rmInstance(id: string) {
  const idx = instances.findIndex(item =&amp;gt; item.id === id)
  if (idx === -1)
    return
  instances[idx].handler.close()
  instances.splice(idx, 1)
}

export function getLastOffset(id: string) {
  const { prev } = getInstance(id)
  if (!prev)
    return toastDefault.offset
  return prev.vm.exposed!.bottom.value // 来自 Toast.vue 的 defineExpose
}

export function getOffsetOrSpace(id: string, offset: number) {
  const idx = instances.findIndex(item =&amp;gt; item.id === id)
  return idx &amp;gt; 0 ? toastDefault.offset : offset
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后在 Toast.vue 中堆计算属性就行 (下面的示例忽略了计时器的处理)&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import { useResizeObserver } from &apos;@vueuse/core&apos;

const toastRef = ref&amp;lt;HTMLElement&amp;gt;()
const height = ref(0)
// 上一个 Toast 的底部位置
const lastOffset = computed(() =&amp;gt; getLastOffset(props.id))

// 这个 Toast 的 offset 就等于 上一个 bottom + 固定 offset
const offset = computed(
  () =&amp;gt; getOffsetOrSpace(props.id, props.offset) + lastOffset.value,
)

// 这个 Toast 的底部位置
const bottom = computed((): number =&amp;gt; height.value + offset.value)

useResizeObserver(toastRef, () =&amp;gt; {
  // 获取 Toast 的高度
  height.value = toastRef.value!.getBoundingClientRect().height
})

defineExpose({
  bottom,
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;到这里，基本原理基本就是讲完了，但最重要的还是传参的设置与类型安全&lt;/p&gt;
&lt;h3&gt;Toast Options Params&lt;/h3&gt;
&lt;p&gt;调用这个 Toast，可能有下面这些方式&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;Toast(&apos;hello&apos;) // default to info Toast

Toast({ message: &apos;hello&apos;, type: &apos;info&apos; })

Toast.error({ message: &apos;error&apos;, duration: 4000 })
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;首先要将所有的参数都设为可选的 (Partial&amp;lt;T&amp;gt;)，对于 type，虽然是 string，但要限定于 &lt;code&gt;&apos;info&apos; | &apos;error&apos;&lt;/code&gt; 等这些类型。这就是为什么要把 props 抽离出来，这也是为了方便管理这些参数&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import type {
  AppContext,
  ComponentInternalInstance,
  ExtractPropTypes,
  VNode,
} from &apos;vue&apos;

export type ToastType = &apos;info&apos; | &apos;success&apos; | &apos;warning&apos; | &apos;error&apos;

export type ToastProps = ExtractPropTypes&amp;lt;
  Omit&amp;lt;typeof toastProps, &apos;type&apos;&amp;gt; &amp;amp; {
    readonly type?: ToastType // 这是为了将 string 类型转为上面那几种
  }
&amp;gt;

// 从 props 中排除掉 id 并全设为可选的
// 同时 appendTo 是在 createVNode 那边指定的，并不在 Toast.vue 中，所以要另外指定，这也是可选的
export type ToastOptions = Partial&amp;lt;Omit&amp;lt;ToastProps, &apos;id&apos;&amp;gt;&amp;gt; &amp;amp; {
  appendTo?: HTMLElement
}

// Toast 的参数，string 或是 options 对象
export type ToastParams = ToastOptions | ToastOptions[&apos;message&apos;]

// 为了能够将纯 string 解析为原先默认的 options 对象
// 这里就全是必选的
export type ToastParamsNormalized = Omit&amp;lt;ToastProps, &apos;id&apos;&amp;gt; &amp;amp; {
  appendTo: HTMLElement
}

// Toast 函数的返回，为了能让调用方手动提前 close
export interface ToastHandler {
  close: () =&amp;gt; void
}

// Toast 函数本体
export interface ToastFn {
  (options?: ToastParams, context?: AppContext | null): ToastHandler
}

// 包含 Toast 信息的实例
export interface ToastInstance {
  id: string
  props: ToastProps
  vm: ComponentInternalInstance
  vnode: VNode
  handler: ToastHandler
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://cn.vuejs.org/api/utility-types.html#extractproptypes&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;ExtractPropTypes&lt;/a&gt; 是为了能够将 props 转为类型，但体验下来还是 sxzz 写的 &lt;a href=&quot;https://github.com/element-plus/element-plus/blob/e69f322b36f85c15698a78e6520f48838031e2b2/packages/utils/vue/props/runtime.ts#L45C24-L45C24&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;buildProp&lt;/a&gt; 好用很多&lt;/p&gt;
&lt;p&gt;于是我们这么定义 toast 函数&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export const toast: ToastFn
  &amp;amp; Partial&amp;lt;ToastFn&amp;gt; &amp;amp; { _context: AppContext | null } = (
    options = {},
    context,
  ) =&amp;gt; {
    const norOptions = normalizeOptions(options) // 解析参数为 option 对象
    const instance = createToast(norOptions, context)

    return instance.handler
  }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;在解析参数中，主要就是覆盖上默认参数了&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;function normalizeOptions(params?: ToastParams): ToastParamsNormalized {
  const options: ToastOptions
    = typeof params === &apos;string&apos; || !params // 如果是纯 string，就套成对象
      ? { message: params }
      : params

  const normalized = {
    ...toastDefault,
    ...options, // 注意顺序，下面的覆盖上面的
  }

  // 默认推到 body 中
  if (!normalized.appendTo) {
    normalized.appendTo = document.body
  }
  // 不然就找选择器，但最后默认还是在 body
  else if (typeof normalized.appendTo === &apos;string&apos;) {
    let appendTo = document.querySelector&amp;lt;HTMLElement&amp;gt;(normalized.appendTo)
    if (!appendTo)
      appendTo = document.body
    normalized.appendTo = appendTo
  }

  return normalized as ToastParamsNormalized
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Migrate to Nuxt3&lt;/h3&gt;
&lt;p&gt;迁移到 Nuxt3 中第一个问题就是 app.use 没了，该怎么转换&lt;/p&gt;
&lt;p&gt;好在这个本质上也是一个插件来的，只要定义到 Nuxt3 的插件上就行了。但由于用到了诸如 document 这样 SSR 没有的方法，最好将它注册为纯客户端插件。同时为了避免与自动导入等冲突了，最好还是将它另起目录，而不是一同在 ~/components 中&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// ~/plugins/installCp.client.ts
import Components from &apos;~/appCP&apos;

export default defineNuxtPlugin((nuxtApp) =&amp;gt; {
  const installer = makeInstaller([...Components])
  nuxtApp.vueApp.use(installer)
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;第二个就是 document not defined 了，这需要特判，&lt;code&gt;export const isClient = process.client&lt;/code&gt; (eslint 或许会提示要用 node:process，但那就更冲突了，client 端是没有 node 的...... disable 就好 &lt;code&gt;/* eslint-disable n/prefer-global/process */&lt;/code&gt;)&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// 在 normalizeOptions 的使用 document 之前加上

if (!isClient) {
  normalized.appendTo = undefined as never
  return normalized as ToastParamsNormalized
}

// 在 props.ts 改一下
export const toastDefault = {
  // ...
  appendTo: isClient ? document.body : (undefined as never),
} as const
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;至此，基本就完成了&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>Chilpost - 又一个仿推应用</title><link>https://chilfish.top/posts/chilpost/</link><guid isPermaLink="true">https://chilfish.top/posts/chilpost/</guid><pubDate>Sun, 06 Aug 2023 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;开始&lt;/h3&gt;
&lt;p&gt;预览：&lt;a href=&quot;https://chilpost.vercel.app&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Chilpost&lt;/a&gt;，&lt;a href=&quot;https://github.com/Chilfish/chilpost&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;GIthub&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;一个月前的 7 月，推的反沉迷和 Thread 预发布，正好看到 @egoist 写了个仿推的 demo &lt;a href=&quot;https://panik.app&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;panik&lt;/a&gt; 来公测。于是月初终于也想着复刻一波了 🤣&lt;/p&gt;
&lt;twitter&gt;
  &lt;blockquote class=&quot;twitter-tweet&quot;&gt;&lt;p lang=&quot;zh&quot; dir=&quot;ltr&quot;&gt;四个小时写了个 &lt;a href=&quot;https://t.co/Rc35oGaKtM&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;https://t.co/Rc35oGaKtM&lt;/a&gt;&lt;/p&gt;— 方向錯亂 (@localhost_4173) &lt;a href=&quot;https://twitter.com/localhost_4173/status/1675230250207420416?ref_src=twsrc%5Etfw&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;July 1, 2023&lt;/a&gt;&lt;/blockquote&gt;
&lt;/twitter&gt;
&lt;p&gt;正好是一号开始写的，写到第六天了但还是不及初版 panik，可能是一开始就没怎么设计好，也没想到要写完它）到现在也还是用 mock 数据来模拟，第五天才加到 api 部分，但还是 Lodis (Local Dictionary Service &lt;a href=&quot;https://www.zhihu.com/question/592335961/answer/2973109071&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;梗&lt;/a&gt;)，纯内存数组&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/dev-log/time.webp&quot; alt=&quot;day 6&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;day 6&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;后续时不时缝缝补补地改，但感觉整体的复杂度什么的都还不怎么样，这方面比较完善的实现还是 Nuxt 社区的 &lt;a href=&quot;https://github.com/elk-zone/elk&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;elk&lt;/a&gt;😹&lt;/p&gt;
&lt;p&gt;之后因为 Web 课程的大作业只能用 Spring Boot 来写，于是就写了份 SB 版本的，顺便当作练习了。具体详见 &lt;a href=&quot;./chilpost-sb/&quot;&gt;chilpost-sb&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;配置&lt;/h3&gt;
&lt;p&gt;一开始想的是顺便也当做复健一下前端了，Vite，Vue，Scss，VueUse，Pinia，最多也就用 &lt;a href=&quot;https://antfu.me/posts/icons-in-pure-css-zh&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;UnoCSS 的图标&lt;/a&gt;，图标包 &lt;a href=&quot;https://icones.js.org/collection/tabler&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;tabler icons&lt;/a&gt; 是真的舒服&lt;/p&gt;
&lt;p&gt;SCSS 格式化用到了 &lt;a href=&quot;https://stylelint.io/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;stylelint&lt;/a&gt;，添加了一下插件分别来排序、vue|Scss 支持：stylelint-config-(recess-order | recommended-vue | standard-scss)，抄了一个 &lt;a href=&quot;https://github.com/Chilfish/chilpost/blob/vue/.stylelintrc.cjs&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;stylelint config&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;DX 上用 &lt;a href=&quot;https://github.com/antfu/unplugin-vue-components&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;unplugin-vue-components&lt;/a&gt; 来自动导入 ~/components 的组件，autoprefixer 来自动添加浏览器 CSS 前缀，@unocss/reset 来清除浏览器默认样式来抹平&lt;/p&gt;
&lt;h3&gt;init&lt;/h3&gt;
&lt;p&gt;动机还是突然想试一下 CSS 的经典顶栏背景高斯模糊，而小红薯网页版动效看着舒服，再就是加上一个夜间模式的切换，到处抄抄就写好了个初版 &lt;a href=&quot;https://learn-rfwzkmb6x-chilfish.vercel.app/post&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;/post&lt;/a&gt;。睡醒第二天想着还是把它抽离出来好了，并加了个底栏，先遵循个 Tailwind 的移动优先 (预览都能在 &lt;a href=&quot;https://github.com/Chilfish/chilpost/deployments&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;deployments&lt;/a&gt; 中倒序找到)&lt;/p&gt;
&lt;p&gt;然后的慢慢添加以前的想法，header 滑动显影 (移动端)、响应式的导航栏 (手机底部，大屏左边)、mock 假数据来测样式、弹窗等&lt;/p&gt;
&lt;h3&gt;mock 的事&lt;/h3&gt;
&lt;p&gt;调样式肯定得有一些假数据来模拟，在手写的之前突然想到了 fake.js，于是造了假数组导出，到这还好。但我按旧习惯要把这个写到文件里，不然每次刷新数据就得重新生成 (其实也不是很麻烦，只是这样路由匹配不到总 404，然后又得重新在首页点进去)。为了方便还是导出到 ts 文件里，以 &lt;code&gt;export const ${mock.name} = ${JSON.stringify(mock.data)};&lt;/code&gt; 的形式，并肯定得加到。gitignore 中，再由 &lt;code&gt;pnpm dev|build&lt;/code&gt; 的时候生成出来，但这时候就遇到了个大问题......&lt;/p&gt;
&lt;p&gt;读写文件得用 &lt;code&gt;node:fs&lt;/code&gt; 模块，但 Vue 是运行在浏览器中，所以我想到让 Vite 来运行。但一开始找不到什么方法来实现，甚至想到了 ts-node，但折腾这边又有些麻烦了。于是就去找了一堆像是 vite-plugin-fs 之类的插件来尝试，但后来才发现这些大多都是用在让浏览器读取 server 的文件，但其实我只需要在运行前读写这个文件就行了&lt;/p&gt;
&lt;p&gt;虽然到后来想到的最佳方案应该是，在 Vite 的生命周期 hooks 类似 ‘build:before’ 中调用这个函数 (也是迁移到 Nuxt 的时候才想到的)。但我碰巧地在摸索的时候发现在 vite.config.ts 中的 console.log 是输出在服务端终端里的，也就是这个配置文件能运行函数并 server only，于是就取巧地这么做了。Vercel Build 也能通过，发现其实他将这些 mock 数据都打包到了 index.js 中了 hh&lt;/p&gt;
&lt;p&gt;其中有个小插曲是，我将生成的 mock data 的命名 &lt;code&gt;export const fakeUsers = []&lt;/code&gt; 和准备用作输出的数组重名了，而且还导出了，导致后来 import 的时候没看清路径，导了动态的。结果就是能出现数据，但浏览器报错找不到 &lt;code&gt;node:fs&lt;/code&gt; hhh，一开始没想到什么问题，但将 fs 相关的与下面这个动态的数据分离后确实没问题了......&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import fs from &apos;node:fs/promises&apos;

// 就是这个，这个是动态生成的，但我不小心引用了它
// 就导致了浏览器之上而下地运行时发现找不到 fs 而报错
export const fakeUsers = [
  ...Array.from({ length: user_num }, () =&amp;gt; genUser()),
  genUser(&apos;Chilfish&apos;),
]
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;样式&lt;/h3&gt;
&lt;p&gt;虽然我的 SCSS 写得还是很糊，感觉就是只是用了嵌套和 &amp;amp; 而已。比较惊艳的还是果然能用 @mixin 写一些很方便的函数，下面这个是对于 &lt;code&gt;button.chat&lt;/code&gt; &lt;code&gt;button.like&lt;/code&gt; 等不同的 class 都有不同的颜色样式，一个个写就麻烦又难维护。问了下 GPT 能不能用类名-颜色这样的映射 map 关系来实现，果然能，并能对其中的颜色再进一步调整。最后生成出来的颜色当然还是固定的，&lt;a href=&quot;https://sass-lang.com/playground/#MTElNDB1c2UlMjAlMjJzYXNzJTNBbWFwJTIyJTNCJTBBJTQwdXNlJTIwJTIyc2FzcyUzQWNvbG9yJTIyJTNCJTBBJTBBJTI0dGhlbWUtY29sb3IlM0ElMjAlMjMxMjM0NTYlM0IlMEElMjRjb2xvci1tYXAlM0ElMjAoJTBBJTIwJTIwJTIyLmNoYXQlMjIlM0ElMjAlMjR0aGVtZS1jb2xvciUyQyUwQSUyMCUyMCUyMi5yZXBvc3QlMjIlM0ElMjAlMjMwMGJhN2MlMkMlMEElMjAlMjAlMjIubGlrZSUyMiUzQSUyMCUyM2Y5MTg4MCUyQyUwQSUyMCUyMCUyMi5zaGFyZSUyMiUzQSUyMCUyNHRoZW1lLWNvbG9yJTJDJTBBJTIwJTIwJTIyLm1lbnUlMjIlM0ElMjAlMjR0aGVtZS1jb2xvciUyQyUwQSUyMCUyMCUyMi5iYWNrJTIyJTNBJTIwJTI0dGhlbWUtY29sb3IlMkMlMEEpJTNCJTBBJTBBJTQwbWl4aW4lMjBhY3Rpb24tYnRuKCklMjAlN0IlMEElMjAlMjAlNDBlYWNoJTIwJTI0a2V5JTJDJTIwJTI0dmFsdWUlMjBpbiUyMCUyNGNvbG9yLW1hcCUyMCU3QiUwQSUyMCUyMCUyMCUyMCUyNGNvbG9yJTNBJTIwbWFwLmdldCglMjRjb2xvci1tYXAlMkMlMjAlMjRrZXkpJTNCJTBBJTBBJTIwJTIwJTIwJTIwYnV0dG9uJTIzJTdCJTI0a2V5JTdEJTIwJTdCJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTI2JTNBaG92ZXIlMjAuYm94JTIwJTdCJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwYmFja2dyb3VuZC1jb2xvciUzQSUyMGNvbG9yLmFkanVzdCglMjRjb2xvciUyQyUyMCUyNGFscGhhJTNBJTIwLTAuOSklM0IlMEElMjAlMjAlMjAlMjAlMjAlMjAlN0QlMEElMEElMjAlMjAlMjAlMjAlMjAlMjAlMjYlM0Fob3ZlciUyMCU3QiUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMGNvbG9yJTNBJTIwJTI0Y29sb3IlM0IlMEElMjAlMjAlMjAlMjAlMjAlMjAlN0QlMEElMjAlMjAlMjAlMjAlN0QlMEElMjAlMjAlN0QlMEElN0QlMEElMEElNDBpbmNsdWRlJTIwYWN0aW9uLWJ0bigpJTNC&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;预览&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-scss&quot;&gt;@use &quot;sass:map&quot;;
@use &quot;sass:color&quot;;

$color-map: (
  &quot;.chat&quot;: $theme-color,
  &quot;.repost&quot;: #00ba7c,
  &quot;.like&quot;: #f91880,
  &quot;.share&quot;: $theme-color,
  &quot;.menu&quot;: $theme-color,
  &quot;.back&quot;: $theme-color,
);

@mixin action-btn() {
  @each $key, $value in $color-map {
    $color: map.get($color-map, $key);

    button#{$key} {
      &amp;amp;:hover .box {
        background-color: color.adjust($color, $alpha: -0.9);
      }

      &amp;amp;:hover {
        color: $color;
      }
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;迁移到 Nuxt 之后，才发现我的样式目录可能放错了，assets 才对，并能够 &lt;code&gt;@use &quot;~/assets/variables&quot; as *;&lt;/code&gt;。并且应该多用 @use：&lt;a href=&quot;https://juejin.cn/post/7117836922176667685&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;SCSS @use vs @import&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;并为了用 UnoCSS 和 Tailwind 的移动端优先，我也这么设置了媒体查询&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-scss&quot;&gt;$sm: 640px;
$lg: 1024px;

#main {
  width: 100%;
  margin-top: $header-height;
  margin-bottom: $nav-footer-height;
}

@media (min-width: $sm) {
  #main {
    width: stretch;
    margin-bottom: 0;
    margin-left: $nav-aside-width;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;获取异步数据&lt;/h3&gt;
&lt;p&gt;推文列表等应该是动态加载出来的，那在 fetch 到之前得有个 isLoading 判断，@vueuse 有两个很好用的方法来处理异步：&lt;a href=&quot;https://vueuse.org/core/computedasync/#computedasync&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;computedAsync&lt;/a&gt;、&lt;a href=&quot;https://vueuse.org/core/useasyncstate/#useasyncstate&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;useAsyncState&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;区别在于正如它们的名字，computedAsync 就是 computed 函数的异步版，每当有变化时就运行，useAsyncState 则是没有响应式的，默认立刻执行，也能手动。第一个常用于路由切换时 fetch 数据，例如从 &lt;code&gt;/u/@chilfish&lt;/code&gt; 切到了 &lt;code&gt;/u/@fish&lt;/code&gt;，路由参数通过 watch 得到了变化，用 computedAsync 就能跟着一起变化&lt;/p&gt;
&lt;p&gt;一开始想着把 useAsyncState 放在 watch 里也能获取，但这样变量作用域又成了一个新的问题。它通常是用来刷新或进入某个路由时获取数据、绑定 button 手动 fetch 等场景&lt;/p&gt;
&lt;p&gt;再要注意的是他们都是返回可 null 的，需要在！isLoading 加个非空判断才能避免 undefined 的可能&lt;/p&gt;
&lt;h3&gt;Api 交互&lt;/h3&gt;
&lt;p&gt;终于是想着要接后端了，一开始想的是后面可以换语言来写后端 (例如下学期要写的 Spring Boot)，于是想到了一直想试试的 Vercel Serverless Functions）其实这些完全不冲突的呀......Nuxt 也能换 baseApiURL&lt;/p&gt;
&lt;p&gt;写得差不多了，也能回数据了，但有很大的问题在于，/api 这部分是属于 Node 规范，而 Vue 是浏览器规范，这就导致 tsconfig 起冲突了。用 ES 模块导入的方式在 Vue 中可行，但每次调用时总会报错：Error：Cannot find module xx&lt;/p&gt;
&lt;p&gt;捣鼓了好久，在 &lt;a href=&quot;https://github.com/orgs/vercel/discussions/1225#discussioncomment-4642381&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Vercel Discussions&lt;/a&gt; 翻到了 &lt;a href=&quot;https://www.typescriptlang.org/docs/handbook/esm-node.html&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;ts esm-node&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;relative import paths need full extensions (e.g we have to write import &quot;./foo.js&quot; instead of import &quot;./foo&quot;)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;也就是即便我在写 ts，要 esm-node 的规范导入模块的话，还是得加。js 后缀 (不是。ts)......对比了好几种配置的方案，用 tsc 看了编译后的结果，还真就只能用这样的方式才能让 Node 正确地识别这些模块&lt;/p&gt;
&lt;p&gt;蒜了......这么写实在是太麻烦了 😅 想着就直接躺床睡了个好几小时的下午觉 (终于睡下了)，醒来第一件事就是立马迁移到 Nuxt&lt;/p&gt;
&lt;h3&gt;Nuxt, yes!&lt;/h3&gt;
&lt;p&gt;过程记在了 PR &lt;a href=&quot;https://github.com/Chilfish/chilpost/pull/5&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Migrate to Nuxt3&lt;/a&gt;，目录结构大迁移，&lt;code&gt;+5,869 −1,672&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;感谢 Nuxt DevTools 的 Hooks 界面，让我找到了比较合适的方法去生成 mock 数据&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export default defineNuxtConfig({
  hooks: {
    &apos;nitro:build:before&apos;: () =&amp;gt; genStaticData(), // generate static data before build
  },
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;遇到比较多的还是 SSR 与数据获取之间的问题了，我在 App.vue 入口这 fetch 当前用户的信息并存到 pinia 中&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;const userStore = useUserStore()
useAsyncState(userStore.fetchCurUser(), null)

// 用户喜好配置 要放入口初始化才能应用到全局（其实就是要启动 pinia 了）
useDarkStore() // init dark mode
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;鉴于 SSR，是没有 Document 之类的变量，定义动态 title 就需要使用 useHead (definePageMeta 是用了宏的形式，其值必须是字面量数据，而不能是动态的变量)，监听页面滚动就用 useWindowScroll&lt;/p&gt;
&lt;p&gt;表单验证使用了 &lt;code&gt;@vueuse/useAsyncValidator&lt;/code&gt;，只要定义规则就能很简单地客户端表单验证&lt;/p&gt;
&lt;p&gt;在 /layout 中定义页面布局，就能很容易地配合媒体查询来布局&lt;/p&gt;
&lt;h3&gt;database/mysql2&lt;/h3&gt;
&lt;p&gt;终于要上数据库了 😹😹 完全是走一步想一步的节奏&lt;/p&gt;
&lt;p&gt;找了很多 mysql 相关的库，看文档感觉用起来都不怎么样，但还是给找着了 &lt;a href=&quot;https://github.com/sidorares/node-mysql2#index&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Node-mysql2&lt;/a&gt;。esm、type、promise、mysql 的具名参数等等都十分的诱人，文档也很全。记录在了 &lt;a href=&quot;https://github.com/Chilfish/chilpost/pull/12&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;chilpost/#12&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;由于它是直接运行 sql 字符串的，为了调试方便，我写了个工具函数来将 sql 查询语句按特定的格式转为 ts 字符串变量，这样就能使用 sql 文件来管理的同时，又能很方便地运行它们。只要将它放在 nitro:init 地 hook 中，就能在运行前转换了&lt;/p&gt;
&lt;p&gt;详见：&lt;a href=&quot;https://github.com/Chilfish/chilpost/blob/35945eea1c0ec3f3c029788848163dc972e3960b/server/utils/sqlToTs.server.ts&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;utils/sqlToTs.ts&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;GoodBye Restful Api&lt;/h3&gt;
&lt;p&gt;看了知乎的那篇讨论，将所有的 server api 返回全换成了 200 的状态码，而具体的业务逻辑错误则是在 data 中返回&lt;/p&gt;
&lt;p&gt;记录在了 &lt;a href=&quot;https://github.com/Chilfish/chilpost/pull/13&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;chilpost/#13&lt;/a&gt;，并专门写了篇博客：&lt;a href=&quot;../return-all-HTTP200-api/&quot;&gt;return_all_HTTP200_api&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;用 todo 来记录进度&lt;/h3&gt;
&lt;p&gt;某天半夜时突然想着要不拿 todo 记录一下要做的事，顺便有个更直观的进度，以及事后感受得到的成就感，再就是为之后能很好地会想起都做了什么，能更好地记录日志什么的。总之就是好处多多，也是属于日志的一种了&lt;/p&gt;
&lt;p&gt;一开始就简单地用小米笔记记一下，它地云同步还算可以，就是功能有些太简陋了，之后就换到了 todoist.com&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/dev-log/chilpost-todo.webp&quot; alt=&quot;来自 todoist.com&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;来自 todoist.com&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h3&gt;前后端分页&lt;/h3&gt;
&lt;p&gt;才想起来要写分页，后端就很简单地写好 pages、size 等参数就好，但在前端我想实现划到底部时自动拼页，麻烦事就来了……&lt;/p&gt;
&lt;p&gt;因为这是要复用的地方，在 &lt;code&gt;/explore&lt;/code&gt; &lt;code&gt;/home&lt;/code&gt; &lt;code&gt;/search&lt;/code&gt; &lt;code&gt;/@user&lt;/code&gt; 这些地方都可以用得到，于是就要单独为它们管理状态，它们的接口也都不一样。为了切换路由后不重复请求，还得都存到 pinia 里管理 😫&lt;/p&gt;
&lt;p&gt;详见：&lt;a href=&quot;https://github.com/Chilfish/chilpost/blob/cd9701b2810defff2075b3e4c8e9aadf18f7de25/src/composables/loadPosts.ts&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;loadPosts.ts&lt;/a&gt; 和 &lt;a href=&quot;https://github.com/Chilfish/chilpost/blob/cd9701b2810defff2075b3e4c8e9aadf18f7de25/src/components/Post/Infinite.vue&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;PostInfinite.vue&lt;/a&gt;，虽然感觉写得很怪很不对，但还是跑起来了 hhh&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>Taro + Vant-WeApp + Vue</title><link>https://chilfish.top/posts/taro-vant-weapp/</link><guid isPermaLink="true">https://chilfish.top/posts/taro-vant-weapp/</guid><pubDate>Tue, 18 Jul 2023 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;开始&lt;/h3&gt;
&lt;p&gt;小程序跨端除了只适用 Vue 的 Uniapp 外，还有京东的 &lt;a href=&quot;https://docs.taro.zone/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Taro&lt;/a&gt;，支持 Vue/React，目前使用 WebPack 5 进行编译，后续会使用 Vite。&lt;a href=&quot;https://vant-contrib.gitee.io/vant/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Vant&lt;/a&gt; 是有赞的移动端为主的组件库，&lt;a href=&quot;https://vant-contrib.gitee.io/vant-weapp/#/home&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Vant-WeApp&lt;/a&gt; 是其中的微信小程序版 (也就是这个只能用在微信小程序中，h5 都不能)&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/Chilfish/taro-learn/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;仓库地址&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;初始化&lt;/h3&gt;
&lt;p&gt;需要先安装 Taro 的脚手架，然后创建模板。或是我摸出来的 &lt;a href=&quot;https://github.com/Chilfish/taro-learn/tree/start&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Start&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm add -g @tarojs/cli

taro init
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;其中选择默认模板即可，同时由于模板的依赖有许多都过时了而导致编译失败，需要先升级 &lt;code&gt;pnpm up --latest&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://vant-contrib.gitee.io/vant-weapp/#/home&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Taro 的项目结构&lt;/a&gt;和内部 Vue 的写法主要是以小程序 &lt;code&gt;&amp;lt;View/&amp;gt;&lt;/code&gt; 的为主，当然也可以设置成 HTML 的标签&lt;/p&gt;
&lt;h3&gt;配置&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;app.config.ts&lt;/code&gt; 是小程序的全局配置，&lt;code&gt;/pages&lt;/code&gt; 下是页面路由，每个页面的 &lt;code&gt;*.config.ts&lt;/code&gt; 是该页面的小程序配置。这些皮脂定义了路由页面 (全局)、窗口状态和样式等。可见文档：&lt;a href=&quot;https://docs.taro.zone/docs/app-config&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;全局配置&lt;/a&gt;和&lt;a href=&quot;https://docs.taro.zone/docs/page-config&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;页面配置&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;eslint&lt;/h4&gt;
&lt;p&gt;新建 Vue 项目当然得 extend @antfu 的配置）&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm add -D @antfu/eslint-config
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后在 &lt;code&gt;.eslintrc&lt;/code&gt; 的 extends 添加 &lt;code&gt;@antfu&lt;/code&gt; 就好了，&lt;code&gt;pnpm eslint . --fix&lt;/code&gt;&lt;/p&gt;
&lt;h4&gt;tsconfig&lt;/h4&gt;
&lt;p&gt;基本没差什么，添加别名和导入 @vant 就需要添加：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;compilerOptions&quot;: {
    &quot;typeRoots&quot;: [&quot;node_modules/@types&quot;, &quot;miniprogram-api-typings&quot;],
    &quot;paths&quot;: {
      &quot;@/*&quot;: [&quot;src/*&quot;]
    }
  },
  &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;dist&quot;]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;使用 HTML 标签&lt;/h4&gt;
&lt;p&gt;其实实际上是可以使用 HTML 标签的，装个插件就行，它会将这些标签转译为小程序的标签&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm add -D @tarojs/plugin-html
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-js&quot;&gt;import ComponentsPlugin from &apos;unplugin-vue-components/webpack&apos;

const config = {
  // ...
  plugins: [&apos;@tarojs/plugin-html&apos;],
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;使用 &lt;code&gt;unplugin-vue-components&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;还是来自 @antfu，有了这个就不用在导入自定义组件的时候都得手动 import 了&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm add -D unplugin-vue-components
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;同时需要设置到 webpack 编译中：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-js&quot;&gt;import ComponentsPlugin from &apos;unplugin-vue-components/webpack&apos;

const config = {
  // ...
  mini: {
    // ...
    // 合并webpack配置
    webpackChain(chain) {
      chain.plugin(&apos;unplugin-vue-components&apos;).use(
        ComponentsPlugin({
          dts: &apos;src/types/components.d.ts&apos;,
        }),
      )
    },
  },
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;记得将导出的类型文件加到 ignore 里：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;src/types/components.d.ts
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;路由&lt;/h3&gt;
&lt;p&gt;页面路由的写法虽然很奇怪，但小程序是这样的。第一个是文件夹名，第二个是 Vue 文件名，它似乎不能自动检测类似 index 这样的特殊命名。而且到编译后的开发者工具或是 h5 的 URL 也是这样的形式&lt;/p&gt;
&lt;p&gt;约定来说，它主要是以文件夹作为页面路由的划分，每个页面下会有一个 &lt;code&gt;*.config.ts&lt;/code&gt; 的页面配置文件&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;pages: [&apos;pages/index/index&apos;, &apos;pages/profile/profile&apos;]
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;子路由和跳转&lt;/h4&gt;
&lt;p&gt;由于小程序是一个 SPA 应用，基本就只能在当前页切换。因此 pages 更像是对应的是主页的 tab page，而 subPages 是要跳转的路由页面，他们通常会放在 packages 文件夹下&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export default defineAppConfig({
  pages: [&apos;pages/index/index&apos;, &apos;pages/profile/profile&apos;],

  subPackages: [
    {
      root: &apos;packages&apos;,
      pages: [&apos;todo/todo&apos;],
    },
  ],
})
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;编译配置&lt;/h3&gt;
&lt;p&gt;根目录下的 &lt;code&gt;/config&lt;/code&gt; 文件夹是 Taro 的编译配置，文档可见：&lt;a href=&quot;https://docs.taro.zone/docs/config&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;编译配置&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;基本不变就行了，只不过 eslint 可能会报错 &lt;code&gt;process&lt;/code&gt; 的问题，就需要手动导入 &lt;code&gt;const process = require(&apos;node:process&apos;)&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;添加路径别名和导入 @Vant：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-js&quot;&gt;const path = require(&apos;node:path&apos;)

const root = path.resolve(__dirname, &apos;..&apos;)
const vantDist = path.resolve(root, &apos;node_modules/@vant/weapp/dist&apos;)

const config = {
  // ...
  alias: {
    &apos;@&apos;: path.resolve(root, &apos;src&apos;),
  },
  copy: {
    patterns: [
      {
        from: vantDist,
        to: &apos;dist/vant/&apos;,
      },
    ],
    options: {},
  },
  mini: {
    hot: true,
    postcss: {
      pxtransform: {
        enable: true,
        config: {
          selectorBlackList: [/van-/],
        },
      },
      // ...
    },
  },
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;其中，&lt;code&gt;copy.patterns&lt;/code&gt; 是指将 node_modules 里 @vant 的组件 dist 目录复制到编译文件夹中，这是因为&lt;a href=&quot;https://docs.taro.zone/docs/vant&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;文档&lt;/a&gt;：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;vant 组件中包含一些小程序原生文件的依赖，目前 Taro 没有对这些依赖进行分析&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;引用 Vant 组件&lt;/h3&gt;
&lt;p&gt;这需要手动在配置文件中导入具名组件 (像是 &lt;code&gt;&amp;lt;van-button/&amp;gt;&lt;/code&gt;)，可以在全局导入，但有时候会引用冲突 (？) 导致有些组件不能在全局导入的时候共存，就需要在各自的 page 下 using 了&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// app.config.ts
export default defineAppConfig({
  usingComponents: {
    &apos;van-button&apos;: &apos;@vant/weapp/button/index&apos;,
  }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这里的地址取决于在编译配置中将组件复制的地址 (相对于编译后的 &lt;code&gt;/dist/app.json&lt;/code&gt;) 来说，当然可以写一个函数来简化：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// vant.ts
/**
 * vant weapp component path
 * @param name component name(s)
 * @returns `{ van-name: @vant/weapp/name/index }`
 */
export function useVant(...name: vantComponentsName[]) {
  const obj: Record&amp;lt;string, string&amp;gt; = {}
  name.forEach((item) =&amp;gt; {
    obj[`van-${item}`] = `@vant/weapp/${item}/index`
  })
  return obj
}

// app.config.ts
export default defineAppConfig({
  usingComponents: {
    ...useVant(&apos;button&apos;),
  },
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这样子在 Vue 中就能直接使用组件，不用手动 import&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-vue&quot;&gt;&amp;lt;script setup lang=&quot;ts&quot;&amp;gt;
import { ref } from &apos;vue&apos;

const msg = ref(&apos;Hello world&apos;)
&amp;lt;/script&amp;gt;

&amp;lt;template&amp;gt;
  &amp;lt;view class=&quot;index&quot;&amp;gt;
    &amp;lt;van-button type=&quot;primary&quot;&amp;gt;
      {{ msg }}
    &amp;lt;/van-button&amp;gt;
  &amp;lt;/view&amp;gt;
&amp;lt;/template&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;只不过这种是属于使用 npm 包的方式，它需要在 &lt;code&gt;/dist&lt;/code&gt; 下有 node_modules 和 packages.json，并在编译前在开发者工具中点构建 npm 才能使用&lt;/p&gt;
&lt;p&gt;所以就多了一步 copy：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-js&quot;&gt;const config = {
  copy: {
    patterns: [
      {
        from: path.resolve(root, &apos;dist.package.json&apos;),
        to: &apos;dist/package.json&apos;,
      },
    ],
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;// dist.package.json
{
  &quot;name&quot;: &quot;dist&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;description&quot;: &quot;&quot;,
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;keywords&quot;: [],
  &quot;author&quot;: &quot;&quot;,
  &quot;license&quot;: &quot;ISC&quot;,
  &quot;dependencies&quot;: {
    &quot;@vant/weapp&quot;: &quot;^1.10.22&quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;运行&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;pnpm dev&lt;/code&gt; 后，就能在微信开发者工具中导入 dist 目录来预览了&lt;/p&gt;
&lt;h3&gt;一定要禁用缓存 &amp;amp; 热重载不了&lt;/h3&gt;
&lt;p&gt;虽然 cli 会提示强烈建议开启缓存，但实测发现它会导致很多配置方面的问题&lt;/p&gt;
&lt;p&gt;首先每次编译的时候，它默认都会将 &lt;code&gt;/dist&lt;/code&gt; 删除，然后将存在某个地方的缓存与当前编译结果 diff (也许) 后复制过来。但对于微信开发者工具来说，由于项目根目录被清空了，它会直接报错：找不到 app.json 之类的，这时候就要让开发者工具重新编译......(它本来是可以热重载差异化编译的)&lt;/p&gt;
&lt;p&gt;回到缓存问题，我发现实际上开了缓存后，修改 app.config.ts 之类的配置文件后，再次 pnpm 编译，&lt;code&gt;dist/app.*&lt;/code&gt; 的内容实际上还是很早之前的，这时候例如添加页面、组件都并没有应用上，小程序那边就会报错：xx not found 之类问题......&lt;/p&gt;
&lt;h3&gt;使用 &lt;code&gt;@ngify/http&lt;/code&gt; 请求库&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/ngify/ngify/tree/main/packages/http#replace-http-backend-class&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;@ngify/http&lt;/a&gt; 适配了微信小程序特殊的 &lt;code&gt;wx.request&lt;/code&gt; (也就是在小程序里是没有 XMLRequest 或是 fetch 的，得用它自己的请求库)，并配合 &lt;a href=&quot;RxJs-ngify-http/&quot;&gt;RxJs&lt;/a&gt; 风格的处理&lt;/p&gt;
&lt;p&gt;首先新建一个 &lt;code&gt;src/service&lt;/code&gt; 文件夹专门用来处理请求，在 index.ts 中初始化设置为 wx 请求库：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import { setupConfig } from &apos;@ngify/http&apos;
import { HttpWxBackend } from &apos;@ngify/http/wx&apos;

/**
 * 使用微信小程序的 wx.request 作为请求后端
 */
export function setupServices() {
  setupConfig({
    backend: new HttpWxBackend(),
  })
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;然后在 app.ts 导入初始化&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import { setupServices } from &apos;./services&apos;

setupServices()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这样就可以新建一个请求类了：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import type { GithubRepo } from &apos;@/types&apos;
import { HttpClient } from &apos;@ngify/http&apos;
import { map } from &apos;rxjs/operators&apos;

// Github API，仅用于示例，需要在微信开发者工具中，在详情-&amp;gt;本地设置中
// 开启 `开发环境不校验请求域名、TLS版本及HTTPS证书` 选项，来跳过对服务器域名的校验
// 否则，需要使用已备案的域名来反代 Github API
const api = &apos;https://api.github.com&apos;

export class GithubService {
  private http: HttpClient

  constructor() {
    this.http = new HttpClient()
  }

  getRepos(input: string) {
    return this.http
      .get&amp;lt;{ items: GithubRepo[] }&amp;gt;(`${api}/search/repositories?q=${input}`)
      .pipe(map(res =&amp;gt; res.items))
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;函数将返回 &lt;code&gt;Observable&amp;lt;T&amp;gt;&lt;/code&gt; 供以后续使用 RxJs 处理&lt;/p&gt;
&lt;p&gt;其中要注意的是，由于微信小程序的限制，请求的只能是备案过的域名......&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>RxJs &amp; @ngify/http</title><link>https://chilfish.top/posts/rxjs-ngify-http/</link><guid isPermaLink="true">https://chilfish.top/posts/rxjs-ngify-http/</guid><pubDate>Mon, 17 Jul 2023 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;RxJs&lt;/h2&gt;
&lt;p&gt;“响应式编程” 最先想到的是 Vue 的 ref 了，用观察者模式监听数据的变化以做出对应的动作；“声明式 (函数式) 编程” 即为像 Lodash 或 ES6 的 Array 方法一样，使用一系列的 lambda 函数将要达成的目的组合起来，而不用手动地一个个实现内部细节&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;RxJs 就是在&lt;strong&gt;时间维度&lt;/strong&gt;上以&lt;strong&gt;流&lt;/strong&gt;的方式处理事件的类 Lodash 库&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;RxJs 对常用的事件请求都做了相当多的封装，节流防抖、过滤、转换、缓存等&lt;/p&gt;
&lt;p&gt;Rx 系列中还有一个是 RxJava，它将被 Kotlin 的 Flow 所代替，这在之前写的 Android Jetpack Compose 中一直有使用着，所以换到 js 中就迁移一下 api 语法就行了&lt;/p&gt;
&lt;p&gt;：&lt;a href=&quot;https://juejin.cn/post/7090422222195523621&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;从业务视角来聊一聊为什么我们需要 RxJS？&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;概念及应用&lt;/h3&gt;
&lt;p&gt;RxJs 基本由以下概念组成：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Observable&lt;/strong&gt;：表示一个可观察的数据流，可以被订阅&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Observer&lt;/strong&gt;：观察者，用来接收 Observable 发出的数据&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Subscription&lt;/strong&gt;：订阅，表示 Observable 和 Observer 之间的连接&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Subject&lt;/strong&gt;：既是 Observable 又是 Observer，可以用来多播数据流&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scheduler&lt;/strong&gt;：调度器，用来控制数据流的执行时机&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Operator&lt;/strong&gt;：操作符，用于对处理数据流操作&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;它有以下的应用场景&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;表单验证&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;在表单验证中，我们经常需要在用户输入时实时验证输入内容的有效性。但是，如果每次输入都触发验证，会造成性能浪费。这时，我们可以使用 RxJs 的 debounceTime 操作符来实现防抖功能，只有在用户停止输入一段时间后才触发验证&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-js&quot;&gt;const input = document.querySelector(&apos;input&apos;)
const inputStream = fromEvent(input, &apos;input&apos;)

inputStream
  .pipe(
    map(event =&amp;gt; event.target.value),
    debounceTime(500),
  )
  .subscribe((value) =&amp;gt; {
    // 验证输入内容
  })
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;搜索建议&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;在搜索框中，我们经常需要根据用户输入的关键词来提供搜索建议。但是，如果每次输入都触发搜索建议请求，会造成大量无用请求。这时，我们可以使用 RxJs 的 switchMap 操作符来实现搜索建议功能，只有在用户停止输入一段时间后才触发搜索建议请求，并且只保留最新的请求结果&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-js&quot;&gt;const input = document.querySelector(&apos;input&apos;)
const inputStream = fromEvent(input, &apos;input&apos;)

inputStream
  .pipe(
    map(event =&amp;gt; event.target.value),
    debounceTime(500),
    switchMap(keyword =&amp;gt; getSearchSuggestions(keyword)),
  )
  .subscribe((suggestions) =&amp;gt; {
    // 显示搜索建议
  })

function getSearchSuggestions(keyword) {
  // 发起搜索建议请求
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;分页加载&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;在分页加载中，我们经常需要在用户滚动到页面底部时自动加载下一页内容。这时，我们可以使用 RxJs 的 concatAll 操作符来实现无限滚动功能，将每次加载的数据流连接在一起，形成一个无限数据流&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-js&quot;&gt;const scrollStream = fromEvent(document, &apos;scroll&apos;)

scrollStream
  .pipe(
    map(() =&amp;gt; isScrollToBottom()),
    filter(isBottom =&amp;gt; isBottom),
    map(() =&amp;gt; getNextPageData()),
    concatAll(),
  )
  .subscribe((data) =&amp;gt; {
    // 显示下一页内容
  })
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;可以看到它很多的方法和 Lodash 十分甚至九分的相像，不同在于 RxJs 将数据或事件转成流的形式 (fromEvent)，通过管道符 pipe 内的一系列的操作符将流进行处理，并传递给下一个操作符处理，最后将返回的数据 (map 或 filter 等处理数据的) 传给订阅者收集&lt;/p&gt;
&lt;h2&gt;@ngify/http&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;@ngify/http&lt;/code&gt; 是一个基于 RxJS 的请求库，提供了一种简洁、灵活和响应式的方式来处理异步数据流&lt;/p&gt;
&lt;p&gt;与 fetch 和 axios 相比，&lt;code&gt;@ngify/http&lt;/code&gt; 有以下几个不同之处：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;基于 RxJS：使用了 RxJS 的 Observable 和操作符来处理异步数据流，也就是它的请求默认返回的都是 &lt;code&gt;Observable&amp;lt;T&amp;gt;&lt;/code&gt;。这使得它具有更强大的功能，比如可以方便地进行数据转换、错误处理和取消请求等&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;简洁的 API：@ngify/http 提供了一种简洁的 API，使得发送 HTTP 请求变得更加直观和易于使用。它使用了类似于 Angular 的 HttpClient 的语法，可以方便地设置请求头、查询参数和请求体等&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;下面是一个使用 @ngify/http 发送 GET 请求的示例：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import { http } from &apos;@ngify/http&apos;

http.get(&apos;https://api.example.com/users&apos;).subscribe(
  (response) =&amp;gt; {
    console.log(response.data)
  },
  (error) =&amp;gt; {
    console.error(error)
  },
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;在使用了 RxJS 的项目中，为什么要使用 @ngify/http 呢？因为 @ngify/http 提供了一种基于响应式编程的方式来处理异步数据流，这与 RxJS 的理念非常契合。它可以方便地与其他 RxJS 操作符和 Observable 进行组合，实现更复杂的数据处理逻辑&lt;/p&gt;
&lt;p&gt;例如，我们可以使用 @ngify/http 和 RxJS 的操作符来实现自动重试、轮询和数据转换等功能。这使得我们可以更好地管理和处理异步数据流，提高代码的可读性和维护性&lt;/p&gt;
&lt;h2&gt;以搜索为例&lt;/h2&gt;
&lt;p&gt;-&amp;gt; &lt;a href=&quot;https://vue.chilfish.top/github&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;预览&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;要实现的功能是经典的搜索请求，当搜索框有变化时发起请求，渲染结果。同时应该也要有过滤空、重复请求，也要有防抖，竟态的先后请求问题等&lt;/p&gt;
&lt;p&gt;同时，我们将请求的部分放到专门的 Services 层来维护，Vue 部分就只有逻辑和 UI&lt;/p&gt;
&lt;p&gt;先放 code：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;const githubService = new GithubService()

fromEvent(searchInput.value!, &apos;input&apos;)
  .pipe(
    map(e =&amp;gt; (e.target as HTMLInputElement).value.trim()),
    tap((val) =&amp;gt; {
      if (val.length === 0)
        repoStatus.value = &apos;idle&apos;
    }),
    filter(val =&amp;gt; val.length !== 0),
    debounceTime(500),
    distinctUntilChanged(),
    switchMap((val: string) =&amp;gt; {
      repoStatus.value = &apos;loading&apos;
      return githubService.getRepos(val)
    }),
  )
  .subscribe({
    next: (data) =&amp;gt; {
      repoStatus.value = data.length === 0 ? &apos;notFound&apos; : &apos;success&apos;
      repos.value = data
    },
    error: (error) =&amp;gt; {
      console.error(error.message)
      repoStatus.value = &apos;error&apos;
    },
  })
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;首先将输入框的 input 事件转为流，这里的 searchInput 是一个 &lt;code&gt;ref&amp;lt;HTMLInputElement | null&amp;gt;&lt;/code&gt;，所以需要将这一段放到 &lt;code&gt;onMounted&lt;/code&gt; 中，等 Dom 渲染完成得到 input 框才到下一步&lt;/p&gt;
&lt;p&gt;在管道中，使用 map 操作符将事件对象转换为输入框的值，并使用 trim 方法去除首尾空格。这样可以确保输入的值是干净的。使用 filter 操作符过滤掉空输入，即长度为 0 的值。这样可以避免发送不必要的请求&lt;/p&gt;
&lt;p&gt;使用 &lt;code&gt;debounceTime&lt;/code&gt; 操作符设置防抖时间为 500 毫秒。这意味着只有在用户停止输入 500 毫秒后才会发起请求。这样可以避免频繁的请求，减轻服务器的负担&lt;/p&gt;
&lt;p&gt;使用 &lt;code&gt;distinctUntilChanged&lt;/code&gt; 操作符确保只有在输入值发生变化时才会发起请求。这样可以避免发送重复的请求，提高性能&lt;/p&gt;
&lt;p&gt;使用 switchMap 将最终的 query 值交由 service 请求。switchMap 的特点是只保留最新的内部 &lt;code&gt;Observable&lt;/code&gt; 流，当新的请求到来时，会取消之前的请求。这样可以解决竟态问题，确保只有最新的请求结果被处理&lt;/p&gt;
&lt;p&gt;最后，订阅这个 service 的结果，返回给 Vue 的数据层&lt;/p&gt;
&lt;p&gt;其中 service 这么写&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;export class GithubService {
  private http: HttpClient

  constructor() {
    this.http = new HttpClient()
  }

  getRepos(input: string) {
    return this.http
      .get&amp;lt;{ items: GithubRepo[] }&amp;gt;(`${api}/search/repositories?q=${input}`)
      .pipe(map(res =&amp;gt; res.items))
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;直接返回 &lt;code&gt;http.get&lt;/code&gt; 这一个 &lt;code&gt;Observable&lt;/code&gt;&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>Chill Chat app Server</title><link>https://chilfish.top/posts/chillchat-server/</link><guid isPermaLink="true">https://chilfish.top/posts/chillchat-server/</guid><pubDate>Mon, 29 May 2023 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;再次的全包&lt;/h3&gt;
&lt;p&gt;原以为我就写安卓端就好了，后来讨论过后，依旧还是我又来负责后端了......&lt;/p&gt;
&lt;p&gt;但这样也好在选择更加自由了，以及后面来看确实有些正确的，主要原因还是一开始就没设计好像是架构、数据库字段之类的。在开发后端的过程中就是在不断地重构推翻自己，但也好在只用和自己争论 hhh&lt;/p&gt;
&lt;p&gt;选择上，原本打算接手寒假时写的 &lt;a href=&quot;./ChillChat-Android/&quot;&gt;Chat 前后端&lt;/a&gt;，那也是用了 express 和 SocketIO + MongoDB。但发现写得实在是太鞑便了，不仅除了登录外的所有的请求都由 SocketIO 接手，js 项目写的也是一坨&lt;/p&gt;
&lt;p&gt;后来才算是知道，严格来说 Express.js 并不算是一个框架，它并没有要求开发者以什么的结构去写，就以至于我写得毫无架构可言。看了一圈，还是用上了 &lt;a href=&quot;https://nestjs.com&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Nest.js&lt;/a&gt;。它可以理解为是 Express 的再封装，不过它完全是一个框架来的，而且完全支持 TypeScript&lt;/p&gt;
&lt;p&gt;数据库上从 mongoose 换到了 TypeScript 环境下的 &lt;a href=&quot;https://typegoose.github.io/&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;Typegoose&lt;/a&gt;，并且为了适配 Nest.js，还得装个封装好的 &lt;a href=&quot;https://github.com/GrapeoffJS/kindagoose&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;kindagoose&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;时间：&lt;img src=&quot;https://wakatime.com/badge/user/0842a71f-c026-4b09-8aa0-f8398b4c3423/project/bf267b0a-5fdb-406b-889d-bbd1ccb800d5.svg&quot; alt=&quot;wakatime&quot;&gt;&lt;/p&gt;
&lt;p&gt;最后是一星期从上手到基本完成基本要求，虽然从架构上来说还差了挺多的，虽然感觉应该够应付了&lt;/p&gt;
</content:encoded><author>Chilfish</author></item><item><title>Jetpack Compose Chat app</title><link>https://chilfish.top/posts/chillchat-android/</link><guid isPermaLink="true">https://chilfish.top/posts/chillchat-android/</guid><pubDate>Thu, 11 May 2023 00:00:00 GMT</pubDate><content:encoded>&lt;h3&gt;开始&lt;/h3&gt;
&lt;p&gt;总算是大致地学好了 Compose，现在终于新建文件夹了...... 这其实是安卓期末课设来着的，但队友不学安卓，他们整后端去了，那我就可以自由开发了 hhh&lt;/p&gt;
&lt;p&gt;先大概地过了 XML 部分，RecycleView、Fragment 什么的一通嗦了，然后新建项目的时候被 AS 用 [DataBinding][DataBinding] 给吸引过去了。了解到是属于 &lt;a href=&quot;../../note/android/Jetpack/index/&quot;&gt;Jetpack&lt;/a&gt; 的一部分后，以及顺便用 AS 迁移到了 Kotlin，补了点语法 (一堆 api 和用法真完全是为了实用而开发的了)，然后就正式地换用 Compose 来写了&lt;/p&gt;
&lt;p&gt;当然，后来也是有用 Jetpack 组件 + XML 的方式来重构或练习了，但对比下来，还是 Compose 舒服多了&lt;/p&gt;
&lt;h3&gt;Compose，Yes！&lt;/h3&gt;
&lt;p&gt;写了一整子的 demo，发现这太 React/Vue 的感觉了 hhh，特别像是组件以及它们的 [状态][Compose_State] 什么的。而且它也能写路由来跳转控制，不禁地想起了这不可以整 SPA 那样的单 Activity，其他的就用路由来导航了，进而地就是它的 [架构设计][Compose_Structure] 了&lt;/p&gt;
&lt;p&gt;它会设计成 UI 与逻辑、数据分离的架构，Composable 函数就只负责绘制 UI；ViewModel 来存放页面的状态和数据，以及它们的事件；数据层方面，会用 Jetpack Room 来代替原生 SQLite，用 repository 来当做数据与 UI 的桥梁，像是从本地还是 api 获取数据什么的都由它来完成，再 export 出方法给 ViewModel 调用&lt;/p&gt;
&lt;p&gt;而 Compose 推崇的是单向数据流，所有的对象基本只会实例化一次，然后通过像是函数参数那样向下传递，通过函数式编程的将函数当参数来向上传递事件来更改。同时地，它通常还会将可变变量设为 private，是能在类内修改，然后暴露不可变的值，外部只能通过调用成员函数来修改&lt;/p&gt;
&lt;br&gt;
&lt;p&gt;开发时长：&lt;img src=&quot;https://wakatime.com/badge/user/0842a71f-c026-4b09-8aa0-f8398b4c3423/project/eba71aa8-b520-4043-a683-355b918aa75c.svg&quot; alt=&quot;wakatime&quot;&gt;&lt;/p&gt;
&lt;h3&gt;复制照搬！&lt;/h3&gt;
&lt;p&gt;hh 其实在一开始写 XML 的时候就想好了期末选题，所以一直以来都在写 Chat 的界面，到 Composable 也是。所以只要复制过来再改改就好了，但为了舒服的 commits，还是按功能来拆分 commit 了）还好没全复制过来，因为后来新学好了 MVI 的架构，对于史来说的旧项目，还是得重构蛮久的&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/dev-log/commits.webp&quot; alt=&quot;得亏有写过，直接搬组件过来就好）&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;得亏有写过，直接搬组件过来就好）&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;然后是截至 5 月 11 号的 UI，但其实 UI 没写多少 (都在之前学的时候写好了)，主要是 Room 数据库和 ViewModel 这些的设计了&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/dev-log/screenshot_0511.webp&quot; alt=&quot;Material 3，Yes！&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;Material 3，Yes！&lt;/figcaption&gt;&lt;/figure&gt;
&lt;blockquote&gt;
&lt;p&gt;先睡再说了）&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;05-12 -&amp;gt; 13&lt;/h3&gt;
&lt;p&gt;此时的 UI：&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/dev-log/message.webp&quot; alt=&quot;大概的样子）仿了&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;大概的样子）仿了&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;差不多就差插到 Room 里了，其他就先完成本地修改的吧，然后再处理 server 端&lt;/p&gt;
&lt;h4&gt;Room&lt;/h4&gt;
&lt;p&gt;一开始很蠢地为每个 Entity 都按流程地创 Dao、Repository 和 Database 实例，直到要 join 查表的时候才意识到应该是同一个 db 然后多个表才对 (其实也是到实例化他们的时候觉得太怪了)&lt;/p&gt;
&lt;p&gt;再就是明明已经 insert 进了 fake Data，但还是没创 db 一样，只有退出重进之后才会创文件，只好预先地在 init 中先 query 一遍&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/dev-log/repoProvider.webp&quot; alt=&quot;还整了一个暴露出来的单例&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;还整了一个暴露出来的单例&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;再就是写着写着忘记应该异步来写了 (虽然这协程就是为了异步)&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://p.chilfish.top/blog/dev-log/async.webp&quot; alt=&quot;JS to Kotlin）&quot; decoding=&quot;async&quot; loading=&quot;lazy&quot; referrerpolicy=&quot;same-origin&quot;&gt;&lt;figcaption&gt;JS to Kotlin）&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h4&gt;路由......&lt;/h4&gt;
&lt;p&gt;比较难搞的点还是路由跳转的传参了......一开始想的就只是传 uid 然后在 ViewModel 再查 room，但想想这也太蠢了。但是翻了一遍虽然是可以传 Bundle 或 Parcelable 对象，但要么获取方法被弃用了，又或者必须安卓 13......而且可 null 的 argument Log 出来的一直都是 null 了&lt;/p&gt;
&lt;p&gt;于是还是老实地换回了传 json 过去。但一大坑点就是如果数据包含 URL，而路由的格式就是以 URL 的 &lt;code&gt;/&lt;/code&gt; 作为分隔的，就被认为了深层路由...... 所以再转 json 的时候需要先将 &lt;code&gt;/&lt;/code&gt; 转为 &lt;code&gt;%2F&lt;/code&gt; 这样的 URLEncode，然后再解码&lt;/p&gt;
&lt;h4&gt;键盘又挡住了 input&lt;/h4&gt;
&lt;p&gt;不是说在 Manifest 中写好 &lt;code&gt;android:windowSoftInputMode=&quot;adjustResize&quot;&lt;/code&gt; 就能自动调整了嘛......哦我用 Scaffold 来布局啊，那还得再多写点&lt;/p&gt;
&lt;p&gt;得手动为 input 的部分加 imePadding&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-kotlin&quot;&gt;val topBarState = rememberTopAppBarState()
Scaffold(
    contentWindowInsets = ScaffoldDefaults
        .contentWindowInsets
        .exclude(WindowInsets.ime)
) { padding -&amp;gt;
    Column(Modifier.fillMaxSize().padding(padding)) {
        UserInput(
            modifier = Modifier
                .navigationBarsPadding()
                .imePadding(),
        )
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;这还是在 Compose 的 example —— &lt;a href=&quot;https://github.com/android/compose-samples/blob/main/Jetchat/app/src/main/java/com/example/compose/jetchat/conversation/Conversation.kt#L148-L150&quot; target=&quot;_blank&quot; rel=&quot;noopener nofollow&quot;&gt;JetChat&lt;/a&gt; 中看到的，先放一个 yes！在这里&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&amp;gt; _ &amp;lt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;其实还是因为两星期没写了......&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;MVI 架构&lt;/h3&gt;
&lt;h3&gt;依赖注入！&lt;/h3&gt;
&lt;p&gt;依赖注入的主要目的是将对象的创建和配置与它们的使用分离开来，从而使代码更加灵活和可扩展。通过使用依赖注入，我们可以将对象的创建和配置委托给容器，容器负责管理对象的生命周期和依赖关系，而不是由对象自己来管理&lt;/p&gt;
&lt;p&gt;在依赖注入中，我们可以使用不同的作用域来控制对象的生命周期。例如，&lt;code&gt;@Singleton&lt;/code&gt; 注释可以将对象的生命周期限定为应用程序的整个生命周期，而 &lt;code&gt;@ActivityScoped&lt;/code&gt; 注释可以将对象的生命周期限定为 Activity 的生命周期。在这种情况下，对象只会被实例化一次，并且在需要时自动引用这个实例&lt;/p&gt;
&lt;h3&gt;编辑信息&lt;/h3&gt;
&lt;h3&gt;Debug Page&lt;/h3&gt;
&lt;h3&gt;比 Retrofit2 更好的网络请求 —— com.drake.net&lt;/h3&gt;
&lt;h3&gt;连接 SocketIO&lt;/h3&gt;
</content:encoded><author>Chilfish</author></item></channel></rss>