NodeJS 如何提高查询的性能?

i34xakig  于 2023-05-06  发布在  Node.js
关注(0)|答案(1)|浏览(133)

我有一个函数,首先提取所有找到的目录并按字母顺序排序,然后提取所有其他不是目录的数据并按字母顺序排序,最后将它们组合起来。

@Get('roots')
  async findRoots(@Req() request: Request) {
    const user = await this.authService.findCurrentUser(request);
    const directories = await this.fileService.findAll({
      relations: ['user', 'parent', 'parent.parent'],
      order: {
        name: 'ASC',
      },
      where: {
        user: user.user_id,
        parent: IsNull(),
        type: 'dir',
      },
    });
    const otherFiles = await this.fileService.findAll({
      relations: ['user', 'parent', 'parent.parent'],
      order: {
        name: 'ASC',
      },
      where: {
        user: user.user_id,
        parent: IsNull(),
        type: Not('dir'),
      },
    });
    return directories.concat(otherFiles);
  }

但我不喜欢必须执行两个查询的事实。有没有可能通过一个请求来实现这一点?

aurhwmvo

aurhwmvo1#

您可以简单地从WHERE条件中删除type

@Get('roots')
  async findRoots(@Req() request: Request) {
    const user = await this.authService.findCurrentUser(request);
    const directoriesAndFiles = await this.fileService.findAll({
      relations: ['user', 'parent', 'parent.parent'],
      order: {
        name: 'ASC',
      },
      where: {
        user: user.user_id,
        parent: IsNull(),
      },
    });
    return directoriesAndFiles;
  }

如果你想在文件之前使用目录,我建议你在代码中进行分离,而不需要进行两次查询。

@Get('roots')
  async findRoots(@Req() request: Request) {
    const user = await this.authService.findCurrentUser(request);
    const directoriesAndFiles = await this.fileService.findAll({
      relations: ['user', 'parent', 'parent.parent'],
      order: {
        name: 'ASC',
      },
      where: {
        user: user.user_id,
        parent: IsNull(),
      },
    });
    
    const directories = [];
    const otherFiles = [];

    for (const directoryOrFile of directoriesAndFiles) {
      if (directoryOrFile.type === 'dir') {
        directories.push(directoryOrFile);
      } else {
        otherFiles.push(directoryOrFile);
      }
    }

    return directories.concat(otherFiles);
  }

相关问题