This commit is contained in:
Sam Rose 2024-09-19 10:09:21 +01:00
parent 27f6fa7de4
commit fd353b2ecf
No known key found for this signature in database
4 changed files with 133 additions and 84 deletions

View File

@ -25,7 +25,11 @@ import {
checkExternalTables, checkExternalTables,
finaliseExternalTables, finaliseExternalTables,
} from "./utils" } from "./utils"
import { GoogleSpreadsheet, GoogleSpreadsheetRow } from "google-spreadsheet" import {
GoogleSpreadsheet,
GoogleSpreadsheetRow,
GoogleSpreadsheetWorksheet,
} from "google-spreadsheet"
import fetch from "node-fetch" import fetch from "node-fetch"
import { cache, configs, context, HTTPError } from "@budibase/backend-core" import { cache, configs, context, HTTPError } from "@budibase/backend-core"
import { dataFilters, utils } from "@budibase/shared-core" import { dataFilters, utils } from "@budibase/shared-core"
@ -330,15 +334,16 @@ export class GoogleSheetsIntegration implements DatasourcePlus {
return { tables: {}, errors: {} } return { tables: {}, errors: {} }
} }
await this.connect() await this.connect()
const sheets = this.client.sheetsByIndex const sheets = this.client.sheetsByIndex
const tables: Record<string, Table> = {} const tables: Record<string, Table> = {}
let errors: Record<string, string> = {} let errors: Record<string, string> = {}
await utils.parallelForeach(
sheets, let promises: Promise<void>[] = []
async sheet => { for (const sheet of sheets) {
// must fetch rows to determine schema const f = async (sheet: GoogleSpreadsheetWorksheet) => {
try { try {
await sheet.getRows() await sheet.getRows({ limit: 1 })
} catch (err) { } catch (err) {
// We expect this to always be an Error so if it's not, rethrow it to // We expect this to always be an Error so if it's not, rethrow it to
// make sure we don't fail quietly. // make sure we don't fail quietly.
@ -346,26 +351,36 @@ export class GoogleSheetsIntegration implements DatasourcePlus {
throw err throw err
} }
if (err.message.startsWith("No values in the header row")) { if (
errors[sheet.title] = err.message err.message.startsWith("No values in the header row") ||
} else { err.message.startsWith("Header values are not yet loaded")
// If we get an error we don't expect, rethrow to avoid failing ) {
// quietly. errors[
throw err sheet.title
] = `Failed to find a header row in sheet "${sheet.title}", is the first row blank?`
return
} }
return
}
const id = buildExternalTableId(datasourceId, sheet.title) // If we get an error we don't expect, rethrow to avoid failing
tables[sheet.title] = this.getTableSchema( // quietly.
sheet.title, throw err
sheet.headerValues, }
datasourceId, }
id promises.push(f(sheet))
) }
},
10 await Promise.all(promises)
)
for (const sheet of sheets) {
const id = buildExternalTableId(datasourceId, sheet.title)
tables[sheet.title] = this.getTableSchema(
sheet.title,
sheet.headerValues,
datasourceId,
id
)
}
let externalTables = finaliseExternalTables(tables, entities) let externalTables = finaliseExternalTables(tables, entities)
errors = { ...errors, ...checkExternalTables(externalTables) } errors = { ...errors, ...checkExternalTables(externalTables) }
return { tables: externalTables, errors } return { tables: externalTables, errors }

View File

@ -10,7 +10,6 @@ import {
TableSourceType, TableSourceType,
} from "@budibase/types" } from "@budibase/types"
import { GoogleSheetsMock } from "./utils/googlesheets" import { GoogleSheetsMock } from "./utils/googlesheets"
import rows from "src/sdk/app/rows"
describe("Google Sheets Integration", () => { describe("Google Sheets Integration", () => {
const config = new TestConfiguration() const config = new TestConfiguration()
@ -506,4 +505,22 @@ describe("Google Sheets Integration", () => {
expect(emptyRows.length).toEqual(0) expect(emptyRows.length).toEqual(0)
}) })
}) })
describe("import spreadsheet", () => {
it.only("should fail to import a completely blank sheet", async () => {
mock.createSheet({ title: "Sheet1" })
await config.api.datasource.fetchSchema(
{
datasourceId: datasource._id!,
tablesFilter: ["Sheet1"],
},
{
status: 400,
body: {
message: "",
},
}
)
})
})
}) })

View File

@ -22,6 +22,7 @@ import type {
CellPadding, CellPadding,
Color, Color,
GridRange, GridRange,
DataSourceSheetProperties,
} from "google-spreadsheet/src/lib/types/sheets-types" } from "google-spreadsheet/src/lib/types/sheets-types"
const BLACK: Color = { red: 0, green: 0, blue: 0 } const BLACK: Color = { red: 0, green: 0, blue: 0 }
@ -91,7 +92,7 @@ interface UpdateValuesResponse {
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddSheetRequest // https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#AddSheetRequest
interface AddSheetRequest { interface AddSheetRequest {
properties: WorksheetProperties properties: Partial<WorksheetProperties>
} }
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/response#AddSheetResponse // https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/response#AddSheetResponse
@ -236,6 +237,38 @@ export class GoogleSheetsMock {
this.mockAPI() this.mockAPI()
} }
public cell(cell: string): Value | undefined {
const cellData = this.cellData(cell)
if (!cellData) {
return undefined
}
return this.cellValue(cellData)
}
public set(cell: string, value: Value): void {
const cellData = this.cellData(cell)
if (!cellData) {
throw new Error(`Cell ${cell} not found`)
}
cellData.userEnteredValue = this.createValue(value)
}
public sheet(name: string | number): Sheet | undefined {
if (typeof name === "number") {
return this.getSheetById(name)
}
return this.getSheetByName(name)
}
public createSheet(opts: Partial<WorksheetProperties>): Sheet {
const properties = this.defaultWorksheetProperties(opts)
if (this.getSheetByName(properties.title)) {
throw new Error(`Sheet ${properties.title} already exists`)
}
const resp = this.handleAddSheet({ properties })
return this.getSheetById(resp.properties.sheetId)!
}
private route( private route(
method: "get" | "put" | "post", method: "get" | "put" | "post",
path: string | RegExp, path: string | RegExp,
@ -462,35 +495,39 @@ export class GoogleSheetsMock {
return response return response
} }
private handleAddSheet(request: AddSheetRequest): AddSheetResponse { private defaultWorksheetProperties(
const properties: Omit<WorksheetProperties, "dataSourceSheetProperties"> = { opts: Partial<WorksheetProperties>
): WorksheetProperties {
return {
index: this.spreadsheet.sheets.length, index: this.spreadsheet.sheets.length,
hidden: false, hidden: false,
rightToLeft: false, rightToLeft: false,
tabColor: BLACK, tabColor: BLACK,
tabColorStyle: { rgbColor: BLACK }, tabColorStyle: { rgbColor: BLACK },
sheetType: "GRID", sheetType: "GRID",
title: request.properties.title, title: "Sheet",
sheetId: this.spreadsheet.sheets.length, sheetId: this.spreadsheet.sheets.length,
gridProperties: { gridProperties: {
rowCount: 100, rowCount: 100,
columnCount: 26, columnCount: 26,
frozenRowCount: 0,
frozenColumnCount: 0,
hideGridlines: false,
rowGroupControlAfter: false,
columnGroupControlAfter: false,
}, },
dataSourceSheetProperties: {} as DataSourceSheetProperties,
...opts,
} }
}
private handleAddSheet(request: AddSheetRequest): AddSheetResponse {
const properties = this.defaultWorksheetProperties(request.properties)
this.spreadsheet.sheets.push({ this.spreadsheet.sheets.push({
properties: properties as WorksheetProperties, properties,
data: [this.createEmptyGrid(100, 26)], data: [
this.createEmptyGrid(
properties.gridProperties.rowCount,
properties.gridProperties.columnCount
),
],
}) })
return { properties }
// dataSourceSheetProperties is only returned by the API if the sheet type is
// DATA_SOURCE, which we aren't using, so sadly we need to cast here.
return { properties: properties as WorksheetProperties }
} }
private handleDeleteRange(request: DeleteRangeRequest) { private handleDeleteRange(request: DeleteRangeRequest) {
@ -767,21 +804,6 @@ export class GoogleSheetsMock {
return this.getCellNumericIndexes(sheetId, startRowIndex, startColumnIndex) return this.getCellNumericIndexes(sheetId, startRowIndex, startColumnIndex)
} }
public cell(cell: string): Value | undefined {
const cellData = this.cellData(cell)
if (!cellData) {
return undefined
}
return this.cellValue(cellData)
}
public sheet(name: string | number): Sheet | undefined {
if (typeof name === "number") {
return this.getSheetById(name)
}
return this.getSheetByName(name)
}
private getCellNumericIndexes( private getCellNumericIndexes(
sheet: Sheet | number, sheet: Sheet | number,
row: number, row: number,

View File

@ -7,43 +7,38 @@ export function unreachable(
throw new Error(message) throw new Error(message)
} }
interface PromiseWithId<T> {
promise: Promise<T>
id: number
}
export async function parallelForeach<T>( export async function parallelForeach<T>(
items: T[], items: T[],
task: (item: T) => Promise<void>, task: (item: T) => Promise<void>,
maxConcurrency: number maxConcurrency: number
): Promise<void> { ): Promise<void> {
const promises: Promise<void>[] = [] try {
let index = 0 let next = 0
let inProgress: PromiseWithId<number>[] = []
while (next < items.length) {
if (inProgress.length === maxConcurrency) {
const finished = await Promise.race(inProgress.map(t => t.promise))
inProgress = inProgress.filter(task => task.id !== finished)
}
const processItem = async (item: T) => { const promise = async (next: number) => {
try { await task(items[next])
await task(item) return next
} finally { }
processNext()
inProgress.push({ promise: promise(next), id: next })
next++
} }
await Promise.all(inProgress.map(t => t.promise))
} catch (e) {
console.error(e)
throw e
} }
const processNext = () => {
if (index >= items.length) {
// No more items to process
return
}
const item = items[index]
index++
const promise = processItem(item)
promises.push(promise)
if (promises.length >= maxConcurrency) {
Promise.race(promises).then(processNext)
} else {
processNext()
}
}
processNext()
await Promise.all(promises)
} }
export function filterValueToLabel() { export function filterValueToLabel() {