0

I want to return API response JSON into a model class.

Sample code is as follows:

const authenticateUserAsync = async  (username: string, password: string) : Promise<UserModel> => {

const loginData = {
     "Username": username,
     "Password": password
}

const api = axios.create({
    baseURL: "https://www.something.com/api/services"
})

const resp = await api.post("/ValidateUserPost", loginData)

if(resp.data != null && resp.data.userId != null && resp.data.userId > 0){    
    
    //How to convert the JSON Response to Model Class
    return resp.data.map((user: UserModel) => {UserId: user.userId, FirstName: user.FirstName })

} 
else
    return NULL User Model
};

The model class which I want to return looks as below:

export interface UserModel {
    UserId: Number;
    CustomerId: number;
    FirstName:string;
    LastName:string;
}
Ashish Tripathi
  • 580
  • 4
  • 18

1 Answers1

0

I've figured out how to set the API Response data into my model classes.

The sample code is as below

const authenticateUserAsync = async  (username: string, password: string) : Promise<UserModel> => {

    const loginData = {
        "Username": username,
        "Password": password
    }

    const api = axios.create({ baseURL: "https://www.something.com/api/services"})

    const resp = await api.post("/ValidateUserPost", loginData)

    //Check if the data is not null. API response could be obtained into .data property. And, the data needs to be set into model class properties
    if(resp.data != null && resp.data.userId != null && resp.data.userId > 0){        
        return {
            UserId: resp.data.userId , 
            FirstName: resp.data.firstName, 
            LastName: resp.data.lastName, 
            CustomerId: resp.data.customerId }
        } else return null
    }
}

Hope you should find it useful.

Thanks!

Ashish Tripathi
  • 580
  • 4
  • 18