Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nest JS: Object is possibly 'undefined' in GraphQL #265

Open
aldoprogrammer opened this issue Aug 29, 2023 · 0 comments
Open

Nest JS: Object is possibly 'undefined' in GraphQL #265

aldoprogrammer opened this issue Aug 29, 2023 · 0 comments

Comments

@aldoprogrammer
Copy link

aldoprogrammer commented Aug 29, 2023

I tried to make the subscription update course in the nest js, but it turns out error Object is possibly 'undefined' in this line of code const course = await this.courseService.findOne({ id: variables.courseId }); below is my course.resolver.ts

@Subscription('courseUpdated', {
    resolve: (value) => value,
    filter: async (payload, variables) => {
      const course = await this.courseService.findOne({ id: variables.courseId });
      if (!course) {
        throw new NotFoundException('Course not found');
      }
      if (course.creatorId !== variables.userId) {
        throw new ForbiddenException('Course not owned by you');
      }
      return payload.courseId === variables.courseId;
    },
  })
  courseUpdated(
    @Args('courseId') courseId: string,
    @Args('userId') userId: string,
  ) {
    return pubSub.asyncIterator(`course:${courseId}`);
  }

Here is the piece of code in my course.graphql

type Course {
  id: String
  title: String
  objective: [String!]
  description: String!
  language: String
  category: String!
  tone: String!
  modality: String!
  classSize: String!
  topics: [String!]
  duration: Int!
  durationLesson: Int!
  creatorId: String!

  outline: CourseOutline
  detailedOutline: CourseDetailedOutline

  createdAt: DateTime!
  updatedAt: DateTime!

  audience: Audience!
}

input UpdateCourse {
  title: String
  objective: [String!]
  description: String
  language: String
  category: String
  tone: String
  modality: String
  classSize: String
  topics: [String!]
  duration: Int
  durationLesson: Int
  audience: CreateAudienceInput

  outline: UpdateCourseOutline
  detailedOutline: UpdateCourseDetailedOutline
}

type Subscription {
     courseUpdated(courseId: String!): Course!
    }

I read a lot on stackoverflow but still couldn't solve it. Yes indeed some of the value is optional, but how to solve it. I also tried the chaining option like this const course = await this.courseService.findOne({ id: variables.courseId })?.id; but still does not work

System:

 "graphql-subscriptions": "2.0.0",
"@nestjs/cli": "^10.1.16",
"@nestjs/graphql": "^12.0.8"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant