'Where to put HttpClient request and response converter functions
In our angular application we are converting every api request and response types to our app specific type so it is easier to implement a property change in a big application.
At the moment we are doing that directly in the Service with a map on the HttpClient observable. But this is a little bit cumbersome, especially for requests that return the same entity (e.g. get and post both returning an entity).
@Injectable()
export class TodoService {
constructor(private httpClient: HttpClient) {
}
public getTodos(): Observable<Todo[]> {
return this.httpClient.get<any>('/path/to/todos').pipe(
map((res: any) => res.map((item) => ({
id: res.id,
name: res.specialProperty
})))
);
}
public getTodoById(id: string): Observable<Todo> {
return this.httpClient.get<any>('/path/to/todos/' + id).pipe(
map((res: any) => ({
id: res.id,
name: res.specialProperty
}))
);
}
}
Now I have found a cool article describing the Implementation of an adapter to keep your code more DRY. See. https://florimond.dev/en/posts/2018/09/consuming-apis-in-angular-the-model-adapter-pattern/
My Problem with that approach is that for a big backend service we have to create a lot of AdapterClasses, where maybe a module with a couple of exported functions would do the trick.
Now my question: Do you have any experience with adapting requests and responses in an Angular Application on a large scale and where do you keep your "mapping" functions?
Solution 1:[1]
I assume you could have a bunch of model classes, and theoreticaly you can then map response to a class, depending on your custom logic.
as an example you could have classes like these:
export class Model1 {
static type = 'model1';
id: number;
name: string;
...;
}
response from backend example:
{
size: 1,
itemType: 'model1',
items: [{name: 'abc', id: 1}]
}
and interceptor logic which will map items to corresponding models
mapResponse(response: MyTypicalResponce) {
const model = allModels.find(({type}) => type == response.itemType);
return {
...response,
items: model ? response.items.map(item => new Model(item)) : response.items;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrei |
