0

Upsert Row

by
Published 16 days ago

Update the row whose key column matches, or append a new row if none does.

Script gsheets Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 16 days ago
1
//native
2

3
export type DynSelect_sheet_name = string
4

5
// Dropdown of the spreadsheet's worksheet (tab) names.
6
export async function sheet_name(auth: RT.Gsheets, spreadsheet_id: string) {
7
  const response = await fetch(
8
    `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}?fields=sheets.properties.title`,
9
    {
10
      headers: {
11
        Authorization: `Bearer ${auth.token}`,
12
        Accept: "application/json",
13
      },
14
    }
15
  )
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { sheets } = (await response.json()) as {
20
    sheets: { properties: { title: string } }[]
21
  }
22
  return sheets.map((s) => ({
23
    value: s.properties.title,
24
    label: s.properties.title,
25
  }))
26
}
27

28
/**
29
 * Upsert Row
30
 * Update the first row whose `key_column` (a header name or column letter) equals the key, or append `values` as a new row when none does. The key defaults to the value of `values` in the key column; matching is exact on the displayed value. Values are parsed as if typed in the UI. Returns `action` (updated/appended) and `row_number`.
31
 */
32
export async function main(
33
  auth: RT.Gsheets,
34
  spreadsheet_id: string,
35
  sheet_name: DynSelect_sheet_name,
36
  key_column: string,
37
  values: any[],
38
  key_value: string | undefined
39
) {
40
  const headers = {
41
    Authorization: `Bearer ${auth.token}`,
42
    Accept: "application/json",
43
  }
44
  const base = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}/values`
45
  const tab = `'${sheet_name.replaceAll("'", "''")}'`
46

47
  // ponytail: reads the whole tab to find the key; fine up to tens of thousands of rows.
48
  const read = await fetch(`${base}/${encodeURIComponent(tab)}`, { headers })
49
  if (!read.ok) {
50
    throw new Error(`${read.status} ${await read.text()}`)
51
  }
52
  const { values: rows = [] } = (await read.json()) as { values?: string[][] }
53
  const header = rows[0] ?? []
54

55
  // Header name first, then column letter (A, B, …, AA).
56
  let index = header.indexOf(key_column)
57
  if (index === -1 && /^[A-Za-z]{1,3}$/.test(key_column)) {
58
    index =
59
      [...key_column.toUpperCase()].reduce(
60
        (n, c) => n * 26 + c.charCodeAt(0) - 64,
61
        0
62
      ) - 1
63
  }
64
  if (index === -1) {
65
    throw new Error(
66
      `Column "${key_column}" not found in header row: ${header.join(", ")}`
67
    )
68
  }
69
  const key =
70
    key_value != null && key_value !== ""
71
      ? key_value
72
      : String(values[index] ?? "")
73
  const match = rows.findIndex((row, i) => i > 0 && (row[index] ?? "") === key)
74

75
  if (match !== -1) {
76
    const url = new URL(`${base}/${encodeURIComponent(`${tab}!A${match + 1}`)}`)
77
    url.searchParams.append("valueInputOption", "USER_ENTERED")
78
    const response = await fetch(url, {
79
      method: "PUT",
80
      headers: { ...headers, "Content-Type": "application/json" },
81
      body: JSON.stringify({ values: [values] }),
82
    })
83
    if (!response.ok) {
84
      throw new Error(`${response.status} ${await response.text()}`)
85
    }
86
    return {
87
      action: "updated",
88
      row_number: match + 1,
89
      ...(await response.json()),
90
    }
91
  }
92

93
  const url = new URL(`${base}/${encodeURIComponent(tab)}:append`)
94
  url.searchParams.append("valueInputOption", "USER_ENTERED")
95
  url.searchParams.append("insertDataOption", "INSERT_ROWS")
96
  const response = await fetch(url, {
97
    method: "POST",
98
    headers: { ...headers, "Content-Type": "application/json" },
99
    body: JSON.stringify({ values: [values] }),
100
  })
101
  if (!response.ok) {
102
    throw new Error(`${response.status} ${await response.text()}`)
103
  }
104
  const result = await response.json()
105
  return {
106
    action: "appended",
107
    row_number: Number(result.updates?.updatedRange?.match(/!\D+(\d+)/)?.[1]),
108
    ...result,
109
  }
110
}
111