How to set up a single js query to handle rest functionality for all data sources in your app

In the current app I'm building, I was going to have to build a post and delete method for all 13 separately existing tables (each in their own view within a stepped container) that each needed their own post/delete rest logic, i.e. when each table contains filtered rows that need to be separately handled.

The short, simple script I created below handles it all without having to create a post and delete method for every single table that may need post/delete functionality. It does so by sequentially executing the following tasks:

  1. Uses triggeredById to find the table to be updated. Here you would simply assign a key / value object where you set each key and value as the name of each table that needs post/delete functionality.
  2. Attempts to find an existing ID match.
    • If a match is found:

      1. We set the restMethod variable to our delete method (since we find a matching ID, we can confirm that the row exists -- so delete that row);
      2. We return the ID of the selected row as an additionalScope (other fields I'm returning here like HEADER and WORKDAY_VALUE are simply being used for a confirmation message to the end user -- not required but good for UX clarity).
    • If a match is not found:

      1. We set the restMethod variable to our post method (since we find no matching ID, the row does not exist yet -- so create/post that row);
      2. We return the column values affiliated with the selected row and its changeset values.
const table = {
  ethnicityTable: ethnicityTable,
  jobProfileTable: jobProfileTable,
  locationTable: locationTable,
  serviceLineTable: serviceLineTable,
  businessUnitTable: businessUnitTable,
  superOrgTable: superOrgTable,
  regionTable: regionTable,
  phoneTypeTable: phoneTypeTable,
  maritalStatusTable: maritalStatusTable,
  hireReasonTable: hireReasonTable
}[triggeredById];

const target = table.changesetArray?.[0];
const row = table.data.find(r => r.ID === table.selectedRow.ID);

let restMethod;
let valueRow;

if (row.ID) {
  restMethod = valueMappingDelete;
  valueRow = {
    ID: row.ID,
    HEADER: row.WORKDAY_HEADER,
    WORKDAY_VALUE: row.WORKDAY_VALUE
  };
} else {
  restMethod = valueMappingPost;
  valueRow = {
    LEGACY_VALUE: target.LEGACY_VALUE,
    WORKDAY_VALUE: target.WORKDAY_VALUE
  };
}

await restMethod.trigger({
  additionalScope: {valueRow}, onSuccess: () => table.refresh()
});

return { restMethod: restMethod.id, valueRow };

This same script can be used to set up an entire rest process w/ update functionality as well. Just set up another condition where an ID row exists, but that an updatable field(s) also exists within your changeset.

Happy coding!!! :technologist:

2 Likes

Very smart! Thanks for sharing!

1 Like

Thank you @MiguelOrtiz!