Create a Apollo graphql server in Nodejs

How to configure and setup graphql with Apollo package in Nodejs


Apollographql help use to create graphql server in Nodejs with inbuilt features. The setup was quick and easy to implement.

Node setup

As a first step we need to create a nodejs project, install dependencies, create scripts to run the project.

In the terminal CD into your project folder and run

npm init -y or npm init

Open the folder in VS Code using code . from the terminal and add following script to package.json file.

  "scripts": {
   
    "start": "nodemon src/index.js",
    "start:ci": "node src/index.js"
  },

Dependenciess

We need to add three dependencies to package.json and run npm install or manually install them using npm install command.

 "dependencies": {
    "apollo-server": "^3.6.3",
    "graphql": "^16.3.0",
    "nodemon": "^2.0.15"
  }

Entry point

Our entry point file is index.js which setup our graphql server.

const {ApolloServer} =require('apollo-server');
const typeDefs =require('./schema'); 

const server = new ApolloServer({typeDefs});
server.listen().then(({url}) => {
    console.log(`
    Server is running!
    Listening on port ${url}
    Query @ http://studio.apollographql.com/dev
    `);
})

In the index.js we created instance of ApolloServer , initialize it with schema which shape our data.

Schema

In the source folder create schema definition and export it.

const {gql}=require('apollo-server')

const typeDefs=gql`
type Query{
    "Query to get all books"
    booksForLib:[Book!]
    }

type Book{
    id:ID!
    author:String!
    title:String!
    language:String
}
`;

module.exports= typeDefs;

Here we have two type , Query and Book. The Book define the book type and Query define the Output of the query.

! indicate it is non nullable object and [ ] indicates it is list of objects.

Let’s build some mock data.

In the index file add mock data and pass it to the, server object as follows

const {ApolloServer} =require('apollo-server');
const typeDefs =require('./schema');

const mocks={
    Query:()=>({
       booksForLib: [...new Array(5)],
    }),
    Book:()=>({
 id:()=>'isbn_1',
author:()=>'JDoe',
title:()=>'Some title'
    })
};

const server = new ApolloServer({typeDefs,mocks});
server.listen(4001).then(({url}) => {
    console.log(`
    Server is running!
    Listening on port ${url}
    Query @ http://studio.apollographql.com/dev
    `);
})

Let’s run the server

npm start

Apollo port

The default port for Grapgql is 4000 , we can pass a different port to the listen method of server object.

We can use the studio / play ground to evaluate our graphql.

What is lack, live data, resolvers and we will cover it in the next post.

Implement react-query mutation

How to implement react query mutations


React-query mutations , which perform create,update,delete operations on data easy to setup and invalidate query.

Preparing the create method

Usually it is done with API route, lets tear the mutation into two part the API createUser method and the Mutation.

export const createUser = async (usr:User) => {
  const res = await fetch('http://localhost:3000/api/users', {
    method: "POST",
    body: JSON.stringify(usr),
    headers: {
      'Content-Type': 'application/json'
    }
  });

The mutation

Mutation can be create inside a functional component by using useMutation hook and our createUser helper function.

import {createUser } from '../hooks'
import { useMutation } from 'react-query';
.....

   const mutation = useMutation((formData) => {
        return createUser(formData)
    });

Use mutation and mutate as follows.

const usr = { name: values.name, email: values.email, cId: values.cid, lId: values.lid, secret: values.secret }
         
       
        mutation.mutate(usr, {
            onSuccess: () => {
                
                console.log('success');
            }

We can use onSuccess function to implement our invalidation logic. Also it is possible to render logics such as

 return (
     <div>
       {mutation.isLoading ? (
         'Adding User...'
       ) : (
         <>
           {mutation.isError ? (
             <div>An error occurred: {mutation.error.message}</div>
           ) : null}
 
           {mutation.isSuccess ? <div>Todo added!</div> : null}
 
            
         </>
       )}
     </div>
   )

Hope this will help someone

Setup Redux store in Reactjs


A global store is essential for app when the work base is dramatically growing, or it working a static environment. For vuejs Vuex store fill the gap. For react everybody talk about Reudx.

Redux little bit complicated,reducers,actions,state,store, lots of thing has to be managed. Redux also have another tool called redux-toolkit which is a helper class for managing redux store.

So where to start ?

As the first step install the basic dependencies and react base project (I skip the react part and leave it for you).

# Yarn
yarn add @reduxjs/toolkit

Folder and files needed

Redux didn’t bother about the folder structure of the store, create a folder redux and inside the folder, create store.js and sliceFile.js

Slice

createSlice method of redux-toolkit will automatically create actions and export state for us. Let’s configure reducer, which is the basic functions and a global state for the store. So let’s create the slice

import { createSlice } from "@reduxjs/toolkit"
 

export const hitSlice = createSlice({
  name: "hit",
  initialState: {
    hitCount: 0,
    isWorking: true
  },
  reducers: {
     setHitCount: (state, action) => {
      state.hitCount=action.payload
       )
    }
  },
  extraReducers: builder => {
    
      
  }
}
)

 
export default hitSlice.reducer


So in our slice we had a hitCount state and reducer to set the hits, that’s all.

Configure the Store

Lets import the reducer from the slice we just made, a minimum setup is required.

//redux/store.js
import { configureStore } from "@reduxjs/toolkit";

import hitReducer from "./hitCounter";
 

export default configureStore({
  reducer: { hits: hitReducer, 
      },
});

Our store just finished, and note that we didn’t export the state. In the index.js (in the root of the project) file we have to configure the redux provider and store, so that state will be available for all the components.

import React from 'react';
import ReactDOM from 'react-dom'; 
import App from './App';
import store from './redux/store';
import {Provider} from 'react-redux'
 
 

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
 

Accessing the state

In the components we can access the with useSelector hook as follows

import { useSelector} from 'react-redux'
... 
const {hits} = useSelector(state =>state.hits);

Accessing reducers/methods

Remember the setHitCount method we created , we have to use useDispatch hook to invoke the reducer function.

import { useDispatch } from 'react-redux'
import {setHitCounter} from './redux/hitCounter'
..
const dispatch = useDispatch();
dispatch(setHitCounter(3))
const {hits} = useSelector(state =>state.hits);

The hits is reactive in nature, when ever we change the state, all the app components will also get updated.

Async Call

It’s is often require that asynchronously fetching data from an API, redux can perform this using createThunk function. I saved the topic for next post

Using Slatejs Editor in Vue

How to implement slatejs editor library in Vuejs apps


Slatjs is Editor library which enable developers to use rich customizable editor capability in web apps. The library come to Reactjs first approach. So how do I use it in a Vuejs app ?

Slatejs is customizable editor, comment sections in a web app. It is one of the alternative for Draftjs which was used in Facebook comment.

slate-vue

slate-vue is react alternative library for slatejs, you can download and use the plugin in Vuejs. Almost every slatejs feature which available in react can use in Vuejs too.

yarn add salte-vue 
or
npm i -s slate-vue

Usage

Plugin

In the main.js include the plugin

import Vue from "vue";
import App from "./App.vue";
import { SlatePlugin } from 'slate-vue';

Vue.config.productionTip = false;
Vue.use(SlatePlugin)
new Vue({
 render: (h) => h(App),
}).$mount("#app");

Component usage

In the component import the Slate and Editable with Initial values as nodes. You can find detailed usage of Slatejs in official docs and in the slate-vue docs.

<template>
 <div id="app">
 <Slate :value="value">
   <Editable  placeholder="Enter some plain text..."></Editable>
 </Slate>
 </div>
</template>

<script>

 import {Slate, Editable} from 'slate-vue'
 const initialValue = [
  {
     children: [
      { text: 'This is editable plain text, just like a <textarea>!' },
    ],
  },
]
export default {
 name: "App",
   components: {
     Slate,
     Editable
  },
   data() {
     return {
       value: JSON.stringify(initialValue)
    }
  }
};
</script>

The editable component allow us to use interactive Ritch text editor in our application which is a child component to the Slate component.

Using nuxt.config in Keystone Nuxt-App

How to use Nuxt config in Keystone app


Using the create-key-5-app we can create a boilerplate template for our Nuxt-Keystone app. It automatically configure the folder structure, pacakge.json and src folder where our regular Nuxt app resides.

Also there is a index.js file which is the entry point to the app. We can set up the project manually and then add scripts, dependencies, entry point file, index.js.

Keystone and index.js

@kestonejs/nuxt-app works through the configuration specified in the export. We can use the config object for specify nuxt configurations such as middleware, plugins, env etc.

//as object
....
const config = {
  srcDir: 'src/',
  buildDir: 'dist',
  env:{
    URI:process.env.API
  },
  router:{
    middleware:'Identity'
  },
   buildModules:['@nuxtjs/tailwindcss'],      
  components:true
 
};

module.exports = {
 keystone,
 apps: [new GraphQLApp(), new AdminUIApp(), new NuxtApp(config)],
};

Or we can prepare our nuxt.config as follows and import @ keystone index.js file as follows

//nuxt.config.js
require('dotenv').config()
const config= {
 srcDir: 'src/',
 buildDir: 'dist',
 router: {
   middleware: 'Identity'
},
 
 target: 'static',  
 
 env:{
   URI:proccess.env.API
},
 ....
}
module.exports =config;
//index.js
....
const config= require("./nuxt.config")

module.exports = {
 keystone,
 apps: [new GraphQLApp(), new AdminUIApp(), new NuxtApp(config)],
};

Following Keystone post may help you learn more

Create API with Prisma + Express + Server Middle Ware in Nuxt

Create a API using serverMiddleware , Prisma and Express in Nuxtjs


Setup Prisma ORM for Nuxtjs project

An API requires special server middleware in nuxt, also we need to create a custom route, express framework will help us manage the route, Prisma ORM, a minimal configurable mapper for managing database.

Prisma is a ORM for JavaScript and Typescript, it let developers easily configure, create / migrate databases using models. One of the cool feature I love mostly is that , it can be configured with few CLI commands like init, migrate

View and Run the code @ sandbox

Setup Prisma

For initializing the Prisma install the developer dependency npm i -d prisma and initialize prisma with

npx prisma init

It will generate necessary files under Prisma folder, please open the file and configure database and models. For demonstration I have configured a Sqlite database, you can use other databases like mysql, postgres, Mongodb etc.

//schema.prisma

datasource db {
 provider = "sqlite"
 url      = "file:./dev.db"
}

generator client {
 provider = "prisma-client-js"
}

model Contact{
 id String @id @default(uuid())
 name String
 email String
}
 

Note the id field in the model, it is a primary key and also auto filled by the uuid() function. One you done models go to generate the real database with migrate command

npx prisam migrate dev --name init

This will generate the tables using the models we defined, to make sure we can use the prisma studio which runs on the port 555, also a standalone studio app is available.

In the future we can modify and rerun the migrate command for updating the tables, which will drop the tables and re-create for us.

// run in new terminal
npmx prisma studio

How to use in our Nuxtjs app

In the nuxtjs app we need the dependency @prisma/client, let’s add them to our project

nmp i -s @prisma/client

In the Nuxt app , we can setup internal API for interacting with database using server middleware.

API routes

In the project folder create a folder api and inside the folder create a file index.ts

For create routes, we can use the express framework the API should export the handler as in Nextjs.

index.ts
import express from "express";
import { PrismaClient, Todo } from "@prisma/client";
const app = express();
const prisma = new PrismaClient();
app.use(express.json());

app.get("/", (req, res) => {
 res.json("Wlcome to API");
});

app.get("/todos", async (req, res) => {
 const todos = await prisma.todo.findMany();
 res.json(todos);
});

export default {
 path: "/api",
 handler: app
};

Nuxt-config

For using Prisma client we need to use PrismaClient object. The API would not work at this point, it also required setup a middleware in the dedicated nuxt-config.

export default {
 // Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
 ssr: false,
 serverMiddleware:[
   '~/api/index.ts',
] ,  
   .....

and now the api can be accessed at http://localhost:3000/api

Setup Prisma ORM for Nextjs

How to setup Prsma ORM for React and Nextjs projects


Prisma is a ORM for JavaScript and Typescript, it let developers easily configure, create / migrate databases using models. One of the cool feature I love mostly is that , it can be configured with few CLI commands like init, migrate

Setup Prisma

For initializing the Prisma install the developer dependency npm i -d prisma and initialize prisma with

npx prisma init

It will generate necessary files under Prisma folder, please open the file and configure database and models. For demonstration I have configured a Sqlite database, you can use other databases like mysql, postgres, Mongodb etc.

//schema.prisma

datasource db {
 provider = "sqlite"
 url      = "file:./dev.db"
}

generator client {
 provider = "prisma-client-js"
}

model Contact{
 id String @id @default(uuid())
 name String
 email String
}
 

Note the id field in the model, it is a primary key and also auto filled by the uuid() function. One you done models go to generate the real database with migrate command

npx prisam migrate dev --name init

This will generate the tables using the models we defined, to make sure we can use the prisma studio which runs on the port 555, also a standalone studio app is available.

In the future we can modify and rerun the migrate command for updating the tables, which will drop the tables and re-create for us.

// run in new terminal
npmx prisma studio

How to use in our Nextjs app

In the nextjs app we need the dependency @prisma/client, let’s add them to our project

nmp i -s @prisma/client

In our React file we can now create prisma object and call the fetch method which will get the data from database. Usually we done the fetching with getStaticProps method in React.

//index.js

export async function getStaticProps() {
 const contacts = await prisma.contact.findMany();
 return {
   props: {
     initialContacts: contacts,
  },
};
}

export default function Home({initialContacts}) {
const [contacts, setcontacts] = useState(initialContacts);
....

In the similar way, we can use them in API or graphql end points too.

Create API with Apollo + graphql + Prisma + Express in Nuxt

How to create a API with Apollo, graphql, Prisma and express


Graphql

Graphql is modern an alternative approach for the REST API invented by Facebook. It is used for fetch data from a server and put data back to a server , just like the regular API does.

The Graphql shines where you want to fetch few data (required), where REST API fetch a bunch of data, it may cause fetching too much data. API have multiple end points where graphql have one. One of the problem with graphql, it is not simple to create a graphql server, even though once it has been done ,using them is quiet simple.

Apollo and Express

With Apollo server we can build and run a graphql server, for creating route for our graphql end point can utilize the node developers favorite express module

Prisma

Prisma is a ORM for JavaScript and Typescript, it let developers easily configure, create / migrate databases using models. One of the cool feature I love mostly is that , it can be configured with few CLI commands like init, migrate

Setup Prisma

For initializing the Prisma install the developer dependency npm i -d prisma and initialize prisma with

npx prisma init

It will generate necessary files under Prisma folder, please open the file and configure database and models. For demonstration I have configured a Sqlite database, you can use other databases like mysql, postgres, Mongodb etc.

//schema.prisma
​
datasource db {
  provider = "sqlite"
  url      = "file:./dev.db"
}
​
generator client {
  provider = "prisma-client-js"
}
​
model Todo{
  id String @id @default(uuid())
  item String
  
}
  

Note the id field in the model, it is a primary key and also auto filled by the uuid() function. One you done models go to generate the real database with migrate command

npx prisam migrate dev --name init

This will generate the tables using the models we defined, to make sure we can use the prisma studio which runs on the port 555, also a standalone studio app is available.

// run in new terminal
npmx prisma studio

In the nuxtjs app we need the dependency @prisma/client, let’s add them to our project

nmp i -s @prisma/client

How to create a Apollo-graphql-server in Nodejs

How to setup a graphql server using Apollo framework and express


Graphql is an alternative approach for the REST API invented by Facebook. It is used for fetch data from a server and put data back to a server , just like the regular API does.

The Graphql shines where you want to fetch few data (required), where REST API fetch a bunch of data, it may cause fetching too much data. API have multiple end points where graphql have one. One of the problem with graphql, it is not simple to create a graphql server, even though once it has been done ,using them is quiet simple.

Play with full code + Graphql Playground in Sandbox

Apollo and Express

With Apollo server we can build and run a graphql server, for creating route for our graphql end point can utilize the node developers favorite express module

Dependencies and Setup

To get started we need to create a folder project and then cd into the folder npm init -y for generating pacakge.json.

We also need to install few Apollo dependencies along with express.

npm i -s apollo-server apollo-core express nodemon

nodemon help us to detect changes and automatically restart server for us.

let’s open the folder in VS Code and create a index.js file ( in root directory ) and also create a script in package.json for running the server as follows

//package.json
"scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "start": "nodemon ./index.js"
},

Mock Data

We also have users list which is used to show some mock data create users.js files with following content in the project root.

//users.js
const users =[
  {
       name:"Dev",
       role: "DBA",
       id:1
  },
  {
       name:"Jhon Doe",
       role: "Admin",
       id:2
  },
  {
       name:"Martin",
       role: "Dev",
       id:3
  }
]
module.exports = users;

How to use GitHub Packages in node project

How to use github package in Node project


Every repo in GH have package link where you find the package. To use a package from GitHub package add the .npmrc file in the root of the project and include the dependency in package.json

.npmrc

This file tell the npm what registries you are using , along side npm registry.

//.npmrc

@OWNER:registry=https://npm.pkg.github.com

Replace the OWNER with organization / user name and add install all the dependencies

npm intsall

following npm posts may help you

​
​