Tutorial: Building a GraphQL API in PHPAndrew Rota
This document discusses building a GraphQL API in PHP. It provides an overview of GraphQL concepts like queries, fields, types and schemas. It then outlines the steps to build a GraphQL API in PHP using the graphql-php library:
1. Define object types and the Query root type in the schema
2. Initialize the GraphQL schema instance
3. Execute GraphQL queries against the schema and return the result
By following these steps, one can build an API for querying a database of PHP conferences and speakers to understand how to build GraphQL APIs in PHP.
Performant APIs with GraphQL and PHP (Dutch PHP 2019)Andrew Rota
This document summarizes an presentation about building performant APIs with GraphQL and PHP. The presentation introduces GraphQL concepts like queries, fields, arguments, variables, types and schemas. It discusses how GraphQL can help address challenges with traditional REST APIs like over-fetching or under-fetching data. The document also provides an overview of building a GraphQL server in PHP using the webonyx/graphql-php library and implementing resolvers to fetch data and return object types.
Integrating React.js Into a PHP Application: Dutch PHP 2019Andrew Rota
This document discusses integrating React.js into a PHP application. It provides an overview of React.js and its benefits for building user interfaces. It then covers different approaches to server-side rendering (SSR) with React in a PHP application, including using the V8Js PHP extension to run JavaScript, making requests from PHP to a Node.js service, and making requests from Node.js to PHP. It emphasizes that React.js and PHP can complement each other and discusses frameworks like Next.js that support SSR. The key takeaways are that React.js can enhance PHP applications, there are different SSR architectures to integrate them, and giving React.js a try can help modernize app views.
GraphQL is a syntax that describes how to ask for data, and is generally used to load data from a server to a client. GraphQL has three main characteristics:
It lets the client specify exactly what data it needs.
It makes it easier to aggregate data from multiple sources.
It uses a type system to describe data.
Introducing Arc: A Common Intermediate Language for Unified Batch and Stream...Flink Forward
Today's end-to-end data pipelines need to combine many diverse workloads such as machine learning, relational operations, stream dataflows, tensor transformations, and graphs. For each of these workload types exist several frontends (e.g., DataFrames/SQL, Beam, Keras) based on different programming languages as well as different runtimes (e.g., Spark, Flink, Tensorflow) that target a particular frontend and possibly a hardware architecture (e.g., GPUs). Putting all the pieces of a data pipeline together simply leads to excessive data materialisation, type conversions and hardware utilisation as well as miss-matches of processing guarantees.
Our research group at RISE and KTH in Sweden has founded Arc, an intermediate language that bridges the gap between any frontend and a dataflow runtime (e.g., Flink) through a set of fundamental building blocks for expressing data pipelines. Arc incorporates Flink and Beam-inspired stream semantics such as windows, state and out of order processing as well as concepts found in batch computation models. With Arc, we can cross- compile and optimise diverse tasks written in any programming language into a unified dataflow program. Arc programs can run on various hardware backends efficiently as well as allowing seamless, distributed execution on dataflow runtimes. To that end, we showcase Arcon a concept runtime built in Rust that can execute Arc programs natively as well as presenting a minimal set of extensions to make Flink an Arc-ready runtime.
Rapid Web API development with Kotlin and KtorTrayan Iliev
Introduction to Kotlin and Ktor with flow, async and channel examples. Ktor is an async web framework with minimal ceremony that leverages the advantages of Kotlin like coroutines and extensible functional DSLs..
Fast federated SQL with Apache CalciteChris Baynes
This document discusses Apache Calcite, an open source framework for federated SQL queries. It provides an introduction to Calcite and its components. It then evaluates Calcite's performance on single data sources through benchmarks. Lastly, it proposes a hybrid approach to enable efficient federated queries using Calcite and Spark.
How web works and browser works ? (behind the scenes)Vibhor Grover
how web and browser works, this presentation can help you in understanding what happens when you enter a URL in your browser and how the page is displayed by the browser, and how we can improve the performance of our applications.
The document discusses various topics related to reactive and functional programming including NGRX, RxJS, Redux, Reactive Streams specification, and computing derived data using Reselect. It provides code examples for setting up an NGRX application with state management, effects, selectors, and composing the root reducer. It also discusses hot and cold streams, converting cold streams to hot, and the anatomy of RxJS operators.
In this presentation, Suraj Kumar Paul of Valuebound has walked us through GraphQL. Founded by Facebook in 2012, GraphQL is a data query language that provides an alternative to REST and web service architectures.
Here he has discussed core ideas of GraphQL, limitations of RESTful APIs, operations, arguments, fragmentation, variables, mutations etc.
----------------------------------------------------------
Get Socialistic
Our website: http://valuebound.com/
LinkedIn: http://bit.ly/2eKgdux
Facebook: https://www.facebook.com/valuebound/
Writing code that writes code - Nguyen LuongVu Huy
“The Pragmatic Programmer” admonished us all to “write code that writes code”: use code generators to increase productivity and avoid duplication. The language communities have clearly caught on, as more and more frameworks generate code at compile time: Project Lombok, Google Auto, and more.
This session reviews these approaches including examples of how and why we’d want to do this.
We will see newest Java language tools, write our own AST tranform and look at some amazing libraries based on these techniques.
Bio: Nguyen Luong is a senior java technical lead at Ekino Vietnam. He likes to research new technologies and solve security challenges.
How to build an ETL pipeline with Apache Beam on Google Cloud DataflowLucas Arruda
This document provides an overview of building an ETL pipeline with Apache Beam on Google Cloud Dataflow. It introduces key Beam concepts like PCollections, PTransforms, and windowing. It explains how Beam can be used for both batch and streaming ETL workflows on bounded and unbounded data. The document also discusses how Cloud Dataflow is a fully managed Apache Beam runner that integrates with other Google Cloud services and provides reliable, auto-scaled processing. Sample architecture diagrams demonstrate how Cloud Dataflow fits into data analytics platforms.
SVR17: Data-Intensive Computing on Windows HPC Server with the ...butest
This document discusses using the DryadLINQ framework to perform data-intensive computing on Windows HPC Server. DryadLINQ allows developers to write LINQ queries over distributed datasets using a declarative programming model. It automatically parallelizes queries by generating execution plans that leverage both intra-node parallelism using PLINQ and inter-node parallelism using the Dryad distributed execution engine. DryadLINQ integrates with .NET and provides type safety while handling serialization, distribution, and failure recovery of queries across large clustered datasets.
Overview of GraphQL
How it is different from REST
When you should consider using it and when you should not
Incremental demos until calling GraphQL from an React application: https://github.com/bary822/graphQL-techtalk
This document discusses different data access technologies in .NET, including LINQ, the ADO.NET Entity Framework, and ADO.NET Data Services. It introduces LINQ as a way to query objects using SQL-like syntax. It describes how LINQ can be used with datasets, entity models, and other data stores. The Entity Framework is introduced as providing LINQ support along with a richer object model and query capabilities. ADO.NET Data Services exposes data through a RESTful API for web and mobile clients.
This document introduces GraphQL, describing what it is and isn't. It explains that GraphQL is not a query language like SQL, but rather specifies fields that can be resolved through code. The document provides examples of GraphQL schemas, queries, and mutations. It also discusses GraphQL integration with various technologies like Relay and Java libraries. Finally, it demonstrates GraphQL tooling like GraphiQL and an example DX integration.
It is a basic presentation which can help you understand the basic concepts about Graphql and how it can be used to resolve the frontend integration of projects and help in reducing the data fetching time
This presentation also explains the core features of Graphql and why It is a great alternative for REST APIs along with the procedure with which we can integrate it into our projects
1) The document discusses how GraphQL provides more power and flexibility to API clients compared to REST by allowing clients to specify exactly what fields they need in a query and receive all the requested data in a single response.
2) With GraphQL, the client can decide which fields to include for an object like a product, and the server returns only the requested data rather than an entire predefined object structure.
3) GraphQL also supports features like schema introspection, which allows clients to discover what fields are available, and makes API evolution easier by allowing fields to be added without breaking existing queries.
Применение паттерна Page Object для автоматизации веб сервисовCOMAQA.BY
Доклад о том, как еще можно организовать автоматизацию тестирования веб-сервисов, а именно, приспособить подход/шаблон Page Object (казалось бы, причем тут он?). Главное достоинство подхода - его максимальная простота и дружелюбность. Мы рассмотрим живой и успешно работающий на реальном проекте фреймворк, построенный подобным образом, разберём на слои, обсудим плюсы, минусы и саму идею подхода в целом.
GraphQL is an application layer query language from Facebook. With GraphQL, you can define your backend as a well-defined graph-based schema. Then client applications can query your dataset as they are needed. GraphQL’s power comes from a simple idea — instead of defining the structure of responses on the server, the flexibility is given to the client. Will GraphQL do to REST what REST did to SOAP?
This document provides a brief overview of Java 8 features including functional interfaces, lambda expressions, stream API, and Optional class. It discusses how functional interfaces provide target types for lambda expressions and can have a single abstract method. Lambda expressions allow implementing functional interfaces concisely without anonymous classes. The stream API provides a powerful way to process collections in a declarative way using lambda expressions. The Optional class avoids null pointer exceptions and allows chaining of method calls on objects that may be null.
Making Machine Learning Easy with H2O and WebFluxTrayan Iliev
Machine learning is becoming a must for many business domains and applications. H2O is a best-of-breed, open source, distributed machine learning library written in Java. The presentation shows how to create and train machine learning models easily using H2O Flow web interface, including Deep Learning Neural Networks (DNNs). The session provides a tutorial how to develop and deploy fullstack-reactive face recognition demo using React + RxJS WebSocket front-end, OpenCV, Caffe CNN for image segmentation, OpenFace CNN for feature extraction, H20 Flow for face recognition interactive model training and export as POJO. The trained POJO model is incorporated in a real-time streaming web service implemented using Spring 5 Web Flux and Spring Boot. All demo is 100% Java!
Modularity and Domain Driven Design; a killer Combination? - Tom de Wolf & St...NLJUG
The document discusses the benefits of combining modularity through domain-driven design and bounded contexts with database migration using Liquibase. This allows independent migration of database schemas for each domain module. It also addresses challenges around cross-domain transactions, search, and migration of multiple module versions. Overall, the approach aims to make systems more resilient to change by containing the impact within loosely coupled domain modules.
Building GraphQL Servers with Node.JS & PrismaNikolas Burk
This document discusses building GraphQL servers with Node.js and Prisma. It introduces GraphQL and its benefits like querying exact data needs. It also outlines the three parts of a GraphQL server: the schema, resolver functions, and network layer. It then provides an example of building a clone of the Medium API from scratch in steps, starting with a minimal GraphQL server and adding database integration with Prisma and completing the API operations. The document encourages following along with the code examples provided in the GitHub repository. It also mentions Prisma is hiring.
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionVMware Tanzu
This document discusses Geode GraphQL Extension (G2QL), which allows a Geode cache to be accessed via GraphQL queries and mutations. G2QL introspects a Geode cache configuration and generates a corresponding GraphQL schema. It converts GraphQL queries and mutations to Geode region operations and OQL, eliminating the need to write resolvers. G2QL addresses issues like schema duplication, boilerplate code, and inefficient data access through features like schema generation, automatic conversion of queries to Geode operations, and batching of queries. The document provides an example of G2QL in action and discusses next steps for the project.
GraphQL is a query language for APIs that allows clients to request specific data rather than entire resources. It addresses common problems with REST APIs like over-fetching data. Several GraphQL libraries exist for Java including graphql-java, graphql-java-kickstart, graphql-dgs-framework, and spring-graphql. These libraries differ in features like code generation, error handling, testing support, and available clients. Spring GraphQL is considered the most mature option as it integrates directly with Spring Boot and allows testing all code.
How web works and browser works ? (behind the scenes)Vibhor Grover
how web and browser works, this presentation can help you in understanding what happens when you enter a URL in your browser and how the page is displayed by the browser, and how we can improve the performance of our applications.
The document discusses various topics related to reactive and functional programming including NGRX, RxJS, Redux, Reactive Streams specification, and computing derived data using Reselect. It provides code examples for setting up an NGRX application with state management, effects, selectors, and composing the root reducer. It also discusses hot and cold streams, converting cold streams to hot, and the anatomy of RxJS operators.
In this presentation, Suraj Kumar Paul of Valuebound has walked us through GraphQL. Founded by Facebook in 2012, GraphQL is a data query language that provides an alternative to REST and web service architectures.
Here he has discussed core ideas of GraphQL, limitations of RESTful APIs, operations, arguments, fragmentation, variables, mutations etc.
----------------------------------------------------------
Get Socialistic
Our website: http://valuebound.com/
LinkedIn: http://bit.ly/2eKgdux
Facebook: https://www.facebook.com/valuebound/
Writing code that writes code - Nguyen LuongVu Huy
“The Pragmatic Programmer” admonished us all to “write code that writes code”: use code generators to increase productivity and avoid duplication. The language communities have clearly caught on, as more and more frameworks generate code at compile time: Project Lombok, Google Auto, and more.
This session reviews these approaches including examples of how and why we’d want to do this.
We will see newest Java language tools, write our own AST tranform and look at some amazing libraries based on these techniques.
Bio: Nguyen Luong is a senior java technical lead at Ekino Vietnam. He likes to research new technologies and solve security challenges.
How to build an ETL pipeline with Apache Beam on Google Cloud DataflowLucas Arruda
This document provides an overview of building an ETL pipeline with Apache Beam on Google Cloud Dataflow. It introduces key Beam concepts like PCollections, PTransforms, and windowing. It explains how Beam can be used for both batch and streaming ETL workflows on bounded and unbounded data. The document also discusses how Cloud Dataflow is a fully managed Apache Beam runner that integrates with other Google Cloud services and provides reliable, auto-scaled processing. Sample architecture diagrams demonstrate how Cloud Dataflow fits into data analytics platforms.
SVR17: Data-Intensive Computing on Windows HPC Server with the ...butest
This document discusses using the DryadLINQ framework to perform data-intensive computing on Windows HPC Server. DryadLINQ allows developers to write LINQ queries over distributed datasets using a declarative programming model. It automatically parallelizes queries by generating execution plans that leverage both intra-node parallelism using PLINQ and inter-node parallelism using the Dryad distributed execution engine. DryadLINQ integrates with .NET and provides type safety while handling serialization, distribution, and failure recovery of queries across large clustered datasets.
Overview of GraphQL
How it is different from REST
When you should consider using it and when you should not
Incremental demos until calling GraphQL from an React application: https://github.com/bary822/graphQL-techtalk
This document discusses different data access technologies in .NET, including LINQ, the ADO.NET Entity Framework, and ADO.NET Data Services. It introduces LINQ as a way to query objects using SQL-like syntax. It describes how LINQ can be used with datasets, entity models, and other data stores. The Entity Framework is introduced as providing LINQ support along with a richer object model and query capabilities. ADO.NET Data Services exposes data through a RESTful API for web and mobile clients.
This document introduces GraphQL, describing what it is and isn't. It explains that GraphQL is not a query language like SQL, but rather specifies fields that can be resolved through code. The document provides examples of GraphQL schemas, queries, and mutations. It also discusses GraphQL integration with various technologies like Relay and Java libraries. Finally, it demonstrates GraphQL tooling like GraphiQL and an example DX integration.
It is a basic presentation which can help you understand the basic concepts about Graphql and how it can be used to resolve the frontend integration of projects and help in reducing the data fetching time
This presentation also explains the core features of Graphql and why It is a great alternative for REST APIs along with the procedure with which we can integrate it into our projects
1) The document discusses how GraphQL provides more power and flexibility to API clients compared to REST by allowing clients to specify exactly what fields they need in a query and receive all the requested data in a single response.
2) With GraphQL, the client can decide which fields to include for an object like a product, and the server returns only the requested data rather than an entire predefined object structure.
3) GraphQL also supports features like schema introspection, which allows clients to discover what fields are available, and makes API evolution easier by allowing fields to be added without breaking existing queries.
Применение паттерна Page Object для автоматизации веб сервисовCOMAQA.BY
Доклад о том, как еще можно организовать автоматизацию тестирования веб-сервисов, а именно, приспособить подход/шаблон Page Object (казалось бы, причем тут он?). Главное достоинство подхода - его максимальная простота и дружелюбность. Мы рассмотрим живой и успешно работающий на реальном проекте фреймворк, построенный подобным образом, разберём на слои, обсудим плюсы, минусы и саму идею подхода в целом.
GraphQL is an application layer query language from Facebook. With GraphQL, you can define your backend as a well-defined graph-based schema. Then client applications can query your dataset as they are needed. GraphQL’s power comes from a simple idea — instead of defining the structure of responses on the server, the flexibility is given to the client. Will GraphQL do to REST what REST did to SOAP?
This document provides a brief overview of Java 8 features including functional interfaces, lambda expressions, stream API, and Optional class. It discusses how functional interfaces provide target types for lambda expressions and can have a single abstract method. Lambda expressions allow implementing functional interfaces concisely without anonymous classes. The stream API provides a powerful way to process collections in a declarative way using lambda expressions. The Optional class avoids null pointer exceptions and allows chaining of method calls on objects that may be null.
Making Machine Learning Easy with H2O and WebFluxTrayan Iliev
Machine learning is becoming a must for many business domains and applications. H2O is a best-of-breed, open source, distributed machine learning library written in Java. The presentation shows how to create and train machine learning models easily using H2O Flow web interface, including Deep Learning Neural Networks (DNNs). The session provides a tutorial how to develop and deploy fullstack-reactive face recognition demo using React + RxJS WebSocket front-end, OpenCV, Caffe CNN for image segmentation, OpenFace CNN for feature extraction, H20 Flow for face recognition interactive model training and export as POJO. The trained POJO model is incorporated in a real-time streaming web service implemented using Spring 5 Web Flux and Spring Boot. All demo is 100% Java!
Modularity and Domain Driven Design; a killer Combination? - Tom de Wolf & St...NLJUG
The document discusses the benefits of combining modularity through domain-driven design and bounded contexts with database migration using Liquibase. This allows independent migration of database schemas for each domain module. It also addresses challenges around cross-domain transactions, search, and migration of multiple module versions. Overall, the approach aims to make systems more resilient to change by containing the impact within loosely coupled domain modules.
Building GraphQL Servers with Node.JS & PrismaNikolas Burk
This document discusses building GraphQL servers with Node.js and Prisma. It introduces GraphQL and its benefits like querying exact data needs. It also outlines the three parts of a GraphQL server: the schema, resolver functions, and network layer. It then provides an example of building a clone of the Medium API from scratch in steps, starting with a minimal GraphQL server and adding database integration with Prisma and completing the API operations. The document encourages following along with the code examples provided in the GitHub repository. It also mentions Prisma is hiring.
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionVMware Tanzu
This document discusses Geode GraphQL Extension (G2QL), which allows a Geode cache to be accessed via GraphQL queries and mutations. G2QL introspects a Geode cache configuration and generates a corresponding GraphQL schema. It converts GraphQL queries and mutations to Geode region operations and OQL, eliminating the need to write resolvers. G2QL addresses issues like schema duplication, boilerplate code, and inefficient data access through features like schema generation, automatic conversion of queries to Geode operations, and batching of queries. The document provides an example of G2QL in action and discusses next steps for the project.
GraphQL is a query language for APIs that allows clients to request specific data rather than entire resources. It addresses common problems with REST APIs like over-fetching data. Several GraphQL libraries exist for Java including graphql-java, graphql-java-kickstart, graphql-dgs-framework, and spring-graphql. These libraries differ in features like code generation, error handling, testing support, and available clients. Spring GraphQL is considered the most mature option as it integrates directly with Spring Boot and allows testing all code.
APIdays Helsinki 2019 - GraphQL API Management with Amit P. Acharya, IBMapidays
GraphQL API management provides essential capabilities for protecting backend systems and enabling differentiated API plans. Key aspects of GraphQL API management include analyzing query complexity to prevent overwhelming backends, enforcing rate limits and access controls, and offering API plans differentiated by query limits and pricing. This allows GraphQL APIs to balance data access for consumers with protection of backend systems.
GraphQL and its schema as a universal layer for database accessConnected Data World
GraphQL is a query language mostly used to streamline access to REST APIs. It is seeing tremendous growth and adoption, in organizations like Airbnb, Coursera, Docker, GitHub, Twitter, Uber, and Facebook, where it was invented.
As REST APIs are proliferating, the promise of accessing them all through a single query language and hub, which is what GraphQL and GraphQL server implementations bring, is alluring.
A significant recent addition to GraphQL was SDL, its schema definition language. SDL enables developers to define a schema governing interaction with the back-end that GraphQL servers can then implement and enforce.
Prisma is a productized version of the data layer leveraging GraphQL to access any database. Prisma works with MySQL, Postgres, and MongoDB, and is adding to this list.
Prisma sees the GraphQL community really coming together around the idea of schema-first development, and wants to use GraphQL SDL as the foundation for all interfaces between systems.
GraphQL is a query language for APIs that was created by Facebook in 2012. It allows clients to define the structure of the data required, and exactly the data they need from the server. This prevents over- and under-fetching of data. GraphQL has grown in popularity with the release of tools like Apollo and GraphQL code generation. GraphQL can be used to build APIs that integrate with existing backend systems and databases, with libraries like Express GraphQL and GraphQL Yoga making it simple to create GraphQL servers.
Code-first GraphQL Server Development with PrismaNikolas Burk
This document discusses code-first and SDL-first approaches to building GraphQL schemas and servers. It defines the terminology and compares the two approaches. Code-first involves programmatically defining types and resolvers, while SDL-first uses a string-based schema definition language. Both have tradeoffs like inconsistencies or lack of tooling for SDL-first, and lack of documentation for code-first. Prisma is introduced as a tool that can generate a GraphQL schema from a database using either approach. The document concludes with a demonstration of building a GraphQL server and schema with Prisma and Nexus using a code-first approach.
GraphQL is query language for APIs, but what are the advantages and how would one implement such in their microservices/APIs. In this session, I will go through the basics of GraphQL, different aspects of GraphQL and architecture of such APIs. How 4 different ways we can implement GraphQL for a Springboot microservice/API.
This document discusses building a GraphQL API in PHP. It introduces GraphQL concepts like queries, fields, arguments, types and schemas. It covers implementing GraphQL on both the client and server side. On the client, queries are made to request data from a GraphQL server. On the server, the schema defines query structure and resolver functions return data. Tools like introspection, GraphiQL and Voyager enable exploration and debugging of GraphQL APIs.
Implementing OpenAPI and GraphQL services with gRPCTim Burks
Behind every API there's code. REST and GraphQL are powerful interface abstractions but are not so great for writing code (we’re still looking for the programming language where every command is a GET, POST, PUT, or DELETE). When programmers work, they are usually making function calls, and an RPC framework like gRPC allows those functions to be written in a mixture of languages and distributed among many servers. This means that gRPC can be a great way to implement REST and GraphQL APIs at scale. We’ll share open source projects from Google that can be used to implement OpenAPI and GraphQL services with gRPC and give you hands-on experience with both.
Presented at the 2019 API Specifications Conference.
https://asc2019.sched.com/event/T6u9/workshop-implementing-openapi-and-graphql-services-with-grpc-tim-burks-google
Slides from presentation, I've made on the BuildStuff LT 2018. Here I'm talking about issues, many people have found when using RESTful APIs and how GraphQL addresses them. Also I'm trying to cover the tradeoffs made by the standard, solutions proposed by different implementations and some ideas for the future.
This document provides a list of React code samples and tutorials for intermediate React developers. It includes 10 React code samples that use tools like GraphQL, Flux, and Redux. It also provides step-by-step instructions for setting up sample projects that combine React with Node, D3, GraphQL, SQLite, and Angular 2. Additionally, the document defines key concepts like Flux, Redux, Relay and GraphQL and compares REST APIs to GraphQL.
MongoDB.local Berlin: Building a GraphQL API with MongoDB, Prisma and TypescriptMongoDB
This document discusses building GraphQL APIs with MongoDB, Prisma and TypeScript. It begins with introductions to GraphQL and understanding GraphQL servers, including defining schemas and resolver functions. It then covers using Prisma as an ORM for MongoDB to provide type-safe database access and simplify workflows like migrations and queries. Finally, it promotes GraphQL Yoga as a framework that combines Prisma and GraphQL for building modern backends with full type-safety and deep database integration.
Your API on Steroids - Retrofitting GraphQL by Code, Cloud Native or ServerlessQAware GmbH
OOP 2023, Online, Februar 2023, Sonja Wegner (Lead Software Architect @QAware) & Stefan Schmöller (Senior Software Engineer @QAware).
== Dokument bitte herunterladen, falls unscharf! Please download slides if blurred! ==
With GraphQL a modern and flexible way of providing APIs for our data is emerging.
The clients specify which data they need, the provisioning of data becomes more flexible and dynamic. Over-fetching or under-fetching are history.
But does this mean we have to rewrite all APIs to benefit? How can we retrofit a GraphQL API onto our existing API landscape?
In this talk we explore three different alternatives:
- The Developer Way: Writing a GraphQL API layer by hand
- The Cloud-native Way: Using lightweight API gateways such as Gloo or Tyk
- The Serverless Way: Using Cloud Provider native services
We will look at all three approaches conceptually and justify when and why each makes sense. Additionally, we will show in a live demo how GraphQL APIs can be added to an existing REST API.
GraphQL - when REST API is not enough - lessons learnedMarcinStachniuk
This document discusses lessons learned from implementing GraphQL APIs. It begins by describing some limitations of REST APIs, such as requiring multiple roundtrips to fetch nested data. GraphQL is introduced as an alternative that allows clients to specify exactly what data they need in a single request. The document then covers various GraphQL concepts like queries, mutations, and type systems. It also discusses best practices like using a schema-first approach, pagination support, and the DataLoader library to solve the N+1 problem. Testing GraphQL APIs and integrating with Relay are also briefly outlined. The overall message is that GraphQL is a good alternative to REST when clients have complex data needs.
SETCON'18 - Ilya labacheuski - GraphQL adventuresNadzeya Pus
GraphQL adventures. Вводный курс молодого бойца по созданию GraphQL прокси сервера с использованием typescript. Опыт миграции legacy API services на GraphQL и сложности, возникающие при этом.
Distributed Queries in IDS: New features.Keshav Murthy
Learn about the latest function relating to distributed queries that was delivered in IBM Informix® Dynamic Server (IDS) 11 and 11.5. This talk will provide an overview of distributed queries, then will jump into a deep dive on the latest functions and how you can benefit from implementing distributed queries in your solutions.
Grails is an open-source framework that enables high-velocity development of Spring applications. It uses conventions over configuration, integrates best-of-breed Java technologies like Spring and Hibernate, and provides a full-stack framework with object-relational mapping, web controllers, and view rendering. Grails aims to increase developer productivity through sensible defaults and simplified APIs.
In tube drawing process, a tube is pulled out through a die and a plug to reduce its diameter and thickness as per the requirement. Dimensional accuracy of cold drawn tubes plays a vital role in the further quality of end products and controlling rejection in manufacturing processes of these end products. Springback phenomenon is the elastic strain recovery after removal of forming loads, causes geometrical inaccuracies in drawn tubes. Further, this leads to difficulty in achieving close dimensional tolerances. In the present work springback of EN 8 D tube material is studied for various cold drawing parameters. The process parameters in this work include die semi-angle, land width and drawing speed. The experimentation is done using Taguchi’s L36 orthogonal array, and then optimization is done in data analysis software Minitab 17. The results of ANOVA shows that 15 degrees die semi-angle,5 mm land width and 6 m/min drawing speed yields least springback. Furthermore, optimization algorithms named Particle Swarm Optimization (PSO), Simulated Annealing (SA) and Genetic Algorithm (GA) are applied which shows that 15 degrees die semi-angle, 10 mm land width and 8 m/min drawing speed results in minimal springback with almost 10.5 % improvement. Finally, the results of experimentation are validated with Finite Element Analysis technique using ANSYS.
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
Sorting Order and Stability in Sorting.
Concept of Internal and External Sorting.
Bubble Sort,
Insertion Sort,
Selection Sort,
Quick Sort and
Merge Sort,
Radix Sort, and
Shell Sort,
External Sorting, Time complexity analysis of Sorting Algorithms.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
This paper proposes a shoulder inverse kinematics (IK) technique. Shoulder complex is comprised of the sternum, clavicle, ribs, scapula, humerus, and four joints.
ELectronics Boards & Product Testing_Shiju.pdfShiju Jacob
This presentation provides a high level insight about DFT analysis and test coverage calculation, finalizing test strategy, and types of tests at different levels of the product.
☁️ GDG Cloud Munich: Build With AI Workshop - Introduction to Vertex AI! ☁️
Join us for an exciting #BuildWithAi workshop on the 28th of April, 2025 at the Google Office in Munich!
Dive into the world of AI with our "Introduction to Vertex AI" session, presented by Google Cloud expert Randy Gupta.
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
Passenger car unit (PCU) of a vehicle type depends on vehicular characteristics, stream characteristics, roadway characteristics, environmental factors, climate conditions and control conditions. Keeping in view various factors affecting PCU, a model was developed taking a volume to capacity ratio and percentage share of particular vehicle type as independent parameters. A microscopic traffic simulation model VISSIM has been used in present study for generating traffic flow data which some time very difficult to obtain from field survey. A comparison study was carried out with the purpose of verifying when the adaptive neuro-fuzzy inference system (ANFIS), artificial neural network (ANN) and multiple linear regression (MLR) models are appropriate for prediction of PCUs of different vehicle types. From the results observed that ANFIS model estimates were closer to the corresponding simulated PCU values compared to MLR and ANN models. It is concluded that the ANFIS model showed greater potential in predicting PCUs from v/c ratio and proportional share for all type of vehicles whereas MLR and ANN models did not perform well.
Analysis of reinforced concrete deep beam is based on simplified approximate method due to the complexity of the exact analysis. The complexity is due to a number of parameters affecting its response. To evaluate some of this parameters, finite element study of the structural behavior of the reinforced self-compacting concrete deep beam was carried out using Abaqus finite element modeling tool. The model was validated against experimental data from the literature. The parametric effects of varied concrete compressive strength, vertical web reinforcement ratio and horizontal web reinforcement ratio on the beam were tested on eight (8) different specimens under four points loads. The results of the validation work showed good agreement with the experimental studies. The parametric study revealed that the concrete compressive strength most significantly influenced the specimens’ response with the average of 41.1% and 49 % increment in the diagonal cracking and ultimate load respectively due to doubling of concrete compressive strength. Although the increase in horizontal web reinforcement ratio from 0.31 % to 0.63 % lead to average of 6.24 % increment on the diagonal cracking load, it does not influence the ultimate strength and the load-deflection response of the beams. Similar variation in vertical web reinforcement ratio leads to an average of 2.4 % and 15 % increment in cracking and ultimate load respectively with no appreciable effect on the load-deflection response.
7. Intro7
… and even more Monster with 333 tables
Magento: Commerce Solutions for Selling Online (333 tables)Hi-Res: http://anna.voelkl.at/wp-content/uploads/2016/12/ce2.1.3.png
Order table
(138 fields)
12. GraphQL Basics12
GraphQL – is a …
query
language
for APIs
query
executor
on Schema
for Frontenders for Backenders
+
NodeJS
C#
.NET
Go
Python
Ruby
etc…
17. GraphQL Basics17
Function with fetch logic from any data source
Type
Args
Resolve
Scalar or Object Type which returns resolve
Set of input args for resolve function
Description
DeprecationReason
Documentation
Field hiding
Type
Field 1
Field N
Field Config
20. GraphQL Basics20
Invoice Customer
id
name
id
customerId
amount
Type Type
Field
Field
Field
Field
Field
customer
invoices Field
date Field
select * from customer where
id = {invoice.customerId}
select * from invoice where
customer_id = {customer.id}
Field Resolve
Resolve
Customer
Array<Invoice>
Relation is a new field in your Type
21. GraphQL Basics21
Invoice Customer
id
name
id
customerId
amount
Type Type
Field
Field
Field
Field
Field
invoices Field
date Field
select * from invoice where
customer_id = {customer.id}
limit {args.limit}
Resolve
Args
Limit: 3
— Limit? Offset? Sort? Additional filtering?
— No problem, add them to args and process in resolve function!
Array<Invoice>
22. GraphQL Basics22
function
// fetch data logic (from any mix of DBs)
// access logic (check permissions)
ANY PRIVATE BUSINESS LOGIC…
// processing logic (operations, calcs)
source, args, context, info( ) {
}
return data;
Resolve function
23. GraphQL Basics23
ResolveJust remove
and you get PUBLIC schema
functions
printSchema(schema); // txt output (SDL format)
graphql(schema, introspectionQuery); // json output (AST)
(private business logic)
Schema Introspection
24. GraphQL Basics24
• types
• fields
• args
• docs
• resolve
• directives
• input types
• enums
• interfaces
• unions
type Customer {
id: Int
name: String
# List of Invoices for current Customer
invoices(limit: Int): [Invoice]
}
# Show me the money
type Invoice {
id: Int
customerId: Int
amount: Decimal
# Customer data for current Invoice
customer: Customer
oldField: Int @deprecated(reason: "will be removed")
}
SDL format
(txt)
Schema Introspection example
25. GraphQL Basics25
an ability for awesome tooling:
GraphiQL — graphical interactive in-browser GraphQL IDE
Eslint-plugin-graphql — check queries in your editor, CI
Relay-compiler — generates type definitions from queries
• Autocompletion
• Query validation
• Documentation
• Visualization
• TypeDefs generation for static analysis (Flow, TypeScript)
Schema Introspection provides
30. 30
REST API
GraphQL
Fetch sub-fetch 1
sub-fetch 2
sub-fetch N
Network
Delay
Network
Delay
RESULT
Query Network
Delay
RESULT
- Sub-fetch logic on client side (increase bundle size)
+ Sub-fetch logic implemented on server side
+ No additional network round-trip (speed)
- Over-fetching (redundant data transfer/parsing)
+ Exactly requested fields (speed)
31. Intro31
A copy from one of the previous slides…
Client-server apps
SERVER CLIENTS
NodeJS
C#
.NET Go
Java Python
Ruby etc…
Browsers
iOS
Android
etc…
MySQL
MongoDB
ES
PostgreSQL
Redis
etc…
HTTP
WS
HTML
REST
XML
JSON
etc…
URL
url-encoded
form-data
etc…
32. 32
GraphQL – is a query language for APIs
NodeJS
C#
.NET Go
Java
PythonRuby etc…
Browsers iOS
Androidetc…
MySQL
MongoDB
ES
PostgreSQL
Redis
etc…
HTTP
WS
etc…
SERVER
CLIENTS
Specification for describing
the capabilities and requirements
of data models
for client‐server apps
SCHEMA
INTROSPECTION
Pretty QUERY
Language
34. Static Analysis34
PRODUCTIVITY
• Holy refactoring
Static type checks 🚀
• Functions call checks
• Types checks
• Auto-suggestion
Static program analysis is the analysis of computer software that is performed without actually executing programs
35. Static Analysis35
Let’s turbo-charge
our client apps static analysis
with GraphQL queries
SERVER JS CLIENT
File with
GraphQL Query
and Response processing
GraphQL
Schema
36. Static Analysis36
SERVER JS CLIENT
File with
GraphQL Query
and Response processing
Schema
Introspection
GraphQL
Schema
1
38. Static Analysis38
Hey, you have a wrong Query
SERVER JS CLIENT
File with
GraphQL Query
and Response processing
Schema
Introspection
GraphQL
Schema
Watcher
File with
Response Type Defs
1
2 3
39. Static Analysis39
SERVER JS CLIENT
File with
GraphQL Query
and Response processing
Schema
Introspection
GraphQL
Schema
Watcher
File with
Response Type Defs
1
2 3
4
40. Static Analysis
SERVER JS CLIENT
File with
GraphQL Query
and Response processing
Schema
Introspection
GraphQL
Schema
Watcher Flowtype
File with
Response Type Defs
1
2 3
4
5
40
or TypeScript
41. Static Analysis41
SERVER JS CLIENT
File with
GraphQL Query
and Response processing
Schema
Introspection
GraphQL
Schema
Watcher Flowtype
File with
Response Type Defs
1
2 3
4
5
Houston, we have a Type Check problem
at line 19287 col 5: possible undefined value
6
52. GraphQL Query Problems52
Denial of Service attacks
• pre-approve queries that
the server can execute
(persisted queries by unique ID)
query HugeResponse {
user {
friends(limit: 1000) {
friends(limit: 1000) {
friends(limit: 1000) {
...
}
}
}
}
}
aka Resource exhaustion attaks
• cost analysis on the query
using by Facebook
Solutions:
• avoid nesting relations
53. GraphQL Query Problems53
query NestedQueryN1 {
{
productList {
id
categoryId
category {
id
name
}
}
}
}
N+1 query problem
1 query for
ProductList
N queries
for fetching every
Category by id
Solution: DataLoader
const CatLoader = new DataLoader(
ids => Category.findByIds(ids)
);
CatLoader.load(1);
CatLoader.load(2);
CatLoader.load(1);
CatLoader.load(4);
will do just one BATCH request
on next tick to the Database
55. Problem #1: too much copy/paste55
const QueryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
films: ...,
persons: ...,
planets: ...,
species: ...,
starships: ...,
vehicles: ...,
}),
});
6 fields and
every FieldConfig
consists from
almost identical
12 ctrl+c/ctrl+v lines
Query Type example
https://swapi.co
The Star Wars API
56. Problem #1: too much copy/paste56
films: {
type: new GraphQLList(FilmType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: async (source, args) => {
const data = await loadData(`https://swapi.co/api/films/`);
if (args && args.limit > 0) {
return data.slice(0, args.limit);
}
return data;
},
FieldConfig example for films field
57. Problem #1: too much copy/paste
{
films: {
type: new GraphQLList(FilmType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: async (source, args) => {
const data = await loadData(`https://swapi.co/api/films/`);
if (args && args.limit > 0) {
return data.slice(0, args.limit);
}
return data;
},
},
planets: {
type: new GraphQLList(PlanetType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: async (source, args) => {
const data = await loadData(`https://swapi.co/api/planets/`);
if (args && args.limit > 0) {
return data.slice(0, args.limit);
}
return data;
},
},
}
57
differs
only by url
Comparison of two FieldConfigs
58. Problem #1: too much copy/paste58
function createListResolve(url) {
return async (source, args) => {
const data = await loadData(url);
if (args && args.limit > 0) {
return data.slice(0, args.limit);
}
return data;
};
}
Solution 1: you may generate your resolve functions
create a function
which returns a resolve function
59. Problem #1: too much copy/paste
films: {
type: new GraphQLList(FilmType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: createListResolve(`https://swapi.co/api/films/`),
},
planets: {
type: new GraphQLList(PlanetType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: createListResolve(`https://swapi.co/api/planets/`),
},
{
films: {
type: new GraphQLList(FilmType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: async (source, args) => {
const data = await loadData(`https://swapi.co/api/films/`);
if (args && args.limit > 0) {
return data.slice(0, args.limit);
}
return data;
},
},
planets: {
type: new GraphQLList(PlanetType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: async (source, args) => {
const data = await loadData(`https://swapi.co/api/planets/`);
if (args && args.limit > 0) {
return data.slice(0, args.limit);
}
return data;
},
},
}
59
Solution 1: you may generate your resolve functions
reduce N times 7 LoC to 1 LoC
60. Problem #1: too much copy/paste
films: {
type: new GraphQLList(FilmType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: createListResolve(`https://swapi.co/api/films/`),
},
planets: {
type: new GraphQLList(PlanetType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: createListResolve(`https://swapi.co/api/planets/`),
},
60
Solution 2: you may generate your FieldConfigs
differs only by `Type` and `url`
61. Problem #1: too much copy/paste61
function createFieldConfigForList(type, url) {
return {
type: new GraphQLList(type),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: createListResolve(url),
};
}
Solution 2: you may generate your FieldConfigs
create a function
which returns a FieldConfig
62. Problem #1: too much copy/paste62
films: {
type: new GraphQLList(PlanetType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: createListResolve(`https://swapi.co/api/films/`),
},
planets: {
type: new GraphQLList(FilmType),
args: { limit: { type: GraphQLInt, defaultValue: 5 } },
resolve: createListResolve(`https://swapi.co/api/planets/`),
},
{
films: createFieldConfigForList(FilmType, `https://swapi.co/api/films/`),
planets: createFieldConfigForList(PlanetType, `https://swapi.co/api/planets/`),
}
10 LoC reduced to 2 LoC
Solution 2: you may generate your FieldConfigs
63. Problem #1: too much copy/paste63
DRY principle
(don't repeat yourself)
was
reduced
in 3 times
90 LoC
30 LoC
Solution 1: you may generate your resolve functions
Solution 2: you may generate your FieldConfigs
64. Problem #2: keep GraphQL types in sync with ORM/DB64
With time you may:
• add new fields
• change field types
• remove fields
• rename fields
Model: User Type: User
SYNC
How to keep to Schemas in SYNC?
65. Problem #2: keep GraphQL types in sync with ORM/DB65
GENERATE
• via some cli/script
• on server boot load (better)
Solution: generate GraphQL types from ORM models
SSOT principle
(single source of truth)
Model: User Type: User
66. Problem #3: mess in types and resolve functions66
InvoiceType.js CustomerType.js
id
name
id
customerId
amount
customer
invoices
date
select * from CUSTOMER
where …
select * from INVOICE
where …
Resolve
Resolve
InvoiceType.js contains CUSTOMER query
CustomerType.js contains INVOICE query
67. Problem #3: mess in types and resolve functions67
select * from INVOICES where …
CustomerType.js
id
name
invoices
transactions
tickets
events
likes
messages
…
select * from TRANSACTIONS where …
select * from TICKETS where …
select * from EVENTS where …
select * from LIKES where …
select * from MESSAGES where …
select * from …
CustomerType.js knows too much
about queries of others types
68. Problem #3: mess in types and resolve functions68
AdminNoteType.js
id
msg
Customer
Product
Invoice
…
Resolve
Resolve
Resolve
Resolve
What if you need to restrict access for some group of users?
Modify resolvers in all places?
69. Problem #3: mess in types and resolve functions69
Solution: GraphQL Models*
* “GraphQL Model” is not a part of GraphQL specification.
It’s suggested additional layer of abstraction for more
comfortable way to construct and maintain your schema
and relations into it.
70. Problem #3: mess in types and resolve functions
class CustomerGQLModel {
type: CustomerGraphQLType;
resolvers: {
findById: {
type: CustomerGraphQLType,
args: { id: 'Int!' },
resolve: (_, args) =>
load(`select * from customer where id = ${args.id}`),
},
findMany: { ... },
createOne: { ... },
updateOne: { ... },
removeOne: { ... },
...
};
inputType: CustomerGraphQLInputType;
}
70
1. type definition
Contains:
2. all possible
ways to CRUD
data
3. may have other
helper methods
and data
Type
MAP<FieldConfig>
InputType
1
2
3
Solution: GraphQL Models
71. Problem #4: import { makeExecutableSchema } from ‘graphql-tools';
Writing Types via SDL and providing resolvers separately.
71
const schema = makeExecutableSchema({ typeDefs, resolvers });
const typeDefs = `
type Query {
customer(id: Int!): Customer
invoices(limit: Int): [Invoice]
}
type Customer {
id: Int!
firstName: String
invoices: [Invoice]
}`;
It’s nice developer experience for small to medium sized schema BUT…
const resolvers = {
Query: {
customer: (_, { id }) =>
Customer.find({ id: id }),
invoices: (_, { limit }) =>
Invoice.findMany({ limit }),
},
Customer: {
invoices: (source) =>
Invoice.find({ customerId: source.id }),
},
};
type args resolve
72. Problem #4: import { makeExecutableSchema } from ‘graphql-tools';72
• If one InputType used in several resolvers, then the
complexity of refactoring increases dramatically.
Hard to work with complex input args
type Query {
invoices(filter: FilterInput): [Invoice]
}
input FilterInput {
num: Int
dateRange: DateRangeInput
status: InvoiceStatusEnum
}
input DateRangeInput {
min: Date
max: Date
}
enum InvoiceStatusEnum {
unpaid paid declined
}
invoices: (_, { filter }) => {
const { num, dateRange, status } = filter;
const q = {};
if (num) q.num = num;
if (dateRange)
q['date.$inRange'] = dateRange;
if (status) q.status = status;
return Post.findMany(q);
},
• If one InputType per resolver, then too much
copy/paste almost similar types.
All highlighted parts with red lines should be in sync
* This example contains an error in the code, try to find it ;)
73. Problem #4: import { makeExecutableSchema } from ‘graphql-tools';
Solution: build the schema programmatically
Generate FieldConfigs via your custom functions (Resolvers) …
73
class InvoiceGQLModel {
findManyResolver(configOptions) {
return {
type: InvoiceType,
args: {
filter: { type: new GraphQLInputObjectType({ … })},
},
resolve: (_, args) => Invoice.findMany(args),
}
}
findByIdResolver() { … }
… … and then …
type
args
resolve
74. Problem #4: import { makeExecutableSchema } from ‘graphql-tools';74
import { GraphQLSchema, GraphQLObjectType } from 'graphql';
import InvoiceResolvers from './InvoiceResolvers';
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
invoices: InvoiceResolvers.findManyResolver(),
...
},
}),
});
http://graphql.org/graphql-js/constructing-types/
Solution: build the schema programmatically
…and then build your Schema from fields and your Resolvers
75. Problem #4: import { makeExecutableSchema } from ‘graphql-tools';75
type Query {
invoices(filter: FilterInput): [Invoice]
}
invoices: (_, { filter }) => { … }
{
type: new GraphQLList(Invoice),
args: {
filter: { type: new GraphQLInputObjectType({ … })},
},
resolve: (_, { filter }) => { … },
}
combine code from different places
back to FieldConfig
type args resolve
type
args
resolve
76. Problem #4: import { makeExecutableSchema } from ‘graphql-tools';76
type Query {
invoices(filter: FilterInput): [Invoice]
}
invoices: (_, { filter }) => { … }
{
type: [Invoice],
args: {
filter: `input FilterInput { … }`,
},
resolve: (_, { filter }) => { … },
}
my code with
graphql-compose
combine code from different places
back to FieldConfig
78. graphql-compose packages78
Graphql-compose-*
The main idea is to generate GraphQL Schema
from your ORM/Mappings at the server startup
with a small lines of code as possible.
— OSS packages family
for generating GraphQL Types
MIT License
Exposes Flowtype/Typescript declarations
With awful docs all packages have more than 460 starts on GitHub
Help wanted
93. 93
Take away!
GraphQL is powerful query language
with great tools
GraphQL is typed so it helps with
static analysis on clients
Generate GraphQL Schemas on server