directus-sync icon indicating copy to clipboard operation
directus-sync copied to clipboard

Sort fields inside JSON files for easier code review

Open Dominic-Preap opened this issue 11 months ago • 3 comments

Is your feature request related to a problem? Please describe.

Currently when we make change in Directus and run pull command, all of the fields in files sometimes changes the ordering making the code review is difficult to follow (example image below).

Describe the solution you'd like

In the past, we used directus-utilities to import the changes, it has the same issues but we make custom script to make sure sort alphabetically. I think we can do something similar.

Either sort fields alphabetically or default fields but make sure it's consistent.

// Example script we used in directus-utilities of Directus 10

const { Directus } = require('@directus/sdk'); // Directus SDK v10
const sortJson = require('sort-json');

const {
  exportDefaultPreset,
  exportPublicPermissions,
  exportPermissionsByRolename
} = require('directus-utilities');

const { presets, publicPermission, roles } = require('./config');

const run = async () => {
  const directus = new Directus('http://localhost:8055', {
    auth: { staticToken: 'MY_TOKEN' }
  });

  await Promise.all(presets.map(x => exportDefaultPreset(directus, x.collection, x.target)));
  await Promise.all(roles.map(x => exportPermissionsByRolename(directus, x.roleName, x.target)));
  await exportPublicPermissions(directus, publicPermission);

 // Sort fields in json
  sortJson.overwrite([
    ...presets.map(x => x.target),
    ...roles.map(x => x.target),
    publicPermission
  ]);
};

run().then(() => {
  process.exit();
});

Describe alternatives you've considered N/A

Additional context

Image

Image

Dominic-Preap avatar Feb 05 '25 12:02 Dominic-Preap

Hi @Dominic-Preap,
That's a good point. However, this should be an option; otherwise, it would create too many diffs when people upgrade the directus-sync CLI.

EdouardDem avatar Feb 10 '25 14:02 EdouardDem

Meanwhile you can use the snapshot hook onSave to sort the JSON keys : https://tractr.github.io/directus-sync/docs/features/hooks#snapshot-hooks

EdouardDem avatar Feb 10 '25 14:02 EdouardDem

Thank you, it's working for me.

const sortJson = require('sort-json');

// Change URL & token to your Directus instance
module.exports = {
  directusUrl: 'http://localhost:8055',
  directusToken: 'token',
  specs: false,
  hooks: {
    snapshot: {
      /**
       * @param {Snapshot} snapshot
       * @param {DirectusClient} client
       */
      onSave: async (snapshot, client) => {
        return sortJson(snapshot);
      },
    },
  },
};

Dominic-Preap avatar Feb 17 '25 07:02 Dominic-Preap

Hi. It has been added in the new version: https://github.com/tractr/directus-sync/releases/tag/directus-sync%403.3.0

EdouardDem avatar Aug 14 '25 15:08 EdouardDem