kukeiko / entity-space

MIT License
5 stars 1 forks source link

hydrate relations across multiple API calls #145

Closed kukeiko closed 2 years ago

kukeiko commented 2 years ago

What

ability to hydrate relations of entities that have not been provided by an API call by using another, subsequent API call.

Why

so the manual work of making multiple API calls and aggregating the data does not have to be done by the user.

Example

using those two models:

export interface Product {
    id: number;
    name: string;
    brandId: number;
    brand?: Brand;
}

export interface Brand {
    id: number;
    name: string;
}

we have an API that returns us products, but it can not include the brands in the same response. entity-space should then collect the brandIds and issue a new query against the Brand API, then assign the result to the products.

feature has to work recursively; so if the Brand model now also has reviews:

export interface Brand {
    id: number;
    name: string;
    reviews?: BrandReview[];
}

export interface BrandReview {
    id: number;
    brandId: number;
    brand?: Brand;
    review: string;
}

and the Brand API can't include the reviews in the same response, we make yet another API call to fetch the reviews and assign them to the brands to finally get this:

const product: Product[] = [
    {
        id: 1,
        name: "A nice Shirt",
        brandId: 7,
        brand: {
            id: 7,
            name: "Nice Shirts Inc.",
            reviews: [
                {
                    id: 42,
                    brandId: 7,
                    review: "They really do make nice shirts!",
                },
            ],
        },
    },
    ...
];
kukeiko commented 2 years ago

implemented via PR #146 and showcased in the products example.