Post

2023-05-22-TIL

2023-05-22-TIL

Today I Learned

@Transactional REQUIRES_NEW

  • https://woodcock.tistory.com/40

GraphQL Pros & Cons

Pros of GraphQL for Frontend:

  1. Efficient Data Fetching: With GraphQL, frontend developers can specify the exact data requirements they need for a particular view or component. This eliminates over-fetching and under-fetching of data, improving the efficiency of data fetching and reducing network bandwidth.

  2. Reduced API Round-Trips: GraphQL allows frontend developers to retrieve multiple resources in a single request, reducing the number of API round-trips. This reduces latency and improves the overall performance of the application.

  3. Flexible Data Modeling: GraphQL provides flexibility in data modeling by allowing the frontend to define the shape and structure of the data it needs. This means that frontend developers can request nested and related data in a single query without relying on the backend to provide specific endpoints for each use case.

  4. Strong Typing and Introspection: GraphQL schemas provide strong typing, allowing frontend developers to have clear visibility into the available data and its structure. This enables better collaboration between frontend and backend teams, as well as improved tooling and IDE support.

Cons of GraphQL for Frontend:

  1. Increased Complexity: GraphQL introduces a learning curve and additional complexity compared to REST APIs. Frontend developers need to understand GraphQL concepts, schema definitions, and query syntax. Implementing features like pagination, caching, and real-time updates may require additional effort.

  2. Lack of Browser Caching: Since GraphQL queries are typically sent via POST requests, browser caching mechanisms that rely on HTTP GET requests are not directly applicable. Frontend developers need to implement custom caching solutions or rely on libraries/tools to handle caching effectively.

Pros of GraphQL for Backend:

  1. Efficient Data Serving: GraphQL allows backend developers to provide precise data responses based on the frontend’s query requirements. By resolving only the requested fields, backend developers can optimize data fetching, reducing database load and improving response times.

  2. Versioning and Evolution: GraphQL schemas support versioning and allow the backend to introduce changes without breaking existing clients. The ability to deprecate fields and types and provide clear documentation makes it easier to evolve the API over time.

  3. Reduced Over-fetching: Unlike REST APIs, GraphQL eliminates the problem of over-fetching data. Backend developers can optimize their APIs by exposing a single endpoint that serves multiple clients, reducing the amount of unnecessary data being sent over the network.

  4. Developer Experience: GraphQL provides powerful developer tools and libraries that simplify the implementation of APIs. Features like introspection, type checking, and documentation generation make it easier for backend developers to design, test, and maintain their APIs.

Cons of GraphQL for Backend:

  1. Increased Complexity: Implementing a GraphQL server requires additional infrastructure and tooling compared to REST APIs. Backend developers need to define and maintain a GraphQL schema, write resolvers to fetch data from various sources, and handle query validation and execution.

  2. Performance Overhead: GraphQL introduces a runtime layer that dynamically resolves queries. While this provides flexibility and efficiency on the frontend side, it can introduce additional processing overhead on the backend, especially for complex or deeply nested queries. Careful optimization and caching strategies are required to ensure optimal performance.

  3. Caching Challenges: Caching becomes more complex in GraphQL due to the dynamic nature of queries and the lack of standardized caching mechanisms for POST requests. Backend developers need to implement caching strategies explicitly, which may require additional effort and consideration.

Overall, GraphQL offers numerous benefits for both frontend and backend development, but it also introduces some challenges and complexities that developers need to consider when adopting it. Understanding the trade-offs and carefully planning the implementation can help maximize the advantages of GraphQL while mitigating

  • https://www.solo.io/topics/graphql/
  • https://blog.logrocket.com/fetching-dynamically-structured-data-cms-graphql/
  • https://www.divante.com/blog/the-5-most-interesting-cms-with-graphql-api
  • https://hygraph.com/
  • https://blog.logrocket.com/graphql-vs-rest-api-why-you-shouldnt-use-graphql/
  • https://future-seller.dev/posts/apply-and-manage-graphql-server
  • https://graphql.org/learn/serving-over-http/#:~:text=Your%20GraphQL%20HTTP%20server%20should%20handle%20the%20HTTP%20GET%20and%20POST%20methods.
  • https://aws.amazon.com/ko/pm/appsync/?trk=264e136f-31bf-4992-9132-a7b1382bab86&sc_channel=ps&ef_id=CjwKCAjwpayjBhAnEiwA-7ena4-PrtDGsHn6VEkPFh60jqPnNxtkVH9Vfl5GnNGt2XBrZJoYzNsGsBoCC0YQAvD_BwE:G:s&s_kwcid=AL!4422!3!647258118462!e!!g!!graphql!19613644257!145815300659
  • https://www.redhat.com/en/topics/api/what-is-graphql
  • https://www.youtube.com/watch?v=eIQh02xuVw4
  • https://www.youtube.com/watch?v=PTfZcN20fro
  • https://www.youtube.com/watch?v=yWzKJPw_VzM
  • https://tech.kakao.com/2019/08/01/graphql-basic/
  • https://docs.github.com/en/graphql

GraphQL in Practical

  • GraphQL is particularly useful in various cases where it brings significant benefits over traditional REST APIs. Here are some scenarios where GraphQL shines:
  1. Single-page Applications (SPAs): SPAs often require efficient data fetching due to their dynamic nature. With GraphQL, frontend developers can precisely specify the data requirements for each component, avoiding over-fetching and under-fetching. This helps optimize performance and reduces the amount of data transferred over the network.

  2. Mobile Applications: Mobile apps often operate under limited network conditions and have specific data requirements for different screens. GraphQL’s ability to fetch only the required data reduces the payload size and minimizes the number of network requests, making it a suitable choice for mobile app development.

  3. Aggregating Data from Multiple Sources: In situations where data is scattered across multiple services or databases, GraphQL acts as a data aggregation layer. Backend developers can consolidate data from different sources into a single GraphQL API, simplifying the frontend integration and reducing the number of backend requests.

  4. Real-time Data Updates: GraphQL subscriptions enable real-time updates by establishing persistent connections between clients and servers. This is particularly useful for applications that require live data, such as chat applications, collaborative editing tools, or real-time monitoring dashboards.

  5. Rapid Iteration and Prototyping: GraphQL’s flexible nature allows frontend developers to iterate quickly without waiting for backend changes. They can adapt their data requirements on the fly, reducing the dependency on backend modifications and enabling faster prototyping and development cycles.

  6. Large and Complex APIs: In large-scale applications with complex data relationships, GraphQL’s ability to traverse and fetch related data in a single query simplifies the frontend development process. It reduces the need for multiple API calls, improves performance, and enhances the developer experience when working with intricate data structures.

  7. Personalized User Experiences: GraphQL’s query language enables frontend developers to tailor data requests to specific user contexts or preferences. This facilitates the creation of personalized user experiences, where different users receive different sets of data based on their roles, permissions, or preferences.

  8. Microservices Architecture: GraphQL is well-suited for microservices architectures where each service can expose its capabilities through a GraphQL API. Frontend developers can aggregate and compose data from various microservices into a unified view using a single GraphQL endpoint.

It’s important to note that while GraphQL brings advantages in these cases, it might not be the ideal choice for every project. Factors such as the project’s scale, team’s familiarity with GraphQL, and specific performance requirements should be considered when evaluating its suitability for a particular use case.

GraphQL in CMS

GraphQL can be highly beneficial when used with Content Management Systems (CMS). Here are some ways in which GraphQL can enhance CMS implementations:

  1. Flexible Data Fetching: CMS platforms often provide a wide range of content types and fields. With GraphQL, frontend developers can precisely define the data they need for a particular page or component, eliminating the need to retrieve unnecessary data. This granular control over data fetching leads to more efficient and optimized CMS-driven applications.

  2. Improved Performance: GraphQL’s ability to fetch multiple resources in a single request is advantageous for CMS-driven applications, as it reduces the number of API calls and minimizes latency. Frontend developers can retrieve all the required data in a single GraphQL query, resulting in faster rendering and improved performance.

  3. Customization and Personalization: CMS platforms often cater to different user roles and personalized experiences. GraphQL enables frontend developers to request specific data based on user contexts or preferences, allowing for personalized content delivery. This flexibility empowers developers to build dynamic and tailored experiences for end-users.

  4. Simplified API Integration: In a CMS ecosystem, different services and APIs might be involved, such as media management, authentication, or e-commerce. With GraphQL, frontend developers can aggregate and integrate data from multiple APIs into a single GraphQL schema, making it easier to consume and work with data from various sources.

  5. Incremental Content Loading: In CMS-driven applications, loading large amounts of content at once can impact performance. GraphQL’s pagination and cursor-based pagination features allow frontend developers to implement incremental content loading, fetching and rendering content as needed. This helps optimize the user experience, particularly when dealing with large content repositories.

  6. Schema Stitching: CMS platforms often consist of multiple content sources or microservices. GraphQL’s schema stitching capabilities enable backend developers to merge and compose schemas from different CMS services, providing a unified and consistent GraphQL API for frontend consumption. This simplifies the integration of multiple CMS services and facilitates a seamless development experience.

  7. Preview and Draft Content: CMS platforms typically support content authoring workflows, including content previews and drafts. GraphQL can be leveraged to fetch preview or draft content, enabling frontend developers to build custom preview experiences or implement versioning functionality within their applications.

While GraphQL offers several advantages for CMS implementations, it’s important to assess the compatibility and support of GraphQL within the specific CMS platform being used. Some CMS platforms have native GraphQL support or provide GraphQL APIs as extensions, while others might require additional setup or customization to integrate GraphQL effectively.

Add, Delete, Update Row in Grid

If you want to include a field in the API payload to inform the action for adding, deleting, or updating rows, you can modify the example I provided earlier. Here’s an updated version:

Endpoint: PUT /grid/{gridId}/rows

Request Payload:

1
2
3
4
5
6
7
8
9
10
11
12
{
  "rows": [
    { "id": 1, "name": "Row 1", "action": "add" },
    { "id": 2, "name": "Row 2", "action": "add" },
    { "id": 3, "name": "Row 3", "action": "add" },
    { "id": 4, "name": "Updated Row 4", "action": "update" },
    { "id": 5, "name": "Updated Row 5", "action": "update" },
    { "id": 6, "action": "delete" },
    { "id": 7, "action": "delete" },
    { "id": 8, "action": "delete" }
  ]
}

Explanation:

  • The payload now includes a single array called rows, which contains objects representing the rows.
  • Each row object includes properties such as id and name.
  • Additionally, there is a new property called action, which indicates the desired action for each row (add, update, or delete).

On the server-side, you would modify your logic to handle the API call as follows:

  • Identify the grid based on the {gridId} parameter.
  • Iterate over the rows array and perform the corresponding action based on the action property of each row object.
    • For rows with "action": "add", add them to the grid.
    • For rows with "action": "update", locate the corresponding rows in the grid based on the id and update their data.
    • For rows with "action": "delete", remove the rows with the matching IDs from the grid.

Remember to implement proper validation and error handling to ensure the payload is correctly formatted and the actions are performed securely and accurately.

By including the action field, you can explicitly specify the action for each row in the API payload, making it more flexible and allowing for different actions to be performed in a single API call.

  • https://muhimasri.com/blogs/load-add-update-and-delete-table-rows-using-api-services/
This post is licensed under CC BY 4.0 by the author.