Last active
July 26, 2021 15:18
-
-
Save devmnj/54524a6316d06857aa147d6f03274056 to your computer and use it in GitHub Desktop.
Create Nuxt apollo-graphql server with Apollo, Express, and Prisma using serverMiddleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Create a folder , api/graphql.ts (root of peoject) and paste the following code*/ | |
| 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 | |
| }; | |
| /* Add a middle ware in Nuxt-config*/ | |
| export default { | |
| // Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode | |
| ssr: false, | |
| serverMiddleware:[ | |
| '~/api/graphql.ts' | |
| ] , | |
| ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment