diff --git a/playground/__tests__/cli.test.js b/playground/__tests__/cli.test.js index 965bc31..d98772f 100644 --- a/playground/__tests__/cli.test.js +++ b/playground/__tests__/cli.test.js @@ -127,6 +127,34 @@ describe('Test the config-sync CLI', () => { expect(diffOutput).toContain('No differences between DB and sync directory'); }); + test('Import stops at the first config that fails and exits 1', async () => { + const invalidFile = 'config/sync/user-role.public.json'; + const changedFile = 'config/sync/user-role.authenticated.json'; + const invalidOriginal = fs.readFileSync(invalidFile, 'utf8'); + const changedOriginal = fs.readFileSync(changedFile, 'utf8'); + const changed = JSON.parse(changedOriginal); + changed.description = 'Not imported'; + fs.writeFileSync(invalidFile, '{ "name": '); + fs.writeFileSync(changedFile, JSON.stringify(changed)); + + let error; + try { + await exec('yarn cs import -p user-role.public,user-role.authenticated -y'); + } catch (e) { + error = e; + } finally { + fs.writeFileSync(invalidFile, invalidOriginal); + fs.writeFileSync(changedFile, changedOriginal); + } + + expect(error).toHaveProperty('code', 1); + expect(error.stdout).toContain('[error]'); + expect(error.stdout).not.toContain('Finished import'); + // The config after the failing one was left alone. + const { stdout: diffOutput } = await exec('yarn cs diff'); + expect(diffOutput).toContain('No differences between DB and sync directory'); + }); + test.each([ ['user-role.public', '{\n "name": ,\n}', 'line 2, column 11'], ['user-role.public', '{\n "name": "ab\\q"\n}', 'line 2, column 15'], diff --git a/playground/__tests__/import.test.js b/playground/__tests__/import.test.js new file mode 100644 index 0000000..f497723 --- /dev/null +++ b/playground/__tests__/import.test.js @@ -0,0 +1,74 @@ +const fs = require('fs'); +const util = require('util'); +const exec = util.promisify(require('child_process').exec); + +const { setupStrapi, cleanupStrapi } = require('./helpers'); + +jest.setTimeout(20000); + +// Each new i18n locale makes Strapi rewrite the super admin's permissions, so +// locales imported at the same time can collide on the permission ids +// (seen on MySQL/MariaDB; better-sqlite3 answers synchronously, so SQLite +// doesn't show it). The import has to handle one config at a time. +let active; +let maxActive; + +const writeLocaleFiles = (codes) => codes.forEach((code) => { + fs.writeFileSync(`config/sync/i18n-locale.${code}.json`, JSON.stringify({ name: code, code })); +}); + +const localeCodes = async () => (await strapi.db.query('plugin::i18n.locale').findMany()).map(({ code }) => code); + +beforeAll(async () => { + await exec('rm -rf .tmp config/sync'); + await exec('yarn cs export -y'); + await setupStrapi(); + + const main = strapi.plugin('config-sync').service('main'); + const { importSingleConfig } = main; + main.importSingleConfig = async (...args) => { + active += 1; + maxActive = Math.max(maxActive, active); + try { + return await importSingleConfig(...args); + } finally { + active -= 1; + } + }; +}); + +afterAll(async () => { + await cleanupStrapi(); + await exec('rm -rf config/sync'); +}); + +beforeEach(() => { + active = 0; + maxActive = 0; +}); + +describe('Test importing several configs', () => { + test('Import all config imports one config at a time', async () => { + writeLocaleFiles(['de', 'fr', 'nl']); + + await strapi.plugin('config-sync').service('main').importAllConfig(); + + expect(await localeCodes()).toEqual(expect.arrayContaining(['de', 'fr', 'nl'])); + expect(maxActive).toBe(1); + }); + + test('The import endpoint imports one config at a time', async () => { + writeLocaleFiles(['es', 'it', 'pt']); + let response; + const ctx = { + request: { body: { config: ['i18n-locale.es', 'i18n-locale.it', 'i18n-locale.pt'] } }, + send: (body) => { response = body; }, + }; + + await strapi.plugin('config-sync').controller('config').importAll(ctx); + + expect(response.message).toContain('successfully imported'); + expect(await localeCodes()).toEqual(expect.arrayContaining(['es', 'it', 'pt'])); + expect(maxActive).toBe(1); + }); +}); diff --git a/server/cli.js b/server/cli.js index 67d3c82..3b56928 100644 --- a/server/cli.js +++ b/server/cli.js @@ -164,7 +164,9 @@ const handleAction = async (syncType, skipConfirm, configType, partials, force) if (syncType === 'import') { const onSuccess = (name) => console.log(`${chalk.cyan.bold('[notice]')} Imported ${name}`); try { - await Promise.all(Object.keys(finalDiff).map(async (name) => { + // One at a time: importing some configs changes others (each new + // i18n locale rewrites the super admin's permissions). + await Object.keys(finalDiff).reduce((previousImport, name) => previousImport.then(async () => { let warning; if ( getConfigState(diff, name, syncType) === chalk.red('Delete') @@ -173,10 +175,11 @@ const handleAction = async (syncType, skipConfirm, configType, partials, force) await app.plugin('config-sync').service('main').importSingleConfig(name, onSuccess, force); if (warning) console.log(`${chalk.yellow.bold('[warning]')} ${warning}`); - })); + }), Promise.resolve()); console.log(`${chalk.green.bold('[success]')} Finished import`); } catch (e) { console.log(`${chalk.red.bold('[error]')} ${e}`); + process.exit(1); } } if (syncType === 'export') { diff --git a/server/controllers/config.js b/server/controllers/config.js index 5ddf9ee..37ec543 100644 --- a/server/controllers/config.js +++ b/server/controllers/config.js @@ -65,9 +65,10 @@ export default { return; } - await Promise.all(ctx.request.body.config.map(async (configName) => { - await strapi.plugin('config-sync').service('main').importSingleConfig(configName, null, ctx.request.body.force); - })); + // One at a time, like the CLI and importAllConfig. + await ctx.request.body.config.reduce((previousImport, configName) => previousImport.then(() => ( + strapi.plugin('config-sync').service('main').importSingleConfig(configName, null, ctx.request.body.force) + )), Promise.resolve()); ctx.send({ message: 'Config was successfully imported.', diff --git a/server/services/main.js b/server/services/main.js index 97c0163..6129e97 100644 --- a/server/services/main.js +++ b/server/services/main.js @@ -225,7 +225,9 @@ export default () => ({ const diff = difference(databaseConfig, fileConfig); - await Promise.all(Object.keys(diff).map(async (file) => { + // One at a time: importing some configs changes others (each new + // i18n locale rewrites the super admin's permissions). + await Object.keys(diff).reduce((previousImport, file) => previousImport.then(async () => { const type = file.split('.')[0]; // Grab the first part of the filename. const name = file.split(/\.(.+)/)[1]; // Grab the rest of the filename. @@ -234,7 +236,7 @@ export default () => ({ } await strapi.plugin('config-sync').service('main').importSingleConfig(`${type}.${name}`, onSuccess); - })); + }), Promise.resolve()); }, /**