Схема GraphQL не обновляется с помощью Nest JS (подход с первым кодом) - PullRequest
0 голосов
/ 03 мая 2020

Довольно плохо знаком с GraphQL, у меня возникла проблема с последней версией Nest JS, в которой я сейчас пытаюсь добавить мутацию в распознаватель, которая не отображается на игровой площадке во время работы сервера.

Похоже, что схема GraphQL не обновляется при запуске сервера.

Мутация createUser отображается на площадке GraphQL и работает, а getUsers (созданная для тестирования) не отображается.

Буду признателен за любую подсказку о том, как решить эту проблему.

Импорт GraphQLMOdule в app.module

import { Module } from '@nestjs/common';
// Libraries
import { TypeOrmModule } from '@nestjs/typeorm';
import { GraphQLModule } from '@nestjs/graphql';
// App modules
import { MealModule } from './meal/meal.module';
import { AuthModule } from './auth/auth.module';
// Entities
import { MealEntity } from './meal/meal.entity';
import { UserEntity } from './auth/user.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mongodb',
      url: 'mongodb://localhost/sideproject',
      synchronize: true,
      useUnifiedTopology: true,
      entities: [MealEntity, UserEntity],
    }),
    GraphQLModule.forRoot({
      autoSchemaFile: true,
      debug: true,
      playground: true
    }),
    MealModule,
    AuthModule,
  ],
})
export class AppModule {}

Вот типы пользовательских модулей, с которыми я сталкиваюсь трудности с:

import { ObjectType, Field, ID } from '@nestjs/graphql';

@ObjectType('User')
export class UserType {
  @Field(() => ID)
  id: string;

  @Field()
  username: string;

  @Field()
  email: string;

  @Field()
  password: string;
}

Связанный преобразователь:

import { Resolver, Mutation, Args, Query } from '@nestjs/graphql';
import { UserType } from './types/user.types';
import { CreateUserInputType } from './inputs/create-user.input';
import { UserEntity } from './user.entity';
import { AuthService } from './auth.service';

@Resolver(of => UserType)
export class AuthResolver {
  constructor(private authService: AuthService) {}

  @Mutation(returns => UserType)
  signUp(
    @Args('createUserInput') createUserInput: CreateUserInputType,
  ): Promise<UserEntity> {
    return this.authService.signUp(createUserInput);
  }

  @Query(returns => [UserType])
  getUsers(): Promise<UserEntity[]> {
    return this.authService.getUsers()
  }
}

Служба:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateUserInputType } from './inputs/create-user.input';
import { UserRepository } from './user.repository';
import { UserEntity } from './user.entity';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(UserRepository)
    private userRepository: UserRepository,
  ) {}

  signUp(createUserInput: CreateUserInputType): Promise<UserEntity> {
    return this.userRepository.signUp(createUserInput);
  }

  async getUsers(): Promise<UserEntity[]> {
    return await this.userRepository.find();
  }
}

И, наконец, хранилище для пользовательского модуля:

import { Repository, EntityRepository } from 'typeorm';
import { UserEntity } from './user.entity';
import { InternalServerErrorException } from '@nestjs/common';
import { CreateUserInputType } from './inputs/create-user.input';

import { v4 as uuid } from 'uuid';
import * as bcrypt from 'bcryptjs';

@EntityRepository(UserEntity)
export class UserRepository extends Repository<UserEntity> {
  async signUp(createUserInput: CreateUserInputType): Promise<UserEntity> {
    const { username, email, password } = createUserInput;

    const user = this.create();
    user.id = uuid();
    user.username = username;
    user.email = email;
    user.password = bcrypt.hashSync(password, bcrypt.genSaltSync(12));
    try {
      return await this.save(user);
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException();
    }
  }
}

Большое спасибо!

...