首页 > 解决方案 > API 请求:设置枚举值的更好方法

问题描述

后端有一个名为 的端点api/Options/GetEmailMessageTemplate,它返回具有此模式的对象:

{
  messageType: string, Enum: [ ConfirmationEmail, 
ConfirmationTransaction, RecoveryPassword, SetupAdminAccount, ConfirmationApiKey, ConfirmationDepositTransaction ]
  language: string, Enum: [ En, Ru, Zh, Es, Et ]
  subject: string,
  template: string,
  isUsed: boolean
}

例如响应:

{
  "messageType": 1,
  "language": "En",
  "subject": "string",
  "template": "string",
  "isUsed": true
}

这是另一个编辑它的端点,它api/Options/Options/UpdateEmailMessageTemplate使用与上面相同的模式使用 json。messageType可能是 Enum 中元素的编号或 Enum 值(例如'ConfirmationEmail'

在前端列出所有数据并能够更改它我想出了这种方法:

  1. 我做了一个严格排序的数组:
messageTypes: [  
 { 
    name: 'Confirmation Email',
    success: false,
 },
...
]

更改此模板是否成功需要成功

  1. messageType从后端获得了一个数字 id,我只是将它用作我的数组中的索引(因此,为了使它工作,我的数组必须以完全相同的方式排序该字段的枚举),以获取该名称的名称messageTypesuccess现场操作

3.api/Options/Options/UpdateEmailMessageTemplate获取messageType当前正在编辑的元素的使用索引(indexOf

虽然这种方法按预期工作,但我不禁认为有更好的方法来处理这个问题。

我想听听是否有更好的做法来处理这个问题

标签: javascriptapienums

解决方案


根据我的理解,您想要一种使用友好的值列表及其 id 的方法。一种方法是创建两个单独classes的 . 这将使您能够将原始响应提供给单个模型,并且您可以添加翻译所需的任何方法id>name或相反。

您可能会更喜欢并使用get/set但我对要求仍然有些模糊。但是,这是我会采取的一种方法:

/**
 * Create a class that knows how to translate it
 * Bonus points: this could be populated via your endpoint
 * that returns your enum list so you don't have to keep
 * updating it if there's a change on the backend
 */
class MessageType {
  constructor(messageType) {
    this.id = messageType;
    const messageTypes = [
      'ConfirmationEmail',
      'ConfirmationTransaction',
      'RecoveryPassword',
      'SetupAdminAccount',
      'ConfirmationApiKey',
      'ConfirmationDepositTransaction'
    ];
    this.name = messageTypes[this.id];
  }
}

/**
 * Create a class / model for your response.
 * This will enable you to add any methods
 * needed for translating things how you need
 * them. For example, you might want a method
 * to convert your model into what the backend
 * expects.
 */
class MessageTemplate {
  constructor(response) {
    this.messageType = new MessageType(response.messageType);
    this.language = response.language;
    this.subject = response.subject;
    this.template = response.template;
    this.isUsed = response.isUsed;
  }
  getJsonPayloadForBackend() {
    const payload = { ...this };
    payload.messageType = payload.messageType.id;
    return payload;
  }
}

// Usage

const template = new MessageTemplate({
  "messageType": 2,
  "language": "En",
  "subject": "string",
  "template": "string",
  "isUsed": true
});

console.log(template);
console.log('data to send to backend', template.getJsonPayloadForBackend())


推荐阅读