Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Request and response models in Angular?

Tags:

angular

I wonder what is the right way to handle request and response model in Angular. Should we always create 2 different model for get and post operations, or can keywords like partial fix our problem?

Lets say I want to create user and API asks me those fields:

name: string;
username: string;
canRead: boolean;
roleId: string;

But when we get user we have also some additional fields. How to handle the difference between those models

Lets say the model when we get user:

name: string; 
username: string;
canRead: boolean;
roleName: string;
roleId: string;
like image 617
Orhan Özkerçin Avatar asked Jul 10 '26 01:07

Orhan Özkerçin


1 Answers

You can have something like this:

api-name.model.ts

interface ApiNameRequest {
    name: string;
    username: string;
    canRead: boolean;
    roleId: string;
}

type ApiNameResponse = ApiNameRequest & {
    roleName: string;
}

If the two types differ too much (and one of them doesn't include the second one) then make two types.
You'll have a clean code and you'll know that roleName comes only on the response, as a comparison with making one type and having roleName? and wondering when will it be available and when it will not.

L.E. Let's suppose your models are:
request <-> name, username, canRead, roleId, userId
response <-> name, username, canRead, roleId, roleName

OPTION 1: Merge the types

interface ApiNameModel {
    name: string;
    username: string;
    canRead: boolean;
    roleId: string;
    userId?: string; // <- optional, just in Request
    roleName?: string; // <- optional, just in Response
}

Now let's say we make the API call:

makeApiCall(url, request: ApiNameModel) {
    code_to_call_the_api
}
...
const request: ApiNameModel = { 
    name: 'a', 
    username: 'a', 
    canRead: true, 
    roleId: 'a'
};

makeApiCall(url, request); // <- you can do this but API will say
                          // you miss userId, so you will get network error

OPTION 2: Make different types

interface ApiNameRequest {
    name: string;
    username: string;
    canRead: boolean;
    roleId: string;
    userId: string;
}

interface ApiNameResponse {
    name: string;
    username: string;
    canRead: boolean;
    roleId: string;
    roleName: string;
}

Now let's say we make the API call:

makeApiCall(url, request: ApiNameRequest) {
    code_to_call_the_api
}
...
const request: ApiNameRequest = { 
    name: 'a', 
    username: 'a', 
    canRead: true, 
    roleId: 'a'
}; // <- you get compile error here saying you miss userId

makeApiCall(url, request); // <- you can't get here until you fix typescript
                          // errors (the build will fail at compile)
like image 91
Damian-Teodor Beleș Avatar answered Jul 17 '26 20:07

Damian-Teodor Beleș