GraphQL
Graplql is a restful API query language, open source by Facebook, and today we will take a look at it.
Endless learning, who let me CAI ah? !
The idea is to make a demo with the following features
- The book list
- Book Details
- The new book
- Delete the book
To start
First, set up the back-end service, using NodeJS + Express, database selection MLab, is a free online database service, for the purpose of learning, fast and convenient.
First of all, let’s set up the basic service. The API here can be found on the official website without explanation.
const graphqlHTTP = require('express-graphql'); // Define data template and query logic, see below const schema = require('./schema/schema'); App.use (// Specify the URL suffix corresponding to the API'/graphql',
graphqlHTTP({
schema,
graphiql: true})); app.listen(4000, () => { console.log('now listen on port 4000');
});
Copy the code
When learning GraphQL, I compared it to Mongoose. Mongoose uses a new Schema as a template to perform database operations. Graphql uses the object GraphQLObjectType to generate a template, and the specific code is as follows:
const BookType = new GraphQLObjectType({
name: 'Book',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
genre: { type: GraphQLString },
author: {
type: AuthorType,
resolve(parent, args) {
returnAuthor.findById(parent.authorId); }}})});Copy the code
Here we’ve generated a book object
Fields can be of type object or ()=>object Corresponds to the query field, the book has
Id primary key, name name, genre type, author author fieldCopy the code
The type of the field specifies the type of the field, which is similar to typescript but is introduced by GraphQL. GraphQLID means that the ID could be a string or a number, so using ID here will take both arguments and convert them to string automatically. eg:
Suppose id is a string in the database, which is"233666"And the incoming is 233666, we hope we can also find it can be used"GraphQLID"Will automatically convert to"233666"
Copy the code
Graphql supports nested queries, and it’s obvious that an author can have a lot of content, such as names and published books, so the type of author corresponds to the author object (see below). Resolve can return a value, a promise, an array of promises, That is, the return value of the database operation.
What is AuthorType?
An object of author is then generated, similar to a book
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
age: { type: GraphQLInt },
books: {
type: new GraphQLList(BookType),
resolve(parent, args) {
// return _.filter(books, { authorId: parent.id });
returnBook.find({ authorId: parent.id }); }}})});Copy the code
An author can have multiple books, so the books field needs to return a list GraphQLList, which defines a BookType list as type, and resolve as type.
Now that we have the book and author object, we’re going to build the template, and according to the official API, we’re going to define it this way
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLID}}, resolve(parent, args) {// get data from a database or other source //Mongodb mysql postgresqlreturn Book.findById(args.id);
}
},
author: {
type: AuthorType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return Author.findById(args.id);
}
},
books: {
type: new GraphQLList(BookType),
resolve(parent, args) {
return Book.find({});
}
},
authors: {
type: new GraphQLList(AuthorType),
resolve(parent, args) {
returnAuthor.find({}); }}}}); module.exports = new GraphQLSchema({ query: RootQuery, });Copy the code
This is the schema that was imported at the beginning, and there are four query methods defined here
- Query book by ID
- Query author by id
- Query book list
- Query author list
Now we put the project startup (here highly recommend nodemon this library, can avoid modifying code every time to restart), and then visit http://localhost:4000/graphql there will be a magical child
No, no, this is it.
Now let’s enter some queries as prompted by the gray text
{books{name ID}} // Then click the upper left run buttonCopy the code
The query was successful, but the data was written to the database manually, so the production environment can not be killed? In the next section, we’ll learn how to delete data using GraphQL new modifications.
All the code has been posted on Github, please give it a thumbs up if you like it.