Imagine having a scenario where there are mothers and children entities, with the mother holding a foreign key linked to the child's ID. The challenge arises when the API can only retrieve all mothers and children from separate endpoints, resulting in a complete list of mothers and potential children. The question now becomes how to resolve this foreign key on the application side, preferably using a transformer.
There is uncertainty about whether handling it this way is the most efficient approach. A preferred solution would involve avoiding child: Observable<Child>
within the Mother
class, favoring child: Child
instead.
models.ts
/**
* Representing entities fetched from the API
*/
export class ApiMother {
id: number;
child: number;
}
export class ApiChild {
id: number;
firstName: string;
lastName: string;
}
/**
* Entities used in the application
*/
export class Mother {
id: number;
child: Observable<Child>
}
export class Child {
id: number;
name: string;
}
mother.service.ts
export class MotherService extends BaseApiService {
constructor(
private http: HttpClient,
private transformer: MotherTransformerService,
) {
super(auth);
}
/**
* Retrieve a list of mothers.
*
* @return An `Observable` of `Mother` representing the request, with a JSON response body.
*/
public getAll(): Observable<Mother[]> {
return this.http
.get<ApiMother[]>(this.url)
.pipe(map(
obj => this.transformer.fromApiModel(obj))
);
}
}
mother-transformer.service.ts
export class MotherTransformerService {
constructor(
private childService: ChildService
) {
}
/**
* Adapt the `Mother` object to meet application requirements.
*
* @param apiModel: ApiMother
* @return Mother
*/
fromApiModel(apiModel: ApiMother): Mother {
let model = new Mother;
const child: Observable<Child> = this.childService.findOne(apiModel.child);
model = {
id: apiModel.id,
child,
};
return model;
}
}
child.service.ts
export class childService extends BaseApiService {
constructor(
private http: HttpClient,
private transformer: ChildTransformService, // Combines `lastName` and `firstName` into `name`.
) {
super(auth);
}
/**
* Obtain a list of children.
*
* @return An `Observable` of `Child[]` for the request, with a JSON response body.
*/
public getAll(): Observable<Child[]> {
return this.http
.get<ApiChild[]>(this.url, this.options)
.pipe(map(
list => list.map(obj => this.transformer.fromApiModel(obj)))
);
}
/**
* Retrieve a single `Child` based on the specified ID.
*
* @param id: ID of the `Child`
* @return An `Observable` of `Child`
*/
public findOne(id: number): Observable<Child> {
return this.getAll()
.pipe(
filter((child: Child) => child.id === id)[0]
);
}
}
I appreciate any advice or suggestions offered. It's possible that this topic overlaps with another thread, but I couldn't locate a related query.