PS.
3rd August, 2020
I am switching over from REST API to GraphQL
GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine and is instead backed by your existing code and data.
From the definition provided by medium, GraphQL consist of 2 parts, a schema and a resolvers. When looking at this from first glance, this seems like an awkward script since this is different from REST API as understanding REST API is knowing the fundamental of JavaScript and redirecting correct routes to each endpoints for corresponding GET/POST request.
Comparing both of this, the power that GraphQL provides to us is powerful. GraphQL does more things that REST API can do and to show some of the benefits:
Code snippet to combine multiple schemas and resolvers together without needing to call each individual ones:
const { ApolloServer } = require("apollo-server");
const glue = require("schemaglue");
const { schema, resolver } = glue("src/graphql");
const server = new ApolloServer({
typeDefs: schema,
resolvers: resolver,
playground: {
settings: {
"editor.theme": "light"
}
},
dataSources: () => ({})
});
Code snippet make use of dataSources in resolvers
getUser: (root, args, { dataSources }) => {
return dataSources.currentArray.getUser(args.ID);
};
**Link for source code can be found here
We can break it down simpler by understanding that schemas is just a list of definitions defined beforehand before we implement resolvers which is what the function does and outputs.
Example snippet of a schema
type Query {
users: [Person!]
user(id: Int!): Person
}
type Mutation {
getUpdateUser(id: Int, name: String, age: String): Person
}
type Person {
id: Int
name: String
age: Int
shark: String
}
Example snippet of a resolver
exports.resolver = {
Query: {
users: (root, args, context, info) => {
return users;
},
user: (root, args, context, info) => {
return users.find((e) => e.id === args.id);
}
},
Mutation: {
getUpdateUser: (root, args, context, info) => {
users.map((user) => {
if (user.id === args.id) {
user.name = args.name;
user.age = args.age;
return user;
}
});
}
}
};
So from the following snippets, we can clearly see that if we compare to programming like C, schema is similar to a header file, whereas resolver is a normal function that you build on top of that header file.
Eventhough I have only just touched the surface of GraphQL, I can see it replacing RESTful API in the long run. It might take a while to get use to the GraphQL syntax but it is worth noting that it provides us a much better data request that we need.