How to design typescript model for response?

Viewed 1686

How do I design my model in typescript where I got below response?

{
    "data":[
            {
                "name": "XYZ",
                "id": "1"
            },
            {
                "name" :"Abc",
                "id": "2"
            }
        ]
}

what I tried :

export class responseModel<T>{
    data:T;
}

export class model{
    name:string;
    id: number;
}

What is your recommendation? all data will come as part of { data: THE_DATA_OBJECT }

{
    data: []
}

getInfo(): Observable<responseModel<model[]>> {
    // API HTTP Call
}
3 Answers

data should have type model[] and whole response type is responseModel

export class responseModel{
   data:model[];
}
export class model{
  name:string;
  id: number;
}

getInfo(): Observable<responseModel> {
// API HTTP Call
}

I think this is a subjective question so I'll share my experiences when I was having a similar situation.

All of the backend endpoints for my project responses with { data: THE_DATA_OBJECT }. I think it's a bit redundant to design all of my response models starts with a "data" prefix, so instead of doing that, I basically unwrap the "data" prefix in my api service.

Something like the following:

genericHttpCall<T>(path: string, method: string, params: any}: Observable<T> {
  return this.httpClient.request().pipe(map(response => response.data));
}

So basically that saves me from doing class responseModel<T> so that I can focus on design the real model freely instead of let backend affect my model structure.

Also, I always use interface instead of class for response model because they are plain data model that involves no constructor or methods. Unless you want to make the model works for your business logic.

Related