
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
With a myriad of HTTP utility methods and middleware at your disposal, creating a robust API is quick and easy.
Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love.
Create a GraphQL HTTP server with HTTP web framework that supports connect styled middleware, including Connect itself, Express
In order to respond to queries, a schema needs to have resolve functions for all fields. Resolve functions cannot be included in the GraphQL schema language, so they must be added separately. This collection of functions is called the “resolver map”.
Every resolver in a GraphQL.js schema accepts four positional arguments:
fieldName(obj, args, context, info) { result }
These arguments have the following meanings and conventional names:
obj: The object that contains the result returned from the resolver on the parent field, or, in the case of a top-level Query field, the rootValue passed from the server configuration. This argument enables the nested nature of GraphQL queries.author(name: "Ada"), the args object would be: { "name": "Ada" }.context: This is an object shared by all resolvers in a particular query, and is used to contain per-request state, including authentication information, dataloader instances, and anything else that should be taken into account when resolving the query.info: This argument should only be used in advanced cases, but it contains information about the execution state of the query, including the field name, path to the field from the root, and more. It’s only documented in the GraphQL.js source code.Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
In simple words, Mongoose acts as an intermediate between mongodb and server side language(like NodeJs)
In this lesson, we will create a new graphql mutation to save record in MongoDB. Mongoose model provides a create method to save new record in MongoDB collection
In this lesson, we will create a new Graphql query to fetch records from MongoDB collection. Mongoose model provides a find method to get all data from MongoDB collection
In this lesson, we will create a new Graphql mutation to update records from MongoDB collection. Mongoose model provides a findOneAndUpdate method to update data from MongoDB collection
In this lesson, we will create a new Graphql mutation to delete records from MongoDB collection. Mongoose model provides a findByIdAndRemove method to delete data from MongoDB collection
GraphQL yoga is a fully-featured GraphQL Server with focus on easy setup, performance & excellent developer experience. It is built on the top of express.js and graphql.js. It also provides a file-upload feature, real-time subscriptions, and typescript typings
As your GraphQL application grows from demo, to proof of concept, to production, the complexity of your schema and resolvers will grow in tandem. To organize your code, you’ll want to split up your schema types and the associated resolvers into multiple files
Protecting your APIs is as critical a component as anything else in your application. We will leverage the document based NoSQL database, MongoDB, to store our user data by creating a user model with mongoose. In this lesson, we will also create a GraphQL Schema for Signup User and Login User.
In this lesson, you’re going to implement signup functionality that allows your users to authenticate against your GraphQL server. We will create a mutation for Signup, the first thing to do is encrypting the User’s password using the bcryptjs library and then generate a JSON web token by using jsonwebtoken library
Up until now, we have been using a shorthand syntax where we omit both the query keyword and the query name, but in production apps it's useful to use these to make our code less ambiguous. You'll need these optional parts to a GraphQL operation if you want to execute something other than a query or pass dynamic variables.We will create a operation for mutation. We have been writing all of our arguments inside the query string. But in most applications, the arguments to fields will be dynamic. We will create a dynamic variables in GraphQL
The Joi npm package handles the input validations. Joi is an Object schema description language and validator for JavaScript objects that does the heavy lifting for validation so you don't have to. You will also learn how to use throw statement to send the error in GraphQL.
In this lesson, we will find the existing User record by the email address that was sent along in the login mutation. If no User with that email address was found, you’re returning a corresponding error.
You’re asking for the id and the password in the selection set. The password is needed because it needs to be compared with the one provided in the login mutation.
The next step is to compare the provided password with the one that is stored in the database. If the two don’t match up, you’re returning an error as well. In the end, you’re returning token and the user again.
GraphQL Yoga needs a single resolver object. We have create a separate resolvers file for Product and Auth. In this lesson, I will show you to merge multiple resolvers object into a single object using lodash merge method.
Lodash is a JavaScript library which provides utility functions for common programming tasks using the functional programming paradigm.
Merge method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object
A Middleware is a schema wrapper which allows you to manage additional functionality across multiple resolvers efficiently. In this lesson, we will create a middleware function for user authentication. If user is authenticated this middleware function will add the `userId` to the context object, otherwise it will return the Authentication error in the response
We will use `graphql-middleware` package. It is the easiest way to handle GraphQL middleware. `graphql-middleware` allows complete control over your resolvers (Before, After). It can also work with any GraphQL Schema. I also show how to use `applyMiddleware` method to apply the middlewares on GraphQL resolvers.
Many times we end-up repeating lots of logic on our resolvers. Access control, for instance, is something that can be done in the resolver level but just tends to end up with repeated code, even when creating services for such a task. Nested resolvers aim to make it easier to build smart resolvers with the logic being reusable and split in small pieces. We will create a nested resolver for custom field product. Whenever you have type with a field that resolves to a `Product` you will get the owner as well
Imagine a website that lists products. Your data might contain thousands of products each with dozens of categories. A typical scenario is then to only display a few products at the same time, allowing the user to seek forwards and backward through the whole list.
GraphQL queries provide an efficient way to fetch data, even across multiple types. This results in a high abstraction layer on top of databases, but sometimes more is needed to satisfy specific data requirements of modern applications. You will learn how to filters nodes by applying one or many matching rules.
In this lesson, you will learn how to orders the set of results in ascending or descending by a field.
Paginating Real-Time Data with Cursor Based Pagination.Pagination is a technique for breaking large record sets into smaller portions called pages. As a developer, you should be familiar with implementing pagination, but implementingpagination for real time data can become tricky even for experienced developers.
One of GraphQL’s major strengths is that it lets you send multiple queries in a single request. However, since the response data is shaped after the structure of the fields being requested, you might run into naming issues when you’re sending multiple queries asking for the same fields.
Fragments are a handy feature to help to improve the structure and reusability of your GraphQL code. A fragment is a collection of fields on a specific type. In GraphQL, you often need to query for the same data fields in different queries. The code to define these fields has to be written multiple times, leading to more errors. By reusing this code, we can be more efficient with our time and reuse these pieces of query logic on different queries.
Also called Enums, enumeration types are a special kind of scalar that is restricted to a particular set of allowed values.
This allows you to:
1. Validate that any arguments of this type are one of the allowed values
2. Communicate through the type system that a field will always be one of a finite set of values
An interface can be used to describe a type in an abstract way. It allows you to specify a set of fields that any concrete type, which implements this interface, needs to have. In many GraphQL schemas, every type is required to have an id field. Using interfaces, this requirement can be expressed by defining an interface with this field and then making sure that all custom types implement it
In this lesson, you will learn how to send query request for interfaces in graphql. I will also show you how to use __resolveType to resolve dynamic type in GraphQL
The Union type indicates that a field can return more than one object type, but doesn’t define specific fields itself. Unions are useful for returning disjoint data types from a single field.Union types are very similar to interfaces, but they don't get to specify any common fields between the types.
Subscriptions are a GraphQL feature that allows a server to send data to its clients when a specific event happens. Subscriptions are usually implemented with WebSockets. In this lesson, you’ll learn how you can bring realtime functionality into your app by implementing GraphQL subscriptions
Subscriptions are a GraphQL feature that allows a server to send data to its clients when a specific event happens. Subscriptions are usually implemented with WebSockets. In this lesson, you’ll learn how you can bring realtime functionality into your app by implementing GraphQL subscriptions
DataLoader is a utility that supports query batching and caching out of the box. These features are enabled by simply defining a “batch function” and instantiating a DataLoader object.
A batch function is simply a function that takes an array of “keys” and returns a Promise which resolves to an array of values. We’ll see a concrete example of this in a bit.
Batching is accomplished in DataLoader by essentially debouncing consecutive calls to the same batch function and executing the defined batch function a single time. Caching is performed within the context of the individual DataLoader instance. As soon as .load() is called on the DataLoader instance, the result is cached, and the same Promise is returned on consecutive calls. Simply put, .load() is a memoized function.
DataLoader is a utility that supports query batching and caching out of the box. These features are enabled by simply defining a “batch function” and instantiating a DataLoader object.
A batch function is simply a function that takes an array of “keys” and returns a Promise which resolves to an array of values. We’ll see a concrete example of this in a bit.
Batching is accomplished in DataLoader by essentially debouncing consecutive calls to the same batch function and executing the defined batch function a single time. Caching is performed within the context of the individual DataLoader instance. As soon as .load() is called on the DataLoader instance, the result is cached, and the same Promise is returned on consecutive calls. Simply put, .load() is a memoized function.
A batch loading function accepts an Array of keys, and returns a Promise which resolves to an Array of values. There are a few constraints that must be upheld:
For example, if your batch function was provided the Array of keys: [ 2, 9, 6, 1 ], and loading from a back-end service returned the values:
{ id: 9, name: 'Chicago' }
{ id: 1, name: 'New York' }
{ id: 2, name: 'San Francisco' }
Our back-end service returned results in a different order than we requested, likely because it was more efficient for it to do so. Also, it omitted a result for key 6, which we can interpret as no value existing for that key.
To uphold the constraints of the batch function, it must return an Array of values the same length as the Array of keys, and re-order them to ensure each index aligns with the original keys [ 2, 9, 6, 1 ]:
[
{ id: 2, name: 'San Francisco' },
{ id: 9, name: 'Chicago' },
null,
{ id: 1, name: 'New York' }
]DataLoader provides a memoization cache for all loads which occur in a single request to your application. After .load() is called once with a given key, the resulting value is cached to eliminate redundant loads.
In addition to relieving pressure on your data storage, caching results per-request also creates fewer objects which may relieve memory pressure on your application:
var userLoader = new DataLoader(...) var promise1A = userLoader.load(1) var promise1B = userLoader.load(1) assert(promise1A === promise1B)
In this lesson, we will do some setup for testing in Nodejs and GraphQL. I will show you how to integrate Jest testing framework in GraphQL.
Integration testing (sometimes called integration and testing, abbreviated I&T) is the phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing. We will write some integration test for our demo application.
In this lesson, will write unit test for GraphQL Mutations and Queries. Jest is a testing framework authored by Facebook. The biggest advantage of using Jest is that it works out of the box with minimal setup or configuration.
The tests are written in BDD style, similar to any other modern testing library. You can literally just put your tests inside of a directory called __tests__ or name them with a .spec.js or .test.js extension, then run jest and it works. That is pretty sweet.
GraphQL is a new API standard that provides a more efficient, robust and flexible alternative to REST. It was developed and open-sourced by Facebook and is now maintained by a large community of companies and individuals from all over the world.
APIs have become ubiquitous components of software infrastructures. In short, an API defines how aclient can load data from a server.
At its core, GraphQL enables declarative data fetching where a client can specify exactly what data it needs from an API. Instead of multiple endpoints that return fixed data structures, a GraphQL server only exposes a single endpoint and responds with precisely the data a client asked for.
How GraphQL is better than REST
1. Increased mobile usage creates need for efficient data loading Increased mobile usage, low-powered devices and sloppy networks were the initial reasons why Facebook developed GraphQL. GraphQL minimizes the amount of data that needs to be transferred over the network and thus majorly improves applications operating under these conditions.
2. Variety of different frontend frameworks and platforms The heterogeneous landscape of frontend frameworks and platforms that run client applications makes it difficult to build and maintain one API that would fit the requirements of all. With GraphQL, each client can access precisely the data it needs.
3. Fast development & expectation for rapid feature development Continuous deployment has become a standard for many companies, rapid iterations and frequent product updates are indispensable. With REST APIs, the way data is exposed by the server often needs to be modified to account for specific requirements and design changes on the client-side. This hinders fast development practices and product iterations.
What you will learn?
This course will cover these following topics