简体   繁体   中英

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.

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.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM