Nuxt graphql server-middleware API
Tags: nuxt, graphql, api, apollo
Published: 2021-07-27 03:48:06

## 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*

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

```javascript
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.

```javascript
//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**

```bash
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. 

```bash
// run in new terminal
npmx prisma studio
```

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

```bash
nmp i -s @prisma/client
```

## Graphql API

In the Nuxt app , we can setup internal API for interacting with database using server middleware.
In the project folder create a folder **api** and inside the folder create a file **graphql.ts**

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

```javascript
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const {PrismaClient} = require("@prisma/client") 
const prisma = new PrismaClient();
const typeDefs = gql`

   type Todo{
        item:String!,        
        id:String
   }

   type Query{
       getAll: [Todo!]!
   }

   type Mutation{
       newTodo(item :String!):Todo
   } 
`;

const resolvers = {
    Query: {
        getAll() {
            return   prisma.todo.findMany();
        }
    },

    Mutation: {
      async  newTodo(_parent: any, _args: any) {
         
          const newTodo = await prisma.todo.create({
              data:_args
          });
            return newTodo;
        }
    }
};
const server = new ApolloServer({
typeDefs,
resolvers
});

const app = express();
server.start().then((r: any) => {
    server.applyMiddleware({ app });    
});

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

## typeDefs

typedefs constant contains graphql type definitions, Query and Mutations, it can be a user defined objects with multiple keys. For a complete data type list refer the official [documentation](https://graphql.org/learn/).

### Query

As the name suggest the query is used to fetch some data, it uses the array synatax to fetch data.

### Mutations

Mutations are for defining graphql part of create,update,delete functions.

## Resolvers

So the first part of our graphql is done with type,query and Mutations. But this is not enough, these are structures, we have to make them working, with resolver function.
Resolvers are function to make the Query and Mutation in motion. 

## 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.

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

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

 

 ```