feat: lire tous les onglets Google Sheets (un onglet par famille de produits)
This commit is contained in:
+28
-6
@@ -36,27 +36,49 @@ export function parseSheetRows(rows: string[][]): SyncProduct[] {
|
||||
|
||||
/**
|
||||
* Lit tous les produits depuis Google Sheets via l'API v4 (API Key publique).
|
||||
* Si GOOGLE_SHEETS_TAB est défini, lit uniquement cet onglet.
|
||||
* Sinon, lit tous les onglets du fichier et combine les produits.
|
||||
* Le fichier Sheets doit être partagé en lecture ("Toute personne avec le lien").
|
||||
*/
|
||||
export async function readSheetProducts(): Promise<SyncProduct[]> {
|
||||
const apiKey = process.env.GOOGLE_API_KEY
|
||||
const sheetId = process.env.GOOGLE_SHEETS_ID
|
||||
const sheetName = process.env.GOOGLE_SHEETS_TAB ?? 'MATRICE'
|
||||
const singleTab = process.env.GOOGLE_SHEETS_TAB
|
||||
|
||||
if (!apiKey || !sheetId) {
|
||||
throw new Error('Variables GOOGLE_API_KEY et GOOGLE_SHEETS_ID requises')
|
||||
}
|
||||
|
||||
const range = encodeURIComponent(`${sheetName}!A2:F`)
|
||||
const url = `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}/values/${range}?key=${apiKey}`
|
||||
const sheetNames = singleTab ? [singleTab] : await listSheetTabs(sheetId, apiKey)
|
||||
|
||||
const results = await Promise.all(
|
||||
sheetNames.map((name) => readOneTab(sheetId, apiKey, name)),
|
||||
)
|
||||
|
||||
return results.flat()
|
||||
}
|
||||
|
||||
async function listSheetTabs(sheetId: string, apiKey: string): Promise<string[]> {
|
||||
const url = `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}?key=${apiKey}&fields=sheets.properties.title`
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) {
|
||||
const err = await res.text()
|
||||
throw new Error(`Google Sheets API error: ${res.status} — ${err}`)
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
const rows = (data.values ?? []) as string[][]
|
||||
return parseSheetRows(rows)
|
||||
return (data.sheets as Array<{ properties: { title: string } }>).map(
|
||||
(s) => s.properties.title,
|
||||
)
|
||||
}
|
||||
|
||||
async function readOneTab(sheetId: string, apiKey: string, sheetName: string): Promise<SyncProduct[]> {
|
||||
const range = encodeURIComponent(`${sheetName}!A2:F`)
|
||||
const url = `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}/values/${range}?key=${apiKey}`
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) {
|
||||
const err = await res.text()
|
||||
throw new Error(`Google Sheets API error (onglet "${sheetName}"): ${res.status} — ${err}`)
|
||||
}
|
||||
const data = await res.json()
|
||||
return parseSheetRows((data.values ?? []) as string[][])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user