Next.js Discord

Discord Forum

Need help connecting to graphQL server

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Brown bearOP
I have been stuck trying to connect graphql up with next.js server.
// src/app/api/graphql/page.ts
import { resolvers } from '../../../../graphql/resolvers'
import { typeDefs } from '../../../../graphql/schema'
import { createSchema, createYoga } from 'graphql-yoga'
import type { NextApiRequest, NextApiResponse } from 'next'

export default createYoga<{
    req: NextApiRequest
    res: NextApiResponse
  }>({
    schema: createSchema({
      typeDefs,
      resolvers
    }),
    graphqlEndpoint: '/api/graphql'
})


I get thrown this error
Error: Cannot read properties of undefined (reading 'endsWith')

2 Replies

Brown bearOP
// resolvers.ts
const prisma = new PrismaClient();

export const dateScalar = new GraphQLScalarType({
  name: 'Date',
  description: 'Date custom scalar type',
  serialize(value) {
    if (value instanceof Date) {
      return value.getTime(); // Convert outgoing Date to integer for JSON
    }
    throw Error('GraphQL Date Scalar serializer expected a `Date` object');
  },
  parseValue(value) {
    if (typeof value === 'number') {
      return new Date(value); // Convert incoming integer to Date
    }
    throw new Error('GraphQL Date Scalar parser expected a `number`');
  },
  parseLiteral(ast) {
    if (ast.kind === Kind.INT) {
      // Convert hard-coded AST string to integer and then to Date
      return new Date(parseInt(ast.value, 10));
    }
    // Invalid hard-coded value (not an integer)
    return null;
  },
});

export const resolvers = {
    Date: dateScalar,
    Query: {
      getUser: async (_: any, args: { id: number }) => {
        return await prisma.user.findUnique({
          where: { id: args.id },
          include: { cars: true, trips: true },
        });
      },
      getCars: async () => {
        return await prisma.car.findMany();
      },
      getTrips: async () => {
        return await prisma.trip.findMany();
      },
    },
    // ... other resolvers for relationships
  };
//scheme.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export const typeDefs = `
scalar Date

type User {
    id: Int!
    email: String!
    firstName: String
    lastName: String
    host: Boolean
    cars: [Car!]
    trips: [Trip!]
  }
  
  type Car {
    id: Int!
    make: String
    totalTrips: Int
    address: String
    model: String
    rating: Int
    image: [String]
    owner: User
    trips: [Trip!]
  }
  
  type Trip {
    id: Int!
    startDate: Date
    endDate: Date
    rating: Int
    review: String
    car: Car
    user: User
  }
  
  type Query {
    getUser(id: Int!): User
    getCars: [Car!]
    getTrips: [Trip!]
  }
`