Skip to content

Instantly share code, notes, and snippets.

@GreXLin85
Created April 6, 2022 18:07
Show Gist options
  • Save GreXLin85/4c70b1d5e1c60a34cf04ca8563c17c8a to your computer and use it in GitHub Desktop.
Save GreXLin85/4c70b1d5e1c60a34cf04ca8563c17c8a to your computer and use it in GitHub Desktop.
Dump your data as JSON with Sequelize Models
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