Initial import/export backend

pull/1/head
Boaz Poolman 2021-03-19 21:50:23 +01:00
parent f6f9beb786
commit 2535d76909
4 changed files with 89 additions and 6 deletions

4
config/config.json Normal file
View File

@ -0,0 +1,4 @@
{
"destination": "extensions/config/files/",
"exclude": []
}

View File

@ -2,8 +2,16 @@
"routes": [
{
"method": "GET",
"path": "/",
"handler": "config.index",
"path": "/export",
"handler": "config.export",
"config": {
"policies": []
}
},
{
"method": "GET",
"path": "/import",
"handler": "config.import",
"config": {
"policies": []
}

View File

@ -1,5 +1,7 @@
'use strict';
const fs = require('fs');
/**
* config.js controller
*
@ -14,12 +16,37 @@ module.exports = {
* @return {Object}
*/
index: async (ctx) => {
// Add your own logic here.
export: async (ctx) => {
const coreStoreAPI = strapi.query('core_store');
const coreStore = await coreStoreAPI.find({ _limit: -1 });
Object.values(coreStore).map(async ({ key, value }) => {
await strapi.plugins.config.services.config.writeConfigFile(key, value);
});
// Send 200 `ok`
ctx.send({
message: 'ok'
message: `Config was successfully exported to ${strapi.plugins.config.config.destination}.`
});
},
import: async (ctx) => {
// Check for existance of the config file destination dir.
if (!fs.existsSync(strapi.plugins.config.config.destination)) {
ctx.send({
message: 'No config files were found.'
});
return;
}
const configFiles = fs.readdirSync(strapi.plugins.config.config.destination);
configFiles.map((file) => {
strapi.plugins.config.services.config.importFromFile(file.slice(0, -5));
});
ctx.send({
message: 'Config was successfully imported.'
});
}
};

View File

@ -1,5 +1,8 @@
'use strict';
const fs = require('fs');
const util = require('util');
/**
* config.js service
*
@ -7,5 +10,46 @@
*/
module.exports = {
writeConfigFile: async (configName, fileContents) => {
await strapi.fs.writePluginFile(
'config',
`files/${configName}.json`,
fileContents
);
},
readConfigFile: async (configName) => {
const readFile = util.promisify(fs.readFile);
return await readFile(`${strapi.plugins.config.config.destination}${configName}.json`)
.then((data) => {
return JSON.parse(data);
})
.catch(() => {
return null;
});
},
importFromFile: async (configName) => {
const coreStoreAPI = strapi.query('core_store');
const fileContents = await strapi.plugins.config.services.config.readConfigFile(configName);
// If there is no corresponding config file we should not try to import.
if (!fileContents) return;
try {
const configExists = await strapi
.query('core_store')
.findOne({ key: configName });
if (!configExists) {
await coreStoreAPI.create({ key: configName, value: fileContents });
} else {
await coreStoreAPI.update({ key: configName }, { value: fileContents });
}
return { success: true };
} catch (err) {
throw new Error(err);
}
}
};