Last active
November 19, 2022 02:45
-
-
Save miguelmota/847bdd00a1b7610c3b9fde53bd330ddb to your computer and use it in GitHub Desktop.
Node.js fetch Metabase download all dashboard queries
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
require('dotenv').config() | |
const fetch = require('node-fetch') | |
const path = require('path') | |
const fs = require('fs') | |
const token = process.env.METABASE_TOKEN | |
const outputDir = process.env.OUTPUT_DIR || './' | |
async function auth() { | |
const res = await fetch('https://metabase.example.com/api/session', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify({ | |
'username': 'email', | |
'password': 'password' | |
}) | |
}); | |
const json = await res.json(); | |
console.log(json) | |
} | |
async function main () { | |
const baseDir = path.resolve(__dirname, outputDir) | |
if (!fs.existsSync(baseDir)) { | |
fs.mkdirSync(baseDir) | |
} | |
const res = await fetch('https://metabase.example.com/api/dashboard', { | |
headers: { | |
'X-Metabase-Session': token | |
} | |
}) | |
const json = await res.json() | |
for (const dashboard of json) { | |
const res = await fetch(`https://metabase.example.com/api/dashboard/${dashboard.id}`, { | |
headers: { | |
'X-Metabase-Session': token | |
} | |
}) | |
const json = await res.json() | |
if (!json.name) { | |
continue | |
} | |
const dir = path.resolve(baseDir, json.name) | |
if (!fs.existsSync(dir)) { | |
fs.mkdirSync(dir) | |
} | |
console.log(`Fetching dashboard: ${json.name}`) | |
for (const item of json.ordered_cards) { | |
if (!item.card.name) { | |
continue | |
} | |
const file = path.resolve(dir, item.card.name) | |
if (!item.card.dataset_query.native.query) { | |
continue | |
} | |
console.log(`\tFetching query: ${item.card.name}`) | |
fs.writeFileSync(file, item.card.dataset_query.native.query) | |
} | |
} | |
console.log('done') | |
} | |
main().catch(console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment