简体   繁体   中英

Change/map object properties to enum values

I get a data object from the backend that looks like this:

  data: [
            {description: 'desc', timestamp: yesterday, type: 'Repair', repair: {}},
            {description: 'desc', timestamp: oneMonthBack, type: 'Checked', readout: {}},
            {description: 'desc', timestamp: threeMonthBack, type: 'False', fault: {}},
            {description: 'desc', timestamp: yesterday, type: 'Read', falseRead: [{}]},
            {description: 'desc', timestamp: yesterday, type: 'Clear'}
          ],

In front-end we have changed the datas "type" via one enum:

export enum ProductEventType {
  FAULT = 'Alert',//Old "False"
  REPAIR = 'repair', //old 'Repair'
  DELIVERY = 'Delivery', //same as before
  CHECKIN = 'check-in', //old 'checked' 
  READFAULTS = 'readFaults',  //old Read
  CLEARFAULTS = 'ClearFaults', //old Clear
}

When we get the data from the backend we use a map and check every item:

this.vehicleEvents.data.forEach((item) => {

      if (RepairEvent.isRepairEvent(item)) {...}

inside the RepairEvent.isRepairEvent lies the issue, where the fault lies that we match the backend name of the data and the front-end enum name. Notice we import and use the enum type:

export class ClearFaultsEvent extends ProductTimelineEvent {
  public static isClearFaultsEvent(event: ProductTimelineEvent): event is ClearFaultsEvent {
    return event.type === ProductTimelineEventType.CLEARFAULTS; 

//err, event.type is 'Clear' while the enumtype have the name "ClearFaults"
      }

In above code we compare the backend name of the data and the name from the enum which obviously returns false, but we want true. We want the event.type somehow mapped or combined with the enum values so the conditional will works. As for now it will always be false. Any help?

You seem to be asking for this

const adaptType = adaptTable => f => ({type}) => f({
  type: adaptTable[type]
});

const adaptProductEvents = adaptType({
  'False': 'Alert',
  'Repair': 'repair',
  'Delivery': 'Delivery',
  'checked': 'check-in',
  'Read': 'readFaults',
  'Clear': 'ClearFaults',
});

data.map(adaptProductEvents(ClearFaultsEvent.isClearFaultsEvent))
// [ false, false, false, false, true ]

But it doesn't scale. A more sensible change would be to create adapter classes which would conform to the back-end API.

Now I am surprised that the values of the enum matter to you. If you need to do some IO based on the enum values, that should be the responsibility of a presenter to translate them to the correct output. You don't want business rules to know about the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM