[英]Design API endpoint for resource that needs to return different forms of data for different pages
I'm using prisma to communicate with db, with nested relations and all.我正在使用 prisma 与 db、嵌套关系等进行通信。
I have a resource that is requested by multiple pages.我有多个页面请求的资源。 Each page needs different set of data from the resource so each page sends different query params.
每个页面都需要来自资源的不同数据集,因此每个页面都会发送不同的查询参数。 Simplified exmaple would be: one page needs price and name, the other page needs price, name and collection.
简化的例子是:一页需要价格和名称,另一页需要价格、名称和收藏。
Example query would be示例查询将是
prisma.product.findMany({
where: {
...(collectionName ? { collection: {
is: {
collectionName,
},
} } : {}),
...(productName ? { productName } : {}),
},
...(select ? { // checking if its array and mapping it is omitted for the example
select: {
[select]: true, // no way to select fields from relation
} } : {}),
});
But the query becomes more complex as I add new pages that use the resource, adding more and more filters and/or select
s, and pages end up requesting-receiving unnecessary data if not using select
s.但是随着我添加使用该资源的新页面,添加越来越多的过滤器和/或
select
s,查询变得更加复杂,如果不使用select
s,页面最终会请求接收不必要的数据。
It feels rather complex and like there's a way to make it better, like splitting endpoints into multiple or sending the whole Prisma.ProductFindManyArgs
from the frontend.感觉相当复杂,好像有办法让它变得更好,比如将端点拆分为多个或从前端发送整个
Prisma.ProductFindManyArgs
。
How can I reduce complexity and increase reusability?如何降低复杂性并提高可重用性?
I would recommend you to use a GraphQL API, which allows for more fine-grained queries by allowing the client to specify exactly what fields it wants to receive.我建议您使用 GraphQL API,它允许客户端准确指定它想要接收的字段,从而允许进行更细粒度的查询。 Using a GraphQL API would also allow for more flexibility and customization and may also simplify the backend code by reducing the number of endpoints.
使用 GraphQL API 还可以提供更大的灵活性和自定义,还可以通过减少端点的数量来简化后端代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.