簡體   English   中英

為資源設計 API 端點,需要為不同的頁面返回不同的 forms 數據

[英]Design API endpoint for resource that needs to return different forms of data for different pages

我正在使用 prisma 與 db、嵌套關系等進行通信。

我有多個頁面請求的資源。 每個頁面都需要來自資源的不同數據集,因此每個頁面都會發送不同的查詢參數。 簡化的例子是:一頁需要價格和名稱,另一頁需要價格、名稱和收藏。

示例查詢將是

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
  } } : {}),
});

但是隨着我添加使用該資源的新頁面,添加越來越多的過濾器和/或select s,查詢變得更加復雜,如果不使用select s,頁面最終會請求接收不必要的數據。

感覺相當復雜,好像有辦法讓它變得更好,比如將端點拆分為多個或從前端發送整個Prisma.ProductFindManyArgs

如何降低復雜性並提高可重用性?

我建議您使用 GraphQL API,它允許客戶端准確指定它想要接收的字段,從而允許進行更細粒度的查詢。 使用 GraphQL API 還可以提供更大的靈活性和自定義,還可以通過減少端點的數量來簡化后端代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM