strapi-plugin-config-sync/services/config.js

79 lines
2.3 KiB
JavaScript
Raw Normal View History

2021-03-19 19:04:22 +01:00
'use strict';
2021-03-19 21:50:23 +01:00
const fs = require('fs');
const util = require('util');
2021-03-19 19:04:22 +01:00
/**
2021-03-20 00:16:26 +01:00
* Main services for config import/export.
2021-03-19 19:04:22 +01:00
*/
module.exports = {
2021-03-20 00:16:26 +01:00
/**
* Write a single config file.
*
* @param {string} configName - The name of the config file.
* @param {string} fileContents - The JSON content of the config file.
* @returns {void}
*/
2021-03-19 21:50:23 +01:00
writeConfigFile: async (configName, fileContents) => {
2021-03-20 00:16:26 +01:00
// Check if the config should be excluded.
const shouldExclude = strapi.plugins.config.config.exclude.includes(configName);
if (shouldExclude) return;
2021-03-20 00:16:26 +01:00
// Check if the JSON content should be minified.
const json =
2021-03-19 22:50:12 +01:00
!strapi.plugins.config.config.minify ?
JSON.stringify(JSON.parse(fileContents), null, 2)
: fileContents;
if (!fs.existsSync(strapi.plugins.config.config.destination)) {
fs.mkdirSync(strapi.plugins.config.config.destination, { recursive: true });
}
const writeFile = util.promisify(fs.writeFile);
await writeFile(`${strapi.plugins.config.config.destination}${configName}.json`, json);
2021-03-19 21:50:23 +01:00
},
2021-03-20 00:16:26 +01:00
/**
* Read from a config file.
*
* @param {string} configName - The name of the config file.
* @returns {object} The JSON content of the config file.
*/
2021-03-19 21:50:23 +01:00
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;
});
},
2021-03-20 00:16:26 +01:00
/**
* Import a config file into the db.
*
* @param {string} configName - The name of the config file.
* @returns {void}
*/
2021-03-19 21:50:23 +01:00
importFromFile: async (configName) => {
2021-03-20 00:16:26 +01:00
// Check if the config should be excluded.
const shouldExclude = strapi.plugins.config.config.exclude.includes(configName);
if (shouldExclude) return;
2021-03-19 21:50:23 +01:00
const coreStoreAPI = strapi.query('core_store');
const fileContents = await strapi.plugins.config.services.config.readConfigFile(configName);
2021-03-20 00:16:26 +01:00
const configExists = await strapi
2021-03-19 21:50:23 +01:00
.query('core_store')
.findOne({ key: configName });
2021-03-20 00:16:26 +01:00
if (!configExists) {
await coreStoreAPI.create({ key: configName, value: fileContents });
} else {
await coreStoreAPI.update({ key: configName }, { value: fileContents });
2021-03-19 21:50:23 +01:00
}
}
2021-03-19 19:04:22 +01:00
};