Last active
November 30, 2023 18:56
-
-
Save thomaswilburn/d4ef1df3463d332aaf757ffbfe9ca249 to your computer and use it in GitHub Desktop.
Update DW graphics from a Google Sheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// run with deno run --allow-all datapatcher.js {SHEET_ID} {SHEET_TAB (optional)} | |
import { login, google } from "https://raw.githubusercontent.com/Chalkbeat/deno-google-login/main/index.js"; | |
import * as flags from "https://deno.land/[email protected]/flags/mod.ts"; | |
var args = flags.parse(Deno.args); | |
var spreadsheetId = args.sheet || args._[0]; | |
var auth = await login(); | |
var sheets = google.sheets("v4"); | |
var meta = await sheets.spreadsheets.get({ | |
auth, | |
spreadsheetId | |
}); | |
var sheetNames = meta.data.sheets.map(s => s.properties.title); | |
var targetSheet = args.tab || args._[1] || sheetNames.includes("patch") ? "patch" : sheetNames[0]; | |
var cells = (await sheets.spreadsheets.values.get({ | |
auth, spreadsheetId, | |
range: `${targetSheet}!A:Z` | |
})).data.values; | |
var patches = {}; | |
var header = cells.shift(); | |
for (var row of cells) { | |
var o = Object.fromEntries(row.map((r, i) => [header[i], r])); | |
if (!(o.id in patches)) { | |
patches[o.id] = {}; | |
} | |
var patch = patches[o.id]; | |
var keys = o.property.split("."); | |
var tail = keys.pop(); | |
for (var k of keys) { | |
if (!patch[k]) { | |
patch[k] = {}; | |
} | |
patch = patch[k]; | |
} | |
patch[tail] = o.value; | |
} | |
const DW_KEY = Deno.env.get("DATAWRAPPER_API_KEY"); | |
function fetchDW(endpoint, options = {}) { | |
return fetch(`https://api.datawrapper.de/v3/${endpoint}`, { | |
...options, | |
headers: { | |
...options.headers, | |
Authorization: `Bearer ${DW_KEY}` | |
} | |
}).then(r => r.json()); | |
} | |
function patchDW(endpoint, data) { | |
return fetchDW(endpoint, { | |
method: "PATCH", | |
headers: { | |
"Content-Type": "application/json" | |
}, | |
body: JSON.stringify(data) | |
}); | |
} | |
for (var [ chart, patch ] of Object.entries(patches)) { | |
var chartMeta = await fetchDW(`charts/${chart}`); | |
console.log(`Current chart data for ${chart}`); | |
console.log(chartMeta); | |
console.log(`Updating ${chart} with:`); | |
console.log(patch); | |
var result = await patchDW(`charts/${chart}`, patch); | |
// console.log(result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment