DEV Community

MANOJ AP
MANOJ AP

Posted on • Updated on

Nuxt graphql server-middleware API

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

npx prisma init
Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

nmp i -s @prisma/client
Enter fullscreen mode Exit fullscreen mode

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.

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
  };

Enter fullscreen mode Exit fullscreen mode

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.

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.

 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



Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
manojap profile image
MANOJ AP • Edited

Sorry for being late for share the Sandbox

codesandbox.io/s/nuxt-api-prisma-a...