Edits history of script submission #23139 for ' Update Data Source (notion)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_data_source_id = string
    
    export async function data_source_id(auth: RT.Notion) {
      const response = await fetch("https://api.notion.com/v1/search", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/json",
          Accept: "application/json",
          "Notion-Version": "2026-03-11",
        },
        body: JSON.stringify({
          filter: { property: "object", value: "data_source" },
        }),
      })
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { results } = (await response.json()) as {
        results: { id: string; title: { plain_text: string }[] }[]
      }
      return results.map((d) => ({
        value: d.id,
        label: d.title.map((t) => t.plain_text).join("") || d.id,
      }))
    }
    
    /**
     * Update Data Source
     * Rename a data source or change its columns. `properties` maps a column name to its new schema, or a type name for simple columns: a new name adds a column, an existing one is retyped, {"name": "New name"} renames it, and null removes it. Columns left out are unchanged.
     */
    export async function main(
      auth: RT.Notion,
      data_source_id: DynSelect_data_source_id,
      title: string | undefined,
      properties: { [key: string]: any } | undefined
    ) {
      const body: { [key: string]: any } = {}
      if (title !== undefined && title !== "") {
        body.title = [{ text: { content: title } }]
      }
      if (properties && Object.keys(properties).length) {
        body.properties = {}
        for (const [name, value] of Object.entries(properties)) {
          body.properties[name] =
            typeof value === "string" ? { [value]: {} } : value
        }
      }
    
      const response = await fetch(
        `https://api.notion.com/v1/data_sources/${data_source_id}`,
        {
          method: "PATCH",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json",
            Accept: "application/json",
            "Notion-Version": "2026-03-11",
          },
          body: JSON.stringify(body),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 4 hours ago