Created
April 6, 2022 18:07
-
-
Save GreXLin85/4c70b1d5e1c60a34cf04ca8563c17c8a to your computer and use it in GitHub Desktop.
Dump your data as JSON with Sequelize Models
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
const models = require("../models/index"); | |
const fs = require("fs"); | |
let modelNames = Object.keys(models); | |
// Filter sequelize and Sequelize | |
modelNames = modelNames.filter( | |
(name) => name !== "sequelize" && name !== "Sequelize" | |
); | |
// Filter already existing models by file name | |
modelNames = modelNames.filter((name) => { | |
const fileName = name; | |
return !fs.existsSync(`./data/${fileName}.json`); | |
}); | |
if (modelNames.length === 0) { | |
throw new Error("No models to dump"); | |
} | |
(async () => { | |
for (const modelName of modelNames) { | |
console.log(`Dumping ${modelName}...`); | |
try { | |
const data = await models[modelName].findAll(); | |
const filePath = `./data/${modelName}.json`; | |
fs.writeFileSync(filePath, JSON.stringify(data)); | |
console.log(`${modelName} dumped to ${filePath}`); | |
} catch (error) { | |
console.log("Error occured dumping model: ", modelName); | |
console.error(error); | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment