Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions playground/__tests__/cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down
74 changes: 74 additions & 0 deletions playground/__tests__/import.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});
7 changes: 5 additions & 2 deletions server/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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') {
Expand Down
7 changes: 4 additions & 3 deletions server/controllers/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down
6 changes: 4 additions & 2 deletions server/services/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -234,7 +236,7 @@ export default () => ({
}

await strapi.plugin('config-sync').service('main').importSingleConfig(`${type}.${name}`, onSuccess);
}));
}), Promise.resolve());
},

/**
Expand Down