Nest js - QueryFailedError: неверный синтаксис ввода для типа uuid - PullRequest
0 голосов
/ 10 марта 2020

У меня есть этот метод, который должен возвращать все сообщения от всех пользователей. Обычно пытается это сделать Select * from posts

  /**
   * Find all posts 
   */
  async findAll(): Promise<Post[]> {
    try {
      return await await getConnection()
      .createQueryBuilder()
      .select("posts")
      .from(Post, "posts").getMany();
    } catch (error) {
      throw new Error(error)      
    }
  }

Когда вызывается этот метод, это ответ от TypeORM

QueryFailedError: invalid input syntax for type uuid: "findAll"

Вывод запроса

SELECT DISTINCT
   "distinctAlias"."Post_post_id" as "ids_Post_post_id" 
FROM
   (
      SELECT
         "Post"."post_id" AS "Post_post_id",
         "Post"."uid" AS "Post_uid",
         "Post"."title" AS "Post_title",
         "Post"."sub_title" AS "Post_sub_title",
         "Post"."content" AS "Post_content",
         "Post"."userUserId" AS "Post_userUserId",
         "Post__comments"."comment_id" AS "Post__comments_comment_id",
         "Post__comments"."content" AS "Post__comments_content",
         "Post__comments"."postPostId" AS "Post__comments_postPostId",
         "Post__comments"."userUserId" AS "Post__comments_userUserId" 
      FROM
         "posts" "Post" 
         LEFT JOIN
            "comments" "Post__comments" 
            ON "Post__comments"."postPostId" = "Post"."post_id" 
      WHERE
         "Post"."post_id" = $1
   )
   "distinctAlias" 
ORDER BY
   "Post_post_id" ASC LIMIT 1

Вот моя схема

Сообщений

/**
 * Post Entity
 */
@Entity('posts')
export class Post {
  @PrimaryGeneratedColumn('uuid') post_id: string;
  @Column({ type: 'varchar', nullable: false, unique: true }) uid: string;
  @Column('text') title: string;
  @Column('text') sub_title: string;
  @Column('text') content: string;
  @ManyToOne(
    type => User,
    user => user.posts,
    {
      cascade: true,
    },
  )
  user: User;
  @OneToMany(
    type => Comment,
    comment => comment.post,
    {
      cascade: true,
    },
  )
  comments: Comment[];

  constructor(title?: string, content?: string) {
    this.title = title || '';
    this.content = content || '';
  }

  @BeforeInsert() async generateUID() {
    this.uid = uuid();
  }
}

Пользователи

/**
 * User Entity
 */
@Entity('users')
export class User {
  @PrimaryGeneratedColumn('uuid') user_id: string;
  @Column({ type: 'varchar', nullable: false, unique: true }) uid: string;
  @Column({ type: 'varchar', nullable: false }) name: string;
  @Column({ type: 'varchar', nullable: false, unique: true }) email: string;
  @Column({ type: 'varchar', nullable: false, unique: true }) username: string;
  @Column({ type: 'varchar', nullable: false }) password: string;

  @OneToMany(
    type => Post,
    post => post.user,
    {
      eager: true,
    },
  )
  posts: Post[];
  @OneToMany(
    type => Comment,
    comment => comment.user,
  )
  comments: Comment[];

  constructor(name?: string, posts?: []);
  constructor(name?: string) {
    this.name = name || '';
  }

  @BeforeInsert() async hashPassword() {
    this.password = await bcrypt.hash(this.password, 10);
    this.uid = uuid();
  }
}

Комментарии

/**
 * Comments Entity
 */
@Entity('comments')
export class Comment {
  @PrimaryGeneratedColumn('uuid') comment_id: string;
  @Column('text') content: string;
  @ManyToOne(
    type => Post,
    post => post.comments,
  )
  post: Post;
  @ManyToOne(
    type => User,
    user => user.comments,
  )
  user: User;
}

Почему это происходит? Почему существует предложение where, если оно не указано?

Версия TypeORM: ^ 0.2.22 TypeScript: ^ 3.7.4

1 Ответ

0 голосов
/ 10 марта 2020

Очевидно, что ku sh в этих частях является мощным, и я не читаю свой собственный код ..

в post.controller.ts, в декораторе @Get() отсутствует ключевое слово find и мой запрос выглядел так:

http://localhost:3000/posts/find, где find не был определен в контроллере как маршрут

, решение было добавить @Get('find') из nestjs/common

Post.controller.ts

  /**
   * Get all posts from all users
   */
  @Get('find')
  @ApiCreatedResponse({
    status: 201,
    description: 'All posts have been successfully retreived.',
    type: [PostDTO],
  })
  @ApiResponse({ status: 403, description: 'Forbidden.' })
  async find() {
    try {
      return this.postService.findAll();
    } catch (error) {
      throw new Error(error);
    }
  }

Post.service.ts

 /**
   * Find all posts 
   */
  async findAll(): Promise<Post[]> {
    const posts = await this.postRepository.find();
    return posts;
  }

PS. Я добавлю теги nest js, так как это связано с ними больше, чем с TypeORM или PG

...