首页 > 解决方案 > React - 如何编写 API 映射器?

问题描述

我正在研究 React 和 TypeScript。并为我糟糕的英语道歉...

我正在尝试制作 Web 服务,并且需要在我的 React 项目(使用 TypeScript)中制作 API 密钥映射器。起初,我的服务器是用 python 编写的,所以键名约定是snake_case. 但是我使用的是 TypeScript,所以我想为 JSON 编写映射器,而不需要任何模块或类。

我这样写映射器:

// api result: { "hello_world": "hello world!" }

const Mapper = {
  HELLO_WORLD: 'hello_world', // snake_case because server is written with python
} as const;

interface APIResult {
  [Mapper.HELLO_WORLD]: string;
}

但是,当我必须使用 API 结果对象时,我需要这样写:

// in React components

const text = result[Mapper.HELLO_WORLD]

我认为这是非常丑陋的代码.. API 映射器有没有更好的方法?

标签: reactjstypescript

解决方案


您可以创建一个清理函数来将 raw_API_Response 转换为您的 expectedAPIResponse ,如下所示:

interface RawResponse {
  hello_world: string;
  another_world: number;
  snack_case_to_camel_case: string;
}

interface expectedResponse {
  helloWorld: string;
  anotherWorld: number;
  snackCaseToCamelCase: string;
}


function sanitizeResponse(raw: RawResponse) : expectedResponse {
  const result: expectedResponse = {
    helloWorld: raw.hello_world,
    anotherWorld: raw.another_world,
    snackCaseToCamelCase: raw.snack_case_to_camel_case,
  };
  return result;
}

console.log(sanitizeResponse({
  hello_world: 'string',
  another_world: 100,
  snack_case_to_camel_case: 'another string'
}));

推荐阅读