Home > Back-end >  React - How to write API mapper?
React - How to write API mapper?

Time:11-07

I'm studying about React and TypeScript. And apologize for my poor English...

I'm trying to make web service, and need to make API key mapper in my React project(with TypeScript). At first, my server is written with python, so key name convention is snake_case. But I'm using TypeScript, so I want to write mapper for JSON without any modules or class.

I write mapper like this:

// 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;
}

But, when I have to use API result object, I need to write this:

// in React components

const text = result[Mapper.HELLO_WORLD]

I think this is pretty ugly code.. and is there any better way for API mapper?

CodePudding user response:

You can create a sanitize function to convert raw_API_Response to your expectedAPIResponse like that:

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'
}));
  • Related