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;
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With