<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: The Javascript Ninja</title>
    <description>The latest articles on DEV Community by The Javascript Ninja (@thejavascriptninja).</description>
    <link>https://dev.to/thejavascriptninja</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F539274%2F234ac1ad-d33a-4ce2-861f-4c9edf55c645.png</url>
      <title>DEV Community: The Javascript Ninja</title>
      <link>https://dev.to/thejavascriptninja</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/thejavascriptninja"/>
    <language>en</language>
    <item>
      <title>The Ultimate Beginner’s Guide to GraphQL: Part 2 – Organization, Parameters, more Queries, and Mutations</title>
      <dc:creator>The Javascript Ninja</dc:creator>
      <pubDate>Sun, 20 Dec 2020 01:49:03 +0000</pubDate>
      <link>https://dev.to/thejavascriptninja/the-ultimate-beginner-s-guide-to-graphql-part-2-organization-parameters-more-queries-and-mutations-42fi</link>
      <guid>https://dev.to/thejavascriptninja/the-ultimate-beginner-s-guide-to-graphql-part-2-organization-parameters-more-queries-and-mutations-42fi</guid>
      <description>&lt;p&gt;Hi everyone! Welcome back to part 2 of &lt;strong&gt;The Ultimate Beginner’s Guide to GraphQL&lt;/strong&gt; tutorial series. Before we start, if you haven’t seen &lt;a href="https://thejavascriptninja.com/the-ultimate-beginners-guide-to-graphql/" rel="noopener noreferrer"&gt;part 1&lt;/a&gt;, you might want to check it out &lt;a href="https://thejavascriptninja.com/the-ultimate-beginners-guide-to-graphql/" rel="noopener noreferrer"&gt;here&lt;/a&gt;. This tutorial will build off the concepts learned in &lt;a href="https://thejavascriptninja.com/the-ultimate-beginners-guide-to-graphql/" rel="noopener noreferrer"&gt;part 1&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;With all that said, I wanted to go more in-depth about something I only briefly mentioned in part 1: the GraphQL infrastructure. This is an important part of learning how GraphQL works, and what makes it so awesome.&lt;/p&gt;

&lt;h1&gt;
  
  
  The GraphQL Infrastructure
&lt;/h1&gt;

&lt;p&gt;To get a better understanding of the advantages and disadvantages of GraphQL, I created this handy little infographic:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi0.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2Fgql-page-001-copy-scaled.jpg%3Fresize%3D768%252C1920%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi0.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2Fgql-page-001-copy-scaled.jpg%3Fresize%3D768%252C1920%26ssl%3D1" alt="graphql_infographic"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Alright! Hopefully that gives you a little insight into the inner workings of GraphQL, and helps you understand some of the operations at a deeper level.&lt;/p&gt;

&lt;h1&gt;
  
  
  Organizing the Code
&lt;/h1&gt;

&lt;p&gt;Unfortunately, before we get to the fun stuff in this tutorial, we do have to work through the boring stuff. This means working on organizing our code.&lt;/p&gt;

&lt;p&gt;If you don’t remember, we used our standard server code and made some significant changes to the &lt;code&gt;index.js&lt;/code&gt; file in &lt;a href="https://thejavascriptninja.com/the-ultimate-beginners-guide-to-graphql/" rel="noopener noreferrer"&gt;part 1&lt;/a&gt; of the tutorial. I’d recommend reading that part first so you’ll be up-to-date on what we’re doing. After completing part 1, the code in our index.js file should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const port = process.env.port || 3000;
const express = require('express');
const ejs = require('ejs');
const layouts = require('express-ejs-layouts');
const app = express();

app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(layouts);

const homeController = require('./controllers/homeController.js');
app.get('/', homeController.renderIndex);

const { gql } = require('apollo-server-express');
const schema = gql`
  type Query {
    getUsers: User
  }
  type User {
    id: Int!
    username: String!
    email: String!
    password: String!
  }
`;

let users = [
  {
    id:1,
    username:'The Javascript Ninja',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
  {
    id:2,
    username:'The Javascript Ninjas Best Friend',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
]

const resolvers = {
  Query: {
    getUsers: _ =&amp;gt; 'Hello World'
  }
}

const { ApolloServer } = require('apollo-server-express');
const serve = new ApolloServer({
  typeDefs: schema,
  resolvers: resolvers,
});
serve.applyMiddleware({ app });

const server = app.listen(port, () =&amp;gt; {
  console.log(`🚀 Server listening on port ${port}`);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For a full explanation, read &lt;a href="https://thejavascriptninja.com/the-ultimate-beginners-guide-to-graphql/" rel="noopener noreferrer"&gt;part 1&lt;/a&gt;. Otherwise, note that the code above will create a GraphQL server alongside our express server, and define a simple query to execute. Don’t leave yet – read on. We’ll be expanding this database model later in the tutorial.&lt;/p&gt;

&lt;p&gt;Since we’ll be greatly expanding the code in our &lt;code&gt;index.js&lt;/code&gt; file, it might do us some good to split it up between other files. This will reduce the amount of clutter in our main file, and keep our project file organized.&lt;/p&gt;

&lt;p&gt;To organize our code, we can move our &lt;code&gt;schema&lt;/code&gt; and &lt;code&gt;resolvers&lt;/code&gt; objects to separate files. This may seem a little overkill at first, but after we expand them, it will be totally necessary.&lt;/p&gt;

&lt;p&gt;To do this, first, create a &lt;code&gt;models&lt;/code&gt; folder at the root level of your project. We will still want everything in our project to correspond with &lt;a href="https://thejavascriptninja.com/what-is-the-mvc/" rel="noopener noreferrer"&gt;MVC formatting&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Then, in our new &lt;code&gt;models&lt;/code&gt; folder, we’ll create the files &lt;code&gt;schema.js&lt;/code&gt; and &lt;code&gt;resolvers.js&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Next, in &lt;code&gt;schema.js&lt;/code&gt;, cut and paste the &lt;code&gt;schema&lt;/code&gt; object from index.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { gql } = require('apollo-server-express');
const schema = gql`
  type Query {
    getUsers: User
  }
  type User {
    id: Int!
    username: String!
    email: String!
    password: String!
  }
`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, in &lt;code&gt;resolvers.js&lt;/code&gt;, cut and paste the &lt;code&gt;resolvers&lt;/code&gt; object and &lt;code&gt;users&lt;/code&gt; array from &lt;code&gt;index.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let users = [
  {
    id:1,
    username:'The Javascript Ninja',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
  {
    id:2,
    username:'The Javascript Ninjas Best Friend',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
];

const resolvers = {
  Query: {
    getUsers: _ =&amp;gt; users;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, modify &lt;code&gt;index.js&lt;/code&gt; so it looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const port = process.env.port || 3000;
const express = require('express');
const ejs = require('ejs');
const layouts = require('express-ejs-layouts');
const app = express();

app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(layouts);

const homeController = require('./controllers/homeController.js');
app.get('/', homeController.renderIndex);

const schema = require('./models/schema.js');
const resolvers = require('./models/resolvers.js');

const { ApolloServer } = require('apollo-server-express');
const serve = new ApolloServer({
  typeDefs: schema,
  resolvers: resolvers,
});
serve.applyMiddleware({ app });

const server = app.listen(port, () =&amp;gt; {
  console.log(`🚀 Server listening on port ${port}`);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Awesome! Now our code is all nice and organized. All that we’ve done above is just sort our &lt;code&gt;resolvers&lt;/code&gt; and &lt;code&gt;schema&lt;/code&gt; objects into modules so they don’t all clutter up the same file.&lt;/p&gt;

&lt;h1&gt;
  
  
  Writing More Advanced Queries With Parameters
&lt;/h1&gt;

&lt;p&gt;Alright, now it’s time to work on the meat of GraphQL: querying. Querying is arguably the biggest and most important part of GraphQL (partly because the QL stands for Query Language). But, with all that said, it’s time to focus on writing more advanced query functions. The queries we wrote in part 1 were great, but they couldn’t do much and left a lot to be desired.&lt;/p&gt;

&lt;p&gt;In a realistic situation, your GraphQL query is probably going to return a lot of data. There are multiple reasons why this could be bad:&lt;/p&gt;

&lt;p&gt;• It’s hard to comprehend&lt;br&gt;
• It will drastically slow down the site&lt;br&gt;
• It’s impossible to filter through or perform operations on&lt;/p&gt;

&lt;p&gt;As you can see, none of these options are good in the slightest. That’s why it’s important to write better queries by filtering through data to return only what we need, not the entire database. We can do this by adding query parameters.&lt;/p&gt;
&lt;h3&gt;
  
  
  Adding In Some Parameters
&lt;/h3&gt;

&lt;p&gt;To add some parameters to our query, navigate to your &lt;code&gt;schema.js&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Then, let’s add some parameters to the &lt;code&gt;getUsers&lt;/code&gt; query in the &lt;code&gt;Query&lt;/code&gt; type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { gql } = require('apollo-server-express');
const schema = gql`
  type Query {
    getUsers(id:Int, username:String, email:String, password:String): User
  }
  type User {
    id: Int!
    username: String!
    email: String!
    password: String!
  }
`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we added all the arguments we wanted available to the &lt;code&gt;getUsers&lt;/code&gt; query. The reason I’ve added these arguments is so I’ll be able to filter through different users by these specific fields. There are no exclamation points after the object types in the parameters because I want all parameters to be optional.&lt;/p&gt;

&lt;p&gt;However, before we can successfully execute our query with these parameters, we need to make some edits to our resolvers.&lt;/p&gt;

&lt;p&gt;Go to &lt;code&gt;resolvers.js&lt;/code&gt;. Let’s update our &lt;code&gt;getUsers&lt;/code&gt; resolver. Right now, it looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let users = [
  {
    id:1,
    username:'The Javascript Ninja',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
  {
    id:2,
    username:'The Javascript Ninjas Best Friend',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
];

const resolvers = {
  Query: {
    getUsers: _ =&amp;gt; 'Hello World'
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pretty lame, huh? Right now, this lame resolver can only return our pre-set array of objects. And even at that, we can’t even filter the results in our query.&lt;/p&gt;

&lt;p&gt;Well, it’s time for things to change. Update &lt;code&gt;resolvers.js&lt;/code&gt; so it looks like the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let users = [
  {
    id:1,
    username:'The Javascript Ninja',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
  {
    id:2,
    username:'The Javascript Ninjas Best Friend',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
];

const resolvers = {
  Query: {
    getUsers: (parent, args) =&amp;gt; {
      if (args.id) {
        return users.filter(user =&amp;gt; user.id === args.id);
      } else if (args.username) {
        return users.filter(user =&amp;gt; user.username === args.username);
      } else if (args.email) {
        return users.filter(user =&amp;gt; user.email === args.email);
      } else if (args.password) {
        return users.filter(user =&amp;gt; user.password === args.password);
      } else {
        return users;
      }
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Wow – Big improvement. However, there’s a lot going on; let me explain it for you:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; First, the &lt;code&gt;getUsers&lt;/code&gt; method takes in two parameters: &lt;code&gt;parent&lt;/code&gt;, and &lt;code&gt;args&lt;/code&gt;. It is important that &lt;code&gt;args&lt;/code&gt; be the second parameter, otherwise you will get an error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; Second, we make a long &lt;code&gt;if&lt;/code&gt; statement. First, we check if the arguments &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;username&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt;, or &lt;code&gt;password&lt;/code&gt; were provided to filter through the data. If no parameters were provided, we return all the data in the users array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; If parameters were provided with the query, we filter through the data in the &lt;code&gt;users&lt;/code&gt; array with the &lt;code&gt;array.filter()&lt;/code&gt; method. Then, we return matching data – if there is any.&lt;/p&gt;

&lt;p&gt;Now, let’s test our new-and-improved query. Run your server and navigate to &lt;code&gt;localhost:3000/graphql&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi1.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-16-at-8.43.32-PM.png%3Fresize%3D768%252C331%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi1.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-16-at-8.43.32-PM.png%3Fresize%3D768%252C331%26ssl%3D1" alt="img"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, enter the following query into the box on the left:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;query {
  getUsers(id:1) {
    id
    username
    email
    password
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This should retrieve all data for the user with an id equal to 1.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi0.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-16-at-8.48.17-PM.png%3Fresize%3D768%252C331%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi0.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-16-at-8.48.17-PM.png%3Fresize%3D768%252C331%26ssl%3D1" alt="img"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  GraphQL Mutations
&lt;/h1&gt;

&lt;p&gt;The next big part of GraphQL is modifying data in the database. This includes adding and deleting users, in our scenario. Fortunately, GraphQL provides an easy way for us to do this: mutations.&lt;/p&gt;

&lt;p&gt;In a brief summary, mutations are just like GraphQL queries, except they modify data. In order to make a mutation, we can define a mutation type just like we did a &lt;code&gt;Query&lt;/code&gt; type in our schema.&lt;/p&gt;

&lt;p&gt;Modify your schema in &lt;code&gt;schema.js&lt;/code&gt; to look like the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { gql } = require('apollo-server-express');
const schema = gql`
  type Query {
    getUsers(id:Int, username:String, email:String, password:String): User
  }
  type Mutation {
    createUser(username:String, email:String, password:String): User
  }
  type User {
    id: Int!
    username: String!
    email: String!
    password: String!
  }
`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, mutations don’t look very different from queries. Of course, you can always get more advanced; these mutations are on a very basic level.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;Mutation&lt;/code&gt; type above, we define a &lt;code&gt;createUser&lt;/code&gt; mutation. This mutation takes in 3 parameters: &lt;code&gt;username&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt;, and &lt;code&gt;password&lt;/code&gt;. The reason we’re not going to provide the &lt;code&gt;id&lt;/code&gt; property is because we want the &lt;code&gt;id&lt;/code&gt; to be defined by the computer, whether randomly or in order, not manually.&lt;/p&gt;

&lt;p&gt;In order to put our mutation into effect, we’ll need to make some edits to our resolvers. Look at the new resolvers below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let users = [
  {
    id:1,
    username:'The Javascript Ninja',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
  {
    id:2,
    username:'The Javascript Ninjas Best Friend',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
];
const resolvers = {
  Query: {
    getUsers: (parent, args) =&amp;gt; {
      if (args.id) {
        return users.filter(user =&amp;gt; user.id === args.id);
      } else if (args.username) {
        return users.filter(user =&amp;gt; user.username === args.username);
      } else if (args.email) {
        return users.filter(user =&amp;gt; user.email === args.email);
      } else if (args.password) {
        return users.filter(user =&amp;gt; user.password === args.password);
      } else {
        return users;
      }
    }
  },
  Mutation: {
    createUser: (parent, args) =&amp;gt; {
      let newUser = {
        id: users.length + 1,
        username: args.username,
        email: args.email,
        password: args.password
      };
      users.push(newUser);
      return newUser;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, in our resolver, we have a new property after the &lt;code&gt;Query&lt;/code&gt; property! This is the &lt;code&gt;Mutation&lt;/code&gt; property. In the &lt;code&gt;Mutation&lt;/code&gt; property, we have the &lt;code&gt;createUser&lt;/code&gt; method. This is so far our first mutation. In the &lt;code&gt;createUser&lt;/code&gt; method we do 3 things:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; Create a &lt;code&gt;newUser&lt;/code&gt; object. In this object, we set the &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;username&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt;, and &lt;code&gt;password&lt;/code&gt; of our new user.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Add the &lt;code&gt;newUser&lt;/code&gt; object to the database. In reality, we would add the &lt;code&gt;newUser&lt;/code&gt; to the database. However, since we’re just using a dummy database model, we just use &lt;code&gt;array.push()&lt;/code&gt; to add the &lt;code&gt;newUser&lt;/code&gt; to our &lt;code&gt;users&lt;/code&gt; array.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Return the &lt;code&gt;newUser&lt;/code&gt;. This is pretty straightforward. We just return the &lt;code&gt;newUser&lt;/code&gt; object as a result of the mutation.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h1&gt;
  
  
  Running our First Mutation
&lt;/h1&gt;

&lt;p&gt;Now that we’ve got our mutation all done, it’s time to run. (Yes, that rhymes 😀). In order to run our mutation, start your server and navigate to &lt;code&gt;localhost:3000/graphql&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi1.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-10-at-8.25.47-PM-2.png%3Fresize%3D768%252C329%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi1.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-10-at-8.25.47-PM-2.png%3Fresize%3D768%252C329%26ssl%3D1" alt="img"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To make sure everything is working right, let’s first run our query. Enter this query into the box on the left:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;query {
  getUsers {
    id
    username
    email
    password
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see the following result:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi2.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-18-at-8.58.43-PM.png%3Fresize%3D768%252C330%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi2.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-18-at-8.58.43-PM.png%3Fresize%3D768%252C330%26ssl%3D1" alt="img"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we’ve ensured everything works and we aren’t getting any errors, it’s time to test our mutation. Let’s enter the mutation we wrote earlier:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mutation myMutation {
  createUser(username:"Subscriber to TJN", email:"contact@thejavascriptninja.com", password:"secret") {
    id
    username
    email
    password
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we call &lt;code&gt;createUser&lt;/code&gt;, and give it the specified params. It should return the following result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "data": {
    "createUser": {
      "id": 3,
      "username": "Subscriber to TJN",
      "email": "contact@thejavascriptninja.com",
      "password": "secret"
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi2.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-18-at-9.09.14-PM.png%3Fresize%3D768%252C330%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi2.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-18-at-9.09.14-PM.png%3Fresize%3D768%252C330%26ssl%3D1" alt="img"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, if we run our query again, we can see our mutation has taken effect.&lt;/p&gt;

&lt;p&gt;Run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;query {
  getUsers {
    id
    username
    email
    password
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "data": {
    "getUsers": [
      {
        "id": 1,
        "username": "The Javascript Ninja",
        "email": "contact@thejavascriptninja.com",
        "password": "its-a-secret"
      },
      {
        "id": 2,
        "username": "The Javascript Ninjas Best Friend",
        "email": "contact@thejavascriptninja.com",
        "password": "its-a-secret"
      },
      {
        "id": 3,
        "username": "Subscriber to TJN",
        "email": "contact@thejavascriptninja.com",
        "password": "secret"
      }
    ]
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi2.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-18-at-9.11.41-PM.png%3Fresize%3D768%252C328%26ssl%3D1" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi2.wp.com%2Fthejavascriptninja.com%2Fwp-content%2Fuploads%2F2020%2F12%2FScreen-Shot-2020-12-18-at-9.11.41-PM.png%3Fresize%3D768%252C328%26ssl%3D1" alt="img"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hooray! Our mutation worked!&lt;/p&gt;

&lt;h1&gt;
  
  
  To Conclude…
&lt;/h1&gt;

&lt;p&gt;A’ight folks!&lt;/p&gt;

&lt;p&gt;Today we’ve talked about organizing our code, writing more advanced queries (using parameters and variables), and GraphQL mutations.&lt;/p&gt;

&lt;p&gt;Pretty awesome stuff.&lt;/p&gt;

&lt;p&gt;I am going to end the tutorial here so it doesn’t get too long, but make sure to &lt;a href="//thejavascriptninja.com"&gt;subscribe&lt;/a&gt; so you don’t miss out on any great content!&lt;/p&gt;

&lt;p&gt;Stay tuned and talk soon!&lt;/p&gt;

</description>
      <category>graphql</category>
      <category>node</category>
      <category>javascript</category>
      <category>database</category>
    </item>
    <item>
      <title>Connecting a Project to GitHub From the Command Line</title>
      <dc:creator>The Javascript Ninja</dc:creator>
      <pubDate>Mon, 14 Dec 2020 16:18:41 +0000</pubDate>
      <link>https://dev.to/thejavascriptninja/connecting-a-project-to-github-from-the-command-line-3kco</link>
      <guid>https://dev.to/thejavascriptninja/connecting-a-project-to-github-from-the-command-line-3kco</guid>
      <description>&lt;p&gt;&lt;a href="//github.com"&gt;GitHub&lt;/a&gt; is a great tool to be used when programming, as it helps store your code over the internet. It makes your project more organized, easier to develop, and allows you to collaborate with friends or other developers. In addition, GitHub works smashingly with Visual Studio Code.&lt;/p&gt;

&lt;p&gt;If you’re still not recognizing a need for GitHub, do not worry – you will soon.&lt;/p&gt;

&lt;p&gt;In this short tutorial, I’m going to show you how to connect your project with GitHub from the command line.&lt;/p&gt;

&lt;h1&gt;
  
  
  Connecting to GitHub
&lt;/h1&gt;

&lt;p&gt;First, navigate to your project in your computer’s terminal and run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That will initialize your project with Git. Next, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git add .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That command will add all of your files to the git repository that we initialized in step 1. After, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git commit -m "Initial Commit"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This commits all your files to your repository. Next, we need to set up a GitHub repository. To do this, go to (github.com)[github.com] and either sign in or create an account. After that, create a new repository by clicking the “new” button on the sidebar on the left side of the screen.&lt;/p&gt;

&lt;p&gt;Next, give your repository a name, select if you want it to be public or private, and then click create at the bottom of the screen.&lt;/p&gt;

&lt;p&gt;Now, copy the repository link from the top of the page.&lt;/p&gt;

&lt;p&gt;Then, go back to your terminal. After, run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git branch -M master
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This creates a master branch for your repository. Finally, run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git remote origin add &amp;lt;repository link&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Make sure to replace &lt;code&gt;&amp;lt;repository link&amp;gt;&lt;/code&gt; with your GitHub repository link from above. The last thing we to do is to push all our files to GitHub! Do that with the following snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git push -u origin main
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Congrats! Now we’ve pushed our project to GitHub, and you should be able to see it if you reload your GitHub repository’s page.&lt;/p&gt;

&lt;h1&gt;
  
  
  Making Changes
&lt;/h1&gt;

&lt;p&gt;However, let’s say you continue to edit your code. How can we update your GitHub repository? It can be updated with this series of commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git add .
git commit -m "Your Commit Message Here"
git push -u origin main
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you're interested make sure to follow me or check out my &lt;a href="https://github.com/the-javascript-ninja"&gt;Github profile&lt;/a&gt;!&lt;/p&gt;

</description>
      <category>github</category>
      <category>bash</category>
      <category>git</category>
    </item>
    <item>
      <title>Getting Started With Electron – Building a 1-Page App</title>
      <dc:creator>The Javascript Ninja</dc:creator>
      <pubDate>Mon, 14 Dec 2020 00:05:10 +0000</pubDate>
      <link>https://dev.to/thejavascriptninja/getting-started-with-electron-building-a-1-page-app-1bf3</link>
      <guid>https://dev.to/thejavascriptninja/getting-started-with-electron-building-a-1-page-app-1bf3</guid>
      <description>&lt;p&gt;If you’re an intermediate or advanced javascript programmer, or even if you’re a beginner, chances are, you might have heard of Electron. Electron is an open-source Javascript framework that is being used to develop many applications all over the world.&lt;/p&gt;

&lt;h1&gt;
  
  
  What Is Electron?
&lt;/h1&gt;

&lt;p&gt;Like I said earlier, Electron is an open-source Javascript framework that is used to develop apps and desktop GUI applications in Javascript and Node.js. Originally developed by GitHub in 2013,  Electron has been used to develop many apps and IDE’s, including my personal favorite, Visual Studio Code. Electron was also used to develop Slack and the Atom editor. By combining the Node.js runtime and the Chromium rendering engine, Electron is easy to use and can develop cross-platform apps very easily without too much of a hassle.&lt;/p&gt;

&lt;h1&gt;
  
  
  Electron Features
&lt;/h1&gt;

&lt;h4&gt;
  
  
  • Reusability
&lt;/h4&gt;

&lt;p&gt;With Electron, since the code is web based, the code is completely reusable. This means that we can code once and still be able to convert our website easily into an app.&lt;/p&gt;

&lt;h4&gt;
  
  
  • Time and Cost
&lt;/h4&gt;

&lt;p&gt;Electron can save a lot of time and money for the fact that you can use the same code for a website and an app. This makes it easier without having to learn multiple new programming languages or hire multiple people.&lt;/p&gt;

&lt;h4&gt;
  
  
  • Performance
&lt;/h4&gt;

&lt;p&gt;Electron can have excellent performance if developed appropriately, deploying only what you need. Electron can save copious amounts of time in deployment, however it does take up some memory.&lt;/p&gt;

&lt;p&gt;These are 3 main features of Electron that make Electron so popular and convenient.  Overall, this makes Electron a fantastic development option.&lt;/p&gt;

&lt;h1&gt;
  
  
  How To Start Using Electron
&lt;/h1&gt;

&lt;p&gt;Electron is relatively easy to understand and is quick to get up and running with. All you need to do is a little bit of Node.js and you can get a 1 page app set up in no time!&lt;/p&gt;

&lt;p&gt;First, create a new project folder and call it anything you like. Then, navigate to that directory in your computer’s terminal.&lt;/p&gt;

&lt;p&gt;Next, initialize your project with NPM and complete the prompt. If you can’t fill out some fields or don’t know what they mean, accept the defaults.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After completing the prompt, install Electron as a development dependency.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i electron --save-dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that Electron is installed appropriately, it’s time to code the application. Let’s start by adding a start script to run the app.&lt;/p&gt;

&lt;p&gt;In your app’s &lt;code&gt;package.json&lt;/code&gt; file, add a start script to the &lt;code&gt;scripts&lt;/code&gt; object. Remember to include a comma after the test script.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
    "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1",
    "start": "electron ."
 },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, whenever you’re ready to run your electron application, you can run &lt;code&gt;electron .&lt;/code&gt; or &lt;code&gt;npm start&lt;/code&gt; to run your project.&lt;/p&gt;

&lt;p&gt;Next, create a file called &lt;code&gt;index.js&lt;/code&gt; at the root level of your project’s directory. In &lt;code&gt;index.js&lt;/code&gt;, we need to require the &lt;code&gt;app&lt;/code&gt; and &lt;code&gt;BrowserWindow&lt;/code&gt; variables from &lt;code&gt;electron&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const {app, BrowserWindow} = require('electron');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we’ll need to write the main function that will open our application’s window. We can do this by declaring a function to create a window. Then, we can declare some properties of the window, like the width and height, and tell it to render an HTML page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var createWindow = () =&amp;gt; {
    var window = new BrowserWindow({
        width:800,
        height:600,
        webPreferences: {
            nodeIntegration: true
        }
    });

    window.loadFile('index.html');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we need just a couple more functions to activate our app. Here are functions that will draw the window when the app is opened, quit when the application has been quit, and draw a new window if the app is activated.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.whenReady().then(() =&amp;gt; {
    createWindow();
});

app.on('window-all-closed', () =&amp;gt; {
    if(process.platform !== 'darwin') {
      app.quit()
    }
})

app.on('activate', () =&amp;gt; {
    if(BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our app is now officially ready. All that’s left to do is to create an HTML page called &lt;code&gt;index.html&lt;/code&gt;, and give it whatever content you would like to be in your app. You can also create CSS and Javascript pages to link to your HTML page.&lt;/p&gt;

&lt;p&gt;Here is the final code for the boilerplate Electron app that I built.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/the-javascript-ninja/Electron_Boilerplate.git"&gt;https://github.com/the-javascript-ninja/Electron_Boilerplate.git&lt;/a&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
    </item>
    <item>
      <title>The Ultimate Beginner's Guide to GraphQL</title>
      <dc:creator>The Javascript Ninja</dc:creator>
      <pubDate>Sat, 12 Dec 2020 22:26:25 +0000</pubDate>
      <link>https://dev.to/thejavascriptninja/the-ultimate-beginner-s-guide-to-graphql-ghe</link>
      <guid>https://dev.to/thejavascriptninja/the-ultimate-beginner-s-guide-to-graphql-ghe</guid>
      <description>&lt;p&gt;Let’s talk about one of the biggest pains in web development: connecting your app to a database. While you might not share the same opinions, this is one of my least favorite parts of server-side development, so this tutorial will show you my tried-and-true tricks for making this go smoothly.&lt;/p&gt;

&lt;p&gt;Firstly, when you’re just starting with databases, it can be very overwhelming as there are TONS of different options to choose from. Should you choose plain-old MySQL, MongoDB, PostgreSQL, or maybe GraphQL? If you’re thinking, “What’s the big difference?” Then don’t worry, you’re not alone; I originally thought that as well, but I can assure you that you’ll soon be on your way to database nirvana.&lt;/p&gt;

&lt;h1&gt;
  
  
  Using This Guide
&lt;/h1&gt;

&lt;p&gt;I’m well aware that there are hundreds of other guides on the internet about this very same topic, and I can confidently say that I’ve looked at most of them. When I first started with databases and GraphQL, I was very confused. The large number of resources and various methods might leave you questioning, “Should I do it this way or that way?” Coming from somebody who’s actually tried most of the different methods, I’ll cover the easiest, simplest, and most effective ways to go about starting with a database (in my opinion).&lt;/p&gt;

&lt;h1&gt;
  
  
  Setting Up
&lt;/h1&gt;

&lt;p&gt;As usual, I’m going to use a basic express server with EJS as my templating engine. I’m also going to arrange my project folder in the MVC format. I’m not going to show how to set up the whole project for sake of brevity, but if you’re unclear on any of these concepts, make sure to check out my articles on:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://thejavascriptninja.com/how-to-add-express-js-to-a-node-js-web-app/" rel="noopener noreferrer"&gt;How to Add Express to a Node.js Web App&lt;/a&gt;&lt;br&gt;
&lt;a href="https://thejavascriptninja.com/what-is-the-mvc/" rel="noopener noreferrer"&gt;What is the MVC?&lt;/a&gt;&lt;br&gt;
&lt;a href="https://thejavascriptninja.com/templating-with-ejs-and-node-js/" rel="noopener noreferrer"&gt;Templating With EJS and Node.js&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In addition, if you just want to jump right in, you can download my boilerplate server code &lt;a href="https://github.com/the-javascript-ninja/boilerplate_server" rel="noopener noreferrer"&gt;here&lt;/a&gt; on GitHub. This is the code I will be using for my server.&lt;/p&gt;

&lt;p&gt;After we’ve gotten the basic server up and running, there is one more dependency that we need to install.&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;a href="https://www.npmjs.com/package/apollo-server-express" rel="noopener noreferrer"&gt;apollo-server-express&lt;/a&gt;
&lt;/h4&gt;

&lt;p&gt;This package is responsible for setting up our GraphQL server. If you’re already familiar with GraphQL, you might realize that there is also a package called apollo-server which would work just as well. The reason I’m using apollo-server-express is so that we can run the GraphQL server alongside our Express server.&lt;/p&gt;

&lt;p&gt;You can install this package by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i apollo-server-express -S
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Later on in this series, we will probably need to install some more dependencies but this is the only other one we’ll be needing for this part.&lt;/p&gt;

&lt;h1&gt;
  
  
  Writing A Schema
&lt;/h1&gt;

&lt;p&gt;For the next couple of following sections, I’m going to teach you some of the basic GraphQL necessities that we will need to write our GraphQL server. We won’t be able to write the server until we get through this part, so bear with me while we go over this necessary material.&lt;/p&gt;

&lt;p&gt;One of the most important parts of GraphQL (or any query language) are parts called schemas. In short, schemas are data representations in the form of a model. For example, if we had a chat app and were storing messages in the database, we might add a message type to our schema. It might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Message {
  id: Int
  text: String
  from: String
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, each message we store would have the &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;text&lt;/code&gt;, and &lt;code&gt;from&lt;/code&gt; properties. This is like an outline that will apply to each message that we send.&lt;/p&gt;

&lt;p&gt;To actually write our schema, we will use have to use the &lt;code&gt;gql&lt;/code&gt; property of the &lt;code&gt;apollo-server-express&lt;/code&gt; module. Check out the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { gql } = require('apollo-server-express');
const schema = gql`
  type Query {
    getUsers: User
  }
  type User {
    id: Int!
    username: String!
    email: String!
    password: String!
  }
`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example, we require &lt;code&gt;gql&lt;/code&gt; from &lt;code&gt;apollo-server-express&lt;/code&gt;. Then, let’s pretend we’re building the user authentication for our chat app. First, we’d define a &lt;code&gt;User&lt;/code&gt; model. Then, we define a &lt;code&gt;Query&lt;/code&gt; type. In our &lt;code&gt;Query&lt;/code&gt; type, we have a &lt;code&gt;getUsers&lt;/code&gt; method. We set this to return data of type &lt;code&gt;User&lt;/code&gt;. In the &lt;code&gt;User&lt;/code&gt; type, each user will have the following properties of &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;username&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt;, and &lt;code&gt;password&lt;/code&gt;. The exclamation point after the property type means that the property is non-nullable.&lt;/p&gt;

&lt;h1&gt;
  
  
  Writing Resolvers
&lt;/h1&gt;

&lt;p&gt;The next thing we’ll need in order to get GraphQL working is to write some resolvers. Briefly, resolvers are groups of functions that act upon a GraphQL query. This means that whenever you execute a query from your schema, such as the &lt;code&gt;getUsers&lt;/code&gt; query we wrote above, you will need a resolver to handle the information and send back a response.&lt;/p&gt;

&lt;p&gt;Writing resolvers is actually fairly simple. Take a look at the example below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const resolvers = {
  Query: {
    getUsers: _ =&amp;gt; 'Hello World'
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alright – this is a fairly simple object. First, we have our &lt;code&gt;resolvers&lt;/code&gt; object; this is where we will put all of our resolvers. Then, inside the &lt;code&gt;resolvers&lt;/code&gt; object, we have the &lt;code&gt;Query&lt;/code&gt; object. This is where we will put all our resolvers of type &lt;code&gt;Query&lt;/code&gt;. You can see that we defined &lt;code&gt;getUsers&lt;/code&gt; in the &lt;code&gt;Query&lt;/code&gt; type when we wrote our schema. Finally, we add our &lt;code&gt;getUsers&lt;/code&gt; resolver to the &lt;code&gt;Query&lt;/code&gt; object and set it to return the string &lt;code&gt;'Hello World'&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It’s important to realize that the Hello World part is temporary. Since we haven’t yet set up a database model, we don’t have anything to return yet. That’s why I’m returning &lt;code&gt;'Hello World'&lt;/code&gt;. Don’t worry though; we will add a dummy database model later on in the tutorial. For now though, I’m going to leave the resolvers as-is so we can start writing the server and seeing some results.&lt;/p&gt;

&lt;h1&gt;
  
  
  Writing The Server
&lt;/h1&gt;

&lt;p&gt;Up until now, we haven’t really seen any results of our coding. We’ve mostly just been writing the code without anything happening. Well, now it’s time to write the server. Once we’ve got the server down, we’ll be able to interact with the database.&lt;/p&gt;

&lt;p&gt;Surprisingly enough, the server is very easy to code. Take a look at the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { ApolloServer } = require('apollo-server-express');
const serve = new ApolloServer({
  typeDefs: schema,
  resolvers: resolvers,
});
serve.applyMiddleware({ app });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, we first require &lt;code&gt;ApolloServer&lt;/code&gt; from the &lt;code&gt;apollo-server-express&lt;/code&gt; package. Then, we set up a &lt;code&gt;serve&lt;/code&gt; object. The &lt;code&gt;typeDefs&lt;/code&gt; property is where we tell the server our schema, and the &lt;code&gt;resolvers&lt;/code&gt; property is where we tell the server our resolvers. Then, we add the GraphQL server to our express server. The &lt;code&gt;app&lt;/code&gt; variable is the variable we declare when we initialize our express server.&lt;/p&gt;

&lt;p&gt;After all this coding, the code in your index.js file should look like the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const port = process.env.port || 3000;
const express = require('express');
const ejs = require('ejs');
const layouts = require('express-ejs-layouts');
const app = express();

app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(layouts);

const homeController = require('./controllers/homeController.js');
app.get('/', homeController.renderIndex);

const { gql } = require('apollo-server-express');
const schema = gql`
  type Query {
    getUsers: User
  }
  type User {
    id: Int!
    username: String!
    email: String!
    password: String!
  }
`;

const resolvers = {
  Query: {
    getUsers: _ =&amp;gt; 'Hello World'
  }
}

const { ApolloServer } = require('apollo-server-express');
const serve = new ApolloServer({
  typeDefs: schema,
  resolvers: resolvers,
});
serve.applyMiddleware({ app });

const server = app.listen(port, () =&amp;gt; {
  console.log(`🚀 Server listening on port ${port}`);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, to run the server, navigate to your project in your computer’s terminal/shell and run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node index
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alright! The server is running! However, if you navigate to &lt;code&gt;localhost:3000&lt;/code&gt; in your web browser, you won’t see any indication that the GraphQL server is working. So, how do we know? Well, GraphQL comes with an awesome browser tool called GraphIQL. This is what we’ll use to interact with the database.&lt;/p&gt;

&lt;h1&gt;
  
  
  Database Interaction With GraphIQL
&lt;/h1&gt;

&lt;p&gt;GraphQL wouldn’t be GraphQL without the QL part: the query language. We need to be able to retrieve, add, modify, and delete information from the database. For this, we’ll use an in-browser feature called GraphIQL.&lt;/p&gt;

&lt;p&gt;In order to access GraphIQL, navigate to &lt;code&gt;localhost:3000/graphql&lt;/code&gt; with your server running. You should see something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwtqptc1ci6biuz7ib90c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fwtqptc1ci6biuz7ib90c.png" alt="Screen Shot 2020-12-10 at 8.25.47 PM"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is the online, fully interactive, GraphQL UI. This is the space where we can run and execute queries. To execute our first query, enter the code below into the box on the left and click the run button.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;query findUsers {
  getUsers
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, we define our query with the &lt;code&gt;query&lt;/code&gt; keyword and the name of our query (the name can be anything you want). If we only have one query, however, we don’t actually need this. The code would also work just fine if we wrote it like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  getUsers
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What this does is it executes the the &lt;code&gt;getUsers&lt;/code&gt; resolver. Once we run the query, it should return the following result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "data": {
    getUsers: 'Hello World'
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It returns the string &lt;code&gt;‘Hello World’&lt;/code&gt; because that is what we set it to return in our &lt;code&gt;getUsers&lt;/code&gt; resolver.&lt;/p&gt;

&lt;h1&gt;
  
  
  Adding in a Database Model
&lt;/h1&gt;

&lt;p&gt;In order to keep this post short, this will be the last section. This will, however, be a series. Make sure to keep an eye out for the parts that follow, or you can subscribe for email updates.&lt;/p&gt;

&lt;p&gt;That said, our GraphQL program and query works pretty well, but it would be pretty neat if we could retrieve actually data, not just a short string. Fortunately for us, this is well within our capabilities. First, let’s create an array of users like the one shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let users = [
  {
    id:1,
    username:'The Javascript Ninja',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
  {
    id:2,
    username:'The Javascript Ninjas Best Friend',
    email:'contact@thejavascriptninja.com',
    password:'its-a-secret'
  },
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above, we have two users in an array. Both users contain all the properties that we entail them to have in our schema. Next, let’s make a couple of changes to our resolvers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;From this:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const resolvers = {
  Query: {
    getUsers: _ =&amp;gt; 'Hello World'
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;To this:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const resolvers = {
  Query: {
    getUsers: _ =&amp;gt; users
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, when we call the &lt;code&gt;getUsers&lt;/code&gt; resolver, it will return the data in the users array.&lt;/p&gt;

&lt;h1&gt;
  
  
  Wrapping Up
&lt;/h1&gt;

&lt;p&gt;I’m going to end this part of the tutorial here, but this certainly isn’t the end of the series! We have only just barely scratched the surface of GraphQL and databases, so make sure to watch out for other parts of my GraphQL for Beginners series. Feel free to subscribe so you don’t miss out on any updates (there’s a form on the home page or at the top of this page if you’re interested).&lt;/p&gt;

&lt;p&gt;As always, leave a comment or like this post if you enjoyed it or want more content like this.&lt;/p&gt;

&lt;p&gt;Hope to see you soon!&lt;/p&gt;

</description>
      <category>graphql</category>
      <category>node</category>
      <category>javascript</category>
      <category>database</category>
    </item>
  </channel>
</rss>
