javascript - 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'
)
在前端列出所有数据并能够更改它我想出了这种方法:
- 我做了一个严格排序的数组:
messageTypes: [
{
name: 'Confirmation Email',
success: false,
},
...
]
更改此模板是否成功需要成功
- 我
messageType
从后端获得了一个数字 id,我只是将它用作我的数组中的索引(因此,为了使它工作,我的数组必须以完全相同的方式排序该字段的枚举),以获取该名称的名称messageType
和success
现场操作
3.api/Options/Options/UpdateEmailMessageTemplate
获取messageType
当前正在编辑的元素的使用索引(indexOf
)
虽然这种方法按预期工作,但我不禁认为有更好的方法来处理这个问题。
我想听听是否有更好的做法来处理这个问题
解决方案
根据我的理解,您想要一种使用友好的值列表及其 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())
推荐阅读
- raspberry-pi - 如何在树莓派上找到 USB 调制解调器的 tty?
- python - 训练时出现 OOM 错误,但验证时没有
- flutter - 如何使用 Providers 或 Riverpod 在 Flutter 中构建状态管理?
- php - Stripe Webhook 测试抛出...测试 webhook 错误:500
- angular - Angular SEO 如何正确实现动态标题和元数据?
- variables - 使用Stata基于二进制变量创建时间变量
- elasticsearch - StormCrawler 不解析 Tika 元数据
- reactjs - 使用 TypeScript 在 React 中的 monaco-editor -> 找不到模块 'monaco-editor'
- c# - 从 C# 流中读取所有字节
- laravel - laravel:更新或创建(更新插入)数据透视表