简介
Notabase 仍然处于开发中,API 会经常改动,不适合在生产环境中使用。如果你对此感兴趣,可以关注 github 仓库以获取最新的消息。对此项目有什么疑问或者建议,可以在本文评论或者在 github 中提 issue
https://github.com/mayneyao/Notabase
Notabase 是专门针对 Notion database 的 API 封装。你可以以操作 JS 对象的形式,访问和管理 notion 中的表格数据。
Notabase 在浏览器 /浏览器扩展/node环境中均可运行,通过 Notabase 你可以把 Notion database 变成一个 API 友好的数据库。
快速体验
安装 NotionPlus 可以在浏览器控制台中使用 Notabase。
载入 notion 页面后,浏览器控制台中会弹出一个 Notabase 的实例对象。在 NotionPlus 下 copy 此对象,即可在控制台中调用。
https://chrome.google.com/webstore/detail/notionplus/mlmicgheiiebfodpmpgcekbhkeipeald
安装
yarn add notabase
使用
访问基础数据
下面的链接是 phos 使用的歌曲表格
https://www.notion.so/2628769120ad41d998ec068d6e2eb410?v=e8e69ac68a8d483792c54541e4d8ba72
import Notabase from 'notabase'
let nb = Notabase()
let songCollection = await nb.fetch("https://www.notion.so/2628769120ad41d998ec068d6e2eb410?v=e8e69ac68a8d483792c54541e4d8ba72")
let song = songCollection.rows[0]
console.log(song.title)
// 风衣
// 通过名称查找歌曲
// songCollection.rows 是一个 Array,因此可以用 map、filter 等链式操作。
let fy = songCollection.rows.find(s => s.title === "风衣")
console.log(fy.title)
/ 风衣
// 但是现在无法获取到外键数据
console.log(song.artist)
// undefine ?
访问外键数据
要正确处理外键关系,需要一次性获取与该表格存在关联的所有表格数据。
例如 song 表格关联了 artist 和 album 表格。则正确获取数据的方式为
import Notabase from 'notabase'
let nb = Notabase()
let db = await nb.fetchAll({
songs: "https://www.notion.so/2628769120ad41d998ec068d6e2eb410?v=e8e69ac68a8d483792c54541e4d8ba72",
artists: "https://www.notion.so/15f1759f38a34fedaa79262812b707f0?v=b385656739214101b2b8a159092a52e8",
albums: "https://www.notion.so/31b8544ffb034964b1aa56bfa78497c1?v=1d9cbfcd279d4534964acdd374c9824e"
})
const { songs, artists, albums } = db
// 获取第一首歌曲
let song = songs.rows[0]
// 风衣
// 获取风衣的歌手名称
console.log(song.artist[0].name)
// 孙燕姿
fetch
获取单个表格的基础数据fetchAll
获取表格基础数据+外键数据
修改记录
let song = songs.rows.find(s=>s.title === "Tonight, I Feel Close To You")
// 修改歌曲名称(基础)改成中文
song.title = "今晚,我感觉离你很近"
// 修改歌曲的歌手信息(外键)歌手里面漏掉了倉木麻衣,现在加上。
let cmmy = artists.rows.find(a=>a.name==="倉木麻衣")
song.artist = [...song.artist,cmmy]
- 你可以理解为 notion 中所有的外键都是多对多的关系
在浏览器环境中使用
如果你想在网页中使用 Notabase,需要解决 notion 的 api 跨域问题。您可以通过 cloudflare 提供的 work 来处理这件事情。使用
https://github.com/mayneyao/Notabase/blob/master/src/cf-worker.js
中的代码构建一个 worker,得到 wroker 地址。如果要访问私密数据,需要在 worker 中配置
token
和 auth_code
然后可以使用 worker url 和 authcode 初始化一个可以访问并修改个人私密数据的 notabase 实例。
- 当您不提供 authcode 时,只能访问公开数据。
let nb = new Notabase({
proxy: {
url: <cloudflare worker url>,
authCode: <>
}
})
在浏览器扩展环境中使用
在浏览器扩展环境中,无需处理跨域和认证。使用下面代码即可初始化,可以 CRUD notion 表格数据的 notabase 实例。
let nb = new Notabase()
在 node 环境中使用
在 node 环境中不存在跨域问题,修改数据则需要提供 token。
使用下面代码,初始化一个可以访问公开表格数据的 notabase 实例
let nb = new Notabase()
使用下面代码,初始化一个可以 CRUD 表格数据的 notabase 实例
let nb = new Notabase({token:"token_v2"})