Created
September 5, 2024 14:11
-
-
Save kevincolten/c1a0f2b94789bf1acb8c24cb057f4d9a to your computer and use it in GitHub Desktop.
Metabase Export/Import Example
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
// METABASE_API_KEY='' METABASE_URL='' COLLECTION_ID='' node index.js | |
const { writeFileSync, readFileSync, cpSync, mkdirSync, existsSync } = require('fs'); | |
const tar = require('tar'); | |
const path = require('path'); | |
const request = require('request-promise-native'); | |
const { METABASE_API_KEY, METABASE_URL, COLLECTION_ID } = process.env; | |
const SERIALIZATION_API_URL = `${METABASE_URL}/api/ee/serialization`; | |
const exportCollection = async (collectionId) => { | |
const dirname = 'from_collection'; | |
const buffer = Buffer.from(await (await fetch(`${SERIALIZATION_API_URL}/export?settings=false&data_model=false&collection=${collectionId}&dirname=${dirname}`, { | |
method: 'POST', | |
headers: { 'x-api-key': METABASE_API_KEY } | |
})).arrayBuffer()); | |
if (!existsSync(path.join(__dirname, 'tmp'))) mkdirSync(path.join(__dirname, 'tmp')); | |
const cwd = path.join(__dirname, 'tmp'); | |
const directory = path.join(__dirname, 'tmp', 'from_collection'); | |
const file = `${directory}.tar.gz`; | |
writeFileSync(file, buffer); | |
await tar.x({ file, cwd }); | |
cpSync(path.join(__dirname, 'tmp', 'from_collection'), path.join(__dirname, 'tmp', 'to_collection'), { recursive: true }); | |
return path.join(__dirname, 'tmp', 'to_collection'); | |
} | |
async function importCollection(directory) { | |
const filePath = `${directory}.tar.gz`.replace('from_collection', 'to_collection'); | |
await tar.create({ gzip: true, file: filePath }, [directory]); | |
const buffer = readFileSync(filePath); | |
const response = await request({ | |
method: 'POST', | |
uri: `${SERIALIZATION_API_URL}/import`, | |
headers: { | |
'x-api-key': METABASE_API_KEY, | |
'Content-Type': 'multipart/form-data', | |
}, | |
formData: { | |
file: { | |
value: buffer, | |
options: { | |
filename: 'file.tar.gz', | |
contentType: 'application/gzip' | |
} | |
} | |
} | |
}); | |
console.log(response); | |
} | |
const syncCollection = async (collectionId) => { | |
const directory = await exportCollection(collectionId); | |
await importCollection(directory); | |
} | |
syncCollection(COLLECTION_ID); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment