Edits history of script submission #23242 for ' Get Cell (gsheets)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    export type DynSelect_sheet_name = string
    
    // Dropdown of the spreadsheet's worksheet (tab) names.
    export async function sheet_name(auth: RT.Gsheets, spreadsheet_id: string) {
      const response = await fetch(
        `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}?fields=sheets.properties.title`,
        {
          headers: {
            Authorization: `Bearer ${auth.token}`,
            Accept: "application/json",
          },
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
      const { sheets } = (await response.json()) as {
        sheets: { properties: { title: string } }[]
      }
      return sheets.map((s) => ({
        value: s.properties.title,
        label: s.properties.title,
      }))
    }
    
    /**
     * Get Cell
     * Read one cell (e.g. `B2`) and return its value, or null when empty. `FORMATTED_VALUE` returns what the cell displays, `UNFORMATTED_VALUE` the raw number/boolean, `FORMULA` the formula.
     */
    export async function main(
      auth: RT.Gsheets,
      spreadsheet_id: string,
      sheet_name: DynSelect_sheet_name,
      cell: string,
      value_render_option:
        "FORMATTED_VALUE" | "UNFORMATTED_VALUE" | "FORMULA" = "FORMATTED_VALUE"
    ) {
      const range = encodeURIComponent(
        `'${sheet_name.replaceAll("'", "''")}'!${cell}`
      )
      const url = new URL(
        `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}/values/${range}`
      )
      url.searchParams.append("valueRenderOption", value_render_option)
    
      const response = await fetch(url, {
        headers: {
          Authorization: `Bearer ${auth.token}`,
          Accept: "application/json",
        },
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const { values } = (await response.json()) as { values?: any[][] }
      return values?.[0]?.[0] ?? null
    }
    

    Submitted by hugo989 2 hours ago