Press "Enter" to skip to content

MERN Stack & GraphQL – #4 Apollo Server with Express


hey guys welcome back to my channel in
this video we’re gonna start building
our full-fledged
graph QL chat application so let’s first
talk about the project we’re about to
build it’s going to be a real-time chat
application built with myrn stack and
graph QL so let’s first of all focus on
some of the features that we’re trying
to accomplish for this application for
the MVP or the Minimum Viable Product
we’re gonna try to achieve a sign up as
well as sign in and perhaps say we set
password functionality we’re gonna also
work on direct messaging so one-on-one
between two users we’re also gonna touch
on private group chats so having two or
more users within a single conversation
well then work on file sharing and this
could be images text and other types of
files and then lastly we’re also gonna
work on responsive material design now
once we accomplish those basic
functionalities for an MVP it would be
nice to have a bunch of other features
like notifications will be also nice to
have themes and customizations with the
user preferences
maybe also things like status indicators
so for example when someone is typing we
might display a status for that user or
perhaps user statuses themselves so for
example user could be online offline
things like that we might also work on
emails so sending confirmation emails
when you finished registering or forgot
password functionality when you want to
restore your lost password and some
other functionalities as well now this
is an open question so if you do have
some ideas in mind leave them down below
and we might as well go over them in
this project so let’s move on to topics
so there’s quite a few technical topics
that I’d like us to focus on the first
thing is schema design so we’re going to
be following a schema first design the
next topic is user validation and that’s
gonna be important for security or
application we’re also definitely going
to touch on authentication we’re gonna
talk extensively about session versus
token-based authentication approaches
and then we’re going to also talk about
authorization so granting users specific
permissions and also rejecting access to
other permissions that they don’t have
we’re next gonna move on to security and
this is going to be a very important
topic for this app we’re gonna talk
about injections we’re gonna talk about
different kinds of attacks so for
example XSS CSRF attacks and we’re also
gonna focus a bit on these security
headers on the client side we’re also
going to talk about safe management
we’re going to be using
Apolo client which basically manages all
of your data client-side and the cache
we’re then going to move on to file
upload so being able to upload files
like images on the server we’re
definitely going to touch on real-time
updates with craftool subscriptions
we’re going to also look into
performance optimizations and this could
be at the query level this could be at
the application level as well and last
thing we might also look into pagination
so instead of returning a full set of
results we’re gonna try to implement
different ways to request a specific
subset for example of messages or users
or other resources let’s talk about the
technologies that we’re gonna be
focusing on for this project first of
all on the back end we have node as well
as the Express framework as firstly data
layer
we’re gonna be using MongoDB as well as
the mongoose or our graph QL application
layer is gonna be built with a pollo
server v2 we’re also gonna make use of
WebSockets every might also be using
Redis for authentication there might be
other technologies as well but this
might as well change throughout the
project so I’ll leave that as an open
question as well and lastly for the
front-end technologies we’re gonna be
using react 16 we’re gonna also be using
a polo client v2 which is the latest
client for react and lastly we’re also
going to be using material UI to develop
our responsive user interface right so
now that we had a basic overview of the
project let’s move on to the coding part
so first of all we already have a repo
you can find it on github if you go to
github comm slash Alex 9 & 6 slash graft
you’ll chat so the first thing I would
suggest you do is that you go to that
repo and you clone it to your local
filesystem you can just copy that URL
you can paste it in in your terminal and
do a git clone on that URL so this is
gonna clone the repo in its current
state so far I’ve basically already done
that on my site so I can just switch
back to my terminal I’ll show you that I
have all the files and I’m also on the
master branch as well so let’s go ahead
and open this project in Visual Studio
code and right off the bat we have this
index.js file that sets up e graphical
server with some basic in memory
database as I mentioned in the last
video this way of creating an Apolo
server instance is gonna instantiate
xpress framework behind the scenes so
it’s actually going to instantiate in
GDP server will the Express framework
now there’s also a different approach to
doing this which is more explicit so if
we go ahead and search for a polo server
we can go ahead and visit the
documentation link and then in here I’m
going to go to building a server you can
see that there is a middleware section
and this one outlines an alternative way
of setting up the server so instead of
using a polo server package you could
also use a polo server express which
basically has the same exports except
you would need to call apply middleware
on your Polo server passing the Express
instance as the argument in the object
now we’re gonna use this approach and
the reason for doing that is first of
all it can allow us for more
fine-grained customization so for
example setting up custom headers or
removing some headers for example one of
the typical headers that you would like
to remove from a production application
would be X powered by in fact if I go
back to the terminal I’m gonna do a yarn
watch to show you what I mean by this
let’s go to localhost 4000 now if I go
ahead and open the network tab so I’m
going to fire a query on users let’s get
users by ID if you inspect the exact
response from the server if you go to
the header section you’re gonna see that
there is an X powered by header on the
response object and this one is set to
Express now this header is one of the
headers that you would like to remove
from your production application like I
said it kind of becomes difficult if
you’re using the Apolo server package
and if you are instantiating the Apolo
server without providing your
application instance from Express it
might as well be easier to create your
own instance and pass it to Apolo
instead so this way you would have a lot
more customization available to you and
the other reason if we go back to the
docs might be to set up an SSL
connection so for example if you have
your certificates for setting up an HTTP
server in order to do that you would
need to call the HTTP module create
server function depending on whether SSL
is enabled in your app you’re going to
need to use a different module if it is
enabled you’re gonna need to call HTTP
which is the built in module in nodejs
but if it’s not enabled you’re gonna
need to call HTTP and this is typically
used for development so that’s another
reason for
your own Express instance and then
passing it to Apollo server instead of
letting it do it by itself implicitly so
what we’re gonna do is we’re gonna go
back over here once again looking back
at the list of dependencies we have a
Polo server and we also have graph QL so
in order to set up a custom server I’m
gonna stop our running server I’ll do a
yarn remove of a Polo server so that’s
gonna remove that dependency instead
we’re gonna do a yarn add a pole server
express and also Express so the first
one is going to be the package for
setting up a polo with Express framework
and the second one is the Express
framework itself now going back to this
index.js file I’m basically going to
remove everything from here we’re
basically going to point to source index
j s which is more of a convention that I
like to follow I’m going to create a
source folder I’m gonna paste in an
index J s file and then in here we can
basically set up a functional server so
we’re going back to this middleware
section let’s go ahead and copy the
initial set up from here so we can save
up some typing now first of all instead
of using common Jia’s for required
statements i’d like to use import
statements so what i mean by that is
instead of doing const and then having a
pull server as well as gql using a
require statement i’d like to import it
from a polo server express using es6
modules now because these six modules
are not enabled in node as of yet we’re
gonna have to use a library like babel
for example this one is gonna allow us
to transpile this import syntax back to
comma j s syntax so this would basically
be like sugar coating for the const
required statement that we had before so
even though we would have imports that
code would be transpiled down to require
statements so this is kind of like
fooling ourselves because we’re actually
using common GS instead of es6 modules
now that’s one common way to go about it
now the other way to do it if you don’t
want to set up the whole babel
infrastructure there’s another package
that we can look into i’m going to go to
npm Gia’s org and we can go ahead
search for ESM ESM is a package that
allows you to use es6 imports and
exports and nodejs and this way you can
use it with earlier versions of node
like note 6 so all we have to do is we
need to do an import of esm library so
going back to the terminal I’m going to
do a yarn add ESM so once that library
is installed we can basically use import
statements safely so let’s go ahead and
finish up this file we’re gonna new up
the Apolo server instance I get rid of
those semicolons and in fact because you
see me working with semicolons trailing
commas single quotes versus double
quotes this topic goes back to something
known as linting now one thing is a
process of verifying your code against a
certain style guide because this project
is gonna be fairly big I’d like us to be
using a linting standard and the one
that I’m passionate about is actually
called standard Jas now if we look for
it there should be a package let me look
for standard and it’s gonna be the first
one popping up version 12 so that’s
exactly the one we’re looking for now
there’s quite a few distinctive features
about standard it’s a bit different from
us lint for example you’re gonna be
using two spaces single quotes no
semicolons spaces between if
conditions-based spaces between function
names things like that
now linting is useful for keeping your
code consistent and in some cases it can
even help you avoid bugs in your code as
well so what I’m gonna do is I’m gonna
do a yarn add a developing dependency of
standard so let’s go ahead and do that
and I might have to restart Visual
Studio code so let me do exactly that
right so as you can see we’ve got
linting enabled right away and for
Visual Studio code you might actually
have to install a plug-in now I already
have one installed and it’s actually
called standard J SEO script standard
style so you can just basically go ahead
and install that package or plugin for
your editor and if you’re using
something like sublime or atom those
must also have the same package as well
now in my case I already have it
installed so it seems like lengthing is
already enabled
so we’re gonna do next is we’re gonna
import Express from Express we’re gonna
need to new it up this app constant
because right now it’s undefined so
let’s do Express now the next thing like
I was talking about we can actually go
ahead and disable one of the headers so
for instance we can go ahead and disable
X powered by and that’s gonna remove
that pesky header from a request the
next thing is that we’re missing type
definitions and resolvers so let’s
actually go ahead and include the import
statements for those too so we’re gonna
have type definitions from type
definitions we’re gonna have the same
one for Silver’s so let me go ahead and
alright so we’re gonna have to create
those two folders so let’s do resolvers
we’ll create one for type definitions
and we need to remove this trailing come
over here now the next thing is we’re
gonna go ahead and do an app listen on
port 4,000 now the port itself this is
one of the things that would like to
customize or at least make configurable
so in this case what I’m gonna do is I’m
gonna create a Const let’s go ahead and
try to extract at port basically this
could be called anything then call it
port I’m just gonna call it a port for
clarity the default value can be 4000
for example we’re gonna grab it from
process and now this way you’re gonna be
able to pass environment variables to
your script when executing it so for
example going back to a package.json I’m
going to switch from watch to down just
because it’s easier to type but in this
case since we’re having an old Wan
script we can go ahead and also pass in
something like let’s say node
environment we can set it to development
we can go ahead and customize the
airport to something like five thousand
for example and this will be the perfect
place for passing those variables for
now I’m just gonna keep in old
environment and going back over here I’m
actually going to also extract it from
here so let’s do new environment and by
default we’re gonna set it to
development like this now the
application port is going to be used
over here to launch your application
next up we can also output the URL so
this way we can also paste in the port
over here and this way we can have the
full URL to the server I’m gonna
move this gql from over here because
we’re not using it now as far as the
configuration goes for a polo server
itself there’s one last thing we also
need to configure and this one is called
playground now the playground refers to
the graphical playground that you see
when interacting with the app and
development basically in this case we’re
using pass in an object with options but
you could also pass any boolean now this
one we actually do need to do it’s
working fine in a pull server but if
you’re using a polo server express there
seems to be a bug where you’re still
able to access the playground in
production but you’re not able to
execute any queries but anyhow to fix
this we’re basically going to set the
boolean to node environment we can check
if null environment equals production
and in this case if the node environment
does not equal production then we want
to enable playground so if we are in
prod this is going to evaluate to false
and we won’t have any playground now in
fact this could also be a variable on
its own now I’m gonna go ahead and
create it so let’s call it in prod we’re
gonna put that expression in there we’re
gonna use not in prod like this next up
let’s go ahead and define the schema so
I’m gonna create an index J as file in
here we’re also gonna start with the
user schema first so let’s create a
basic schema for a user I’m gonna do an
export default of gql we’re gonna pass
in the schema inside so in here we can
have a type query we can have a type of
mutation and we can have a type of user
like this of course we need to import
gql as well so let’s do that
from a Polo Server Express now as you
can see some of these types are actually
going to be sure between schemas so what
I mean by that is for example we’re
gonna have a schema for a chat a schema
for a message all of those different
schema definitions are gonna need to
somehow extend the main route types and
this is basically gonna allow us to
modularize our schema but to do this is
very simple all we have to do is we need
to put in the extend keyword in front of
it now this is only going to work if you
have a definition for
query and mutation so going back and
index what we can do is we can actually
have an import of user from user and
then to export this key mobile could do
an export default of an array and this
way we can pass in the user inside so if
we create other schema definitions so
for example for a message for a chat we
can also pass in those definitions
inside of the array and this way they’re
going to be concatenated and served up
as a single schema but like I said
there’s one caveat and the caveat is
that we need to create a sort like a
route or parent definition need to call
gql and we basically just need to define
the query type we need to define the
mutation type and that’s because we’re
gonna be extending both of them across
the different files for defining custom
schemas like user or message or chat
once again and because we’re also going
to be extending the subscription rule
type we’re gonna go ahead and also put
subscription in here
let’s do subscription now the only
caveat here is that all of these route
types cannot be empty so we’re gonna
need to go ahead and put in something
inside so for example we can put an end
underscore or we can put in like empty
or something that’s not intended to be
used for actual data so this one can be
a string and we’re gonna do the same
thing for mutation and subscription like
this so this route definition can as
well go into its own file so I’m gonna
create a route is file in here we can go
ahead and copy gql import I’ll put it at
the top and here so actually we can do
an export default of the adji ql and
once again this import/export syntax is
only available to us because of the ESM
library another thing i mention it but
in order to use this module we’re gonna
need to use a – our flag from the
command line so let’s actually go ahead
and look for nodejs command line options
let’s see if we can find it and for CLI
options we can actually look for require
and this one allows us to require M
before loading up a script so in order
to start the script you can either use
node – are require the ESM module and
then point to index j s where we can
just basically put a dot this is gonna
look for index.js file in the current
directory or using node mod we could do
NP x node mod we can pass in the – or
option on the ESM package or library and
then also put in a dot but even with
Novant we don’t actually have to put in
any arguments after that so let me go
ahead and do exactly that back in my
editor for the Deaf command I’m gonna go
ahead and put a node Mon – or ESM like
this so this is where we’re gonna be
loading up the ESM package right so
going back to our file over here we’ve
got our root query definitions and
that’s perfect so we can close it up
back in here let’s do an import of that
root file
let’s do import on root we’re gonna pass
them in to the array like this a back
end user we’re gonna go ahead and create
a definition for user so once again
we’re gonna have an ID
as always we will also have an email
this would be a required string field
let’s also have a user name a string
yeah it’s gonna be required a name which
will also be required string once again
let’s also have created adds and this
one is going to be a string as well now
eventually we’re also gonna have other
types so for example we’re gonna have
chats with each add object but let’s not
get ahead of ourselves we’re gonna go
step by step so for the time being we’re
gonna have a simple user schema and so
kick this off we’re gonna have a sign up
mutation so this one is gonna accept an
email once again the string a username
string and a name as well so let’s do a
name string and this might or might not
return a user because for example if you
are already logged in it makes no sense
to create a user so you’re probably
going to get an exception from the
server or you might get a validation
error or something might as well crash
on the server itself so the user object
might or my
not be returned so we’re gonna keep it
as optional for now now for the query
type we’re going to define a user by ID
we’re gonna accept an ID and return a
user once again this is gonna be
optional so I’m not gonna put in an
exclamation because if you provide an
invalid ID we’re gonna have to raise an
exception so this is gonna be part of
validation and no worries we’re gonna
get into that in the upcoming videos but
aside from that we’re also gonna have a
users query and this one is gonna return
an array of user objects now in this
case I’m putting inflammation marks once
again when all we’ve talked about it
before but it’s important to emphasize
this the user object inside the array
cannot be null in the array itself
cannot be null either so we have to
return at least an empty array and one
last thing I forgot for the signup
mutation of course we also need to pass
in a password as well so this one needs
to be a required string now of course
we’re not gonna have a password on the
user type itself so we’re not gonna be
returning it from the API but we’re
gonna have to provide it as one of the
arguments because it’s gonna be stored
in a database and once this is done
let’s go ahead and create a resolvers in
the extras file and this one is gonna be
an entry point so I know I’m gonna
create a user file so let’s do an import
of user from user this one is gonna be
user resolver so let’s create that so
this one is gonna be an export default
of an object once again for a root type
resolver for example on the query if we
have let’s say a user’s resolver we’re
gonna have the root value arguments
context and then the last one is gonna
be info so this will be a function and
go ahead and copy that so let’s also
create one for a user we’re gonna also
add a key for mutation like this let’s
also create a signup mutation so that we
can go ahead and create users in our
database and that should basically be it
now in this index.js file I’m gonna do
an export the fault of an array and I’m
gonna pass in the user object inside and
now to start the server we need to go
back to our index J’s file at the top
this file is gonna be loaded by default
so using this
def command or we could also add a start
script for a production build so for
example we can have a load environment
set to production and we can basically
call node on the current directory and
of course we need to require ESM and
once again this script is going to be
pretty much identical to the dev one
except we’re going to be setting the
environment to production and this node
environment variable is going to be
available in here so we’re destructuring
it from process and and on the same note
it seems like i’m a date type over here
of course this needs to be a triple
equal because we’re checking if the null
environment is production if so we’re
setting the in prod variable to that
expression so actually let’s see the
file and last stop let’s go back to our
index j s and here i’m going to import
the contents of the source directory and
this is supposed to go to the index J is
valid here so let’s go ahead and back to
our terminal I’m gonna do a yarn dev and
this is gonna start the playground so
for example let’s open up the network
tab when I try to fire a query hmm I’m
not sure if it’s gonna work though
because we don’t have anything in there
yet and of course we are getting an
error but at least we can see that the
server is working and on the same note
we are not getting the X powered by header anymore as you can see

Please follow and like us: