如何在nestjs graphql和typescript中使用guards

lnvxswe2  于 2023-03-24  发布在  TypeScript
关注(0)|答案(1)|浏览(116)

我是NestJS,GraphQL,Typescript的新手。
我有一个transfers.resolver.ts文件,如下所示:

import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql';
import { TransfersService } from './transfers.service';
import { Transfer } from './entities/transfer.entity';
import { CreateTransferInput } from './dto/create-transfer.input';
import { UpdateTransferInput } from './dto/update-transfer.input';
import { ListInput } from 'src/common/dto/list-input.dto';
import { ListTransfersResponse } from './dto/list-transfer-response';
import ConnectionArgs, {
  getPagingParameters,
} from 'src/common/relay/connection.args';
import { connectionFromArraySlice } from 'graphql-relay';
import { JwtAuthGuard } from 'src/common/auth/jwt-auth.guard';
import { UseGuards } from '@nestjs/common';
import { PubSub } from 'graphql-subscriptions';
import { WriteApiKeyGuard } from 'src/common/auth/write-api-key.guard';

const pubSub = new PubSub();

@Resolver(() => Transfer)
export class TransfersResolver {
  constructor(private readonly transfersService: TransfersService) {}

  /**
   * Create Transfer
   *
   * @param createTransferInput Object with transfer info
   * @returns Object with created transfer info
   */
  @Mutation(() => Transfer, { name: 'createTransfer' })
  @UseGuards(WriteApiKeyGuard)
  createTransfer(
    @Args('createTransferInput') createTransferInput: CreateTransferInput,
  ) {
    const newTransfer = this.transfersService.create(createTransferInput);
    pubSub.publish('transferAdded', { transferAdded: newTransfer });
    return newTransfer;
  }
}

我有一个write-api-key.guard.ts文件,如下所示:

import { InjectModel } from '@nestjs/mongoose';
import { ExecutionContext, Injectable } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { AuthGuard } from '@nestjs/passport';
import { Model } from 'mongoose';
import { Agency } from '../../agencies/entities/agency.entity';

@Injectable()
export class WriteApiKeyGuard extends AuthGuard('write-api-key') {
  constructor(
    @InjectModel(Agency.name)
    private readonly agencyModel: Model<Agency>,
  ) {
    super();
    console.log('This agency model');
    console.log(this.agencyModel);
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const ctx = GqlExecutionContext.create(context);
    const request = ctx.getContext().req;
    const apiKey = request.headers['write-api-key'];

    console.log(apiKey);

    if (!apiKey) {
      return false;
    }

    const agency = await this.agencyModel
      .find({ write_api_key: apiKey })
      .limit(1)
      .exec();

    return !!agency;
  }
}

正如你所看到的,我试图用write-up-key guard保护createTransfer mutation,但收到了以下错误:无法读取属性'find' of undefined我向控制台发送消息确认agency.model未定义。
转账和代理不在同一模块中
怎么了?我遗漏了什么?

nue99wik

nue99wik1#

我省略了在transfers.module.ts文件中添加agencies实体

import { forwardRef, Module } from '@nestjs/common';
import { TransfersService } from './transfers.service';
import { TransfersResolver } from './transfers.resolver';
import { MongooseModule } from '@nestjs/mongoose';
import { CommonModule } from '../common/common.module';
import { Transfer, TransferSchema } from './entities/transfer.entity';
import { Agency, AgencySchema } from 'src/agencies/entities/agency.entity';

@Module({
  imports: [
    forwardRef(() => CommonModule),
    MongooseModule.forFeature([
      {
        name: Transfer.name,
        schema: TransferSchema,
      },
      {
        name: Agency.name,
        schema: AgencySchema,
      },
    ]),
  ],
  providers: [TransfersResolver, TransfersService],
  exports: [TransfersService],
})
export class TransfersModule {}

刚刚添加了import { Agency,AgencySchema } from 'src/agencies/entities/agency. entity';
以及

{ name:Agency.name,schema:AgencySchema,},

谢谢

相关问题