Our Tech Journal
  • Introduction
  • Overview
    • Introduction
  • Javascript
    • JS Runtime, Env Context, Scopes, Hoisting & Execution Cycle, var/let/const, this
    • Javascript Runtime Env
      • Event loops
    • What are WebVitals
    • Module Patterns in JS - CommonJS, AMD and ES6 classes
    • Lexical Environment in JS
    • var vs let/const
    • Temporal Dead Zone (TDZ)
    • Execution Context
    • 'this' keyword
    • undefined value in JS
    • Function expressions vs Function statements
    • Javascript Code Execution
    • Closures
    • JS : Object Oriented Programming
    • Prototypal Inheritance
      • Creating Object in Javascript
    • NaN
    • Objects
      • Ways to create
      • ways to check if Object is empty
      • Object's own properties
    • use strict mode
    • typeof vs instanceof
    • Promise
    • localStorage and SessionStorage
    • Event handlers
    • Event bubbling
    • Event Delegation
    • XHR Request
    • Promise Error: Catch vs Error Function in Then
    • Immutability
    • Useful Code samples
    • window, document, screen
    • window.innerheight, outer height, screen.height
    • JS Design Patters
    • Interview Questions
    • Encapsulation - Module Patterns in JS
    • Redesigning services using Entity framework approach
  • JS Functions
    • JS Array - Slice vs Splice
  • PWA
    • What is PWA
  • ES6
    • Sets
    • Maps
    • spread vs destructure operator
  • Web
    • http / https
    • CORS
    • CSRF
    • XSS Attack
    • What is SPA
    • Semantic Elements in HTML
  • Angular 4
    • Angular vs React
    • Change Detection
    • Lazy Loading of modules
    • Preloading
    • AOT Compilation
    • Route Guards
    • Shared Modules
    • Tree Shaking
    • LifeCycle Hooks
    • ngRx
    • Observables
    • Observable vs Subject
      • BehaviorSubject
    • Observables vs Promises
    • Builtin Directives
      • Temp
      • Structural Directives
        • ngForTemp
        • ngSwitch
        • ngFor
        • ngIf
      • Attribute Directives
        • temp
        • ngClass
        • ngStyle
    • Routing
      • Routing in Angular
      • Setting up basic routing
      • routerLink and routerLinkActive
      • router.navigate and ActivatedRoute
      • Route Params as Observables
      • redirectTo
      • relativeTo
      • pathMatch
      • ActivatedRoute
      • Routing in Angular
      • Passing Data with Route
      • Route Parameters
    • Intercept HTTP request
    • Custom Directives
    • Communication between components
    • Angular Modules
    • Reactive Forms
    • Unit Testing
      • TestBed and component fixture
      • Testing HttpClient requests
      • Testing fakeAsync
  • GraphQL
    • Introduction
    • Server
    • Client Side
    • GraphQL in Angular
    • Queries
      • temp
      • query with parameters
      • aliases
      • fragments
      • @include directive
      • @skip directive
      • variables
      • Inline Fragments
  • CSS
    • What is Box model?
    • display: block, inline or inline-block
    • CSS Selector: Combinators
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS3 Filter
    • CSS3 Transitions
    • Media Queries
    • Flex vs Grid
    • CSS 3 Grids
    • What is Flexbox?
    • position: relative vs absolute
  • SASS
    • Mixins
    • Lists
    • Maps
  • RxJS
    • throttle vs debounceTime
    • distinctUnitChange
    • reduce vs scan
  • Typescript
    • Typeguards
    • Pattern Matching with Typescript
    • TS Decorators
    • Using LINQ in TS
  • NodeJS
    • NodeJS Security Checklist
    • What is Node.js
  • REACT
    • React - VDOM - Under the hood
    • Synthetic events in React
    • Routing - React Router 4
    • React Custom hook
    • Higher-Order Component
    • REDUX
    • Redux Thunk vs Redux Saga
    • forceUpdate()
    • Storing Data in React
    • Error Handling
    • React Context
    • How React-Native works
    • refs
    • Server-side Rendering
    • Jest setup file
    • React-test-renderer
    • Lifecycle
    • React Testing Library
    • React Query
  • JWT
    • What is JWT and How it works
Powered by GitBook
On this page
  • TypeDefs / Schema
  • Resolvers
  • Make Executable Schema
  • Set up Express to use graphQLExpress middleware
  1. GraphQL

Server

PreviousIntroductionNextClient Side

Last updated 5 years ago

GraphQL's server side setup has following important components:

  1. typeDefs - Type definitions aka schema of your data models and shapes/contract defs of your queries and mutations. (Think of Queries and Mutations as your GraphQL server's endpoints. Queries are for GET, Mutations can be for PUT or POST.)

  2. resolvers - functions/code for your queries and mutations. These function signature should match with the signature that you have defined in your queries/mutations schema. In these functions, you write code for how or where to get or post data, and then resolve/customize/massage the response data as defined in the typeDefs of data models. ( for example a resolve function could contain a MongoDB/Mongoose find statement to query some data or even could be an Axios call to query some external REST API endpoint)

TypeDefs / Schema

type definitions of data models, queries and mutations:

  • are written in .

  • are first written in a templated string format (within a pair of backticks (`...`)

 const typeDefs = [`
  type UserDetails {
    id: String
    name: String
    email: String
  }

  // Query(GET) endpoints typedefs go inside the parent type `Query`
  type Query {
     UserDetails: UserDetails
  }

  // Mutations(PUT/POST) endpoints typedefs go inside the parent type `Mutation`
  type Mutation {
   UserEmail(id: String!, email: String!): Channel
  }
`];

Resolvers

const resolvers = {
  Query: {
    UserDetails ({ id }, context) {
       return request('GET')
         .from(await route(`user/${id}`))
         .send<{ UserDetails }>()
         .then((res) => res.data.user)
         .catch((err) => {
            // throw error
       });
    }
  },
  Mutation: {
    UserEmail: (args) => {

      { id, email } = args;
      const res = request('PUT')
                 .from(`user/${id}`)
                 .withData({email})
                 .send();
      return {
        ...res.data.email,
        id: id
      };
   }
  },
};

Make Executable Schema

Once you have typeDefs and Resolvers set up, you make a executable schema that GraphQL can execute using the graphql-tools's makeExecutableSchema function:

// schema.ts

import typeDefs from './schema';
import resolvers from './resolvers';

const schema = makeExecutableSchema({ typeDefs, resolvers });

Set up Express to use graphQLExpress middleware

Once we have our executable schema ready, we can provide it to graphQLExpress to set it as a middleware for our node Express server:

server.use('/graphql', bodyParser.json(), graphqlExpress({
  schema
}));

//also set up the endpoint for the `GraphiQL` query editor tool:
server.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql'
}));

This is server side setup for GraphQL in brief. Next we'll set the client side setup needed for GraphQL

GraphQL Schema Language