跨 nestjs 模块共享服务
Sharing services across nestjs modules
我正在做一个个人项目,我遵循存储库模式并将存储库注入我的服务(我不使用 typeorm,我使用 prisma)。现在我 运行 遇到了一个问题,我想在 auth 模块中使用 usersService 访问数据,它在我的 usersModule 中导出,而我的 auth 模块也导入了 usersModule,但它总是给出错误nest 无法解析 authService 中 usersService 的依赖关系。你们能帮我解决这个问题吗?
users.service.ts:
import { Inject, Injectable } from "@nestjs/common";
import { CreateUserDto } from "./dto/create-user.dto";
import { IUserRepository } from "./user.types";
import { TYPES } from "../app.types";
import { UserOutput } from "./dto/user.output";
@Injectable()
export class UsersService {
constructor(
@Inject(TYPES.User) private readonly userRepository: IUserRepository
) {}
async create(data: CreateUserDto): Promise<UserOutput | null> {
return await this.userRepository.createUser(data);
}
}
users.repository.ts:
import { HttpStatus, Injectable } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { CreateUserDto } from "./dto/create-user.dto";
import { UserOutput } from "./dto/user.output";
import { IUserRepository } from "./user.types";
import { ConfigService } from "@nestjs/config";
import { IEnv } from "../env.types";
import { HttpException } from "@nestjs/common";
@Injectable()
export class UserRepository implements IUserRepository {
constructor(
private readonly prismaService: PrismaService,
private readonly configService: ConfigService<IEnv>
) {}
async createUser(data: CreateUserDto): Promise<UserOutput> {
let { userName, password } = data;
try {
const user = await this.prismaService.user.findFirst({
where: { userName: userName },
});
if (user) {
throw new HttpException(
"User Already Exists",
HttpStatus.UNPROCESSABLE_ENTITY
);
}
const userCreated = await this.prismaService.user.create({
data: { userName: userName, password: hashedPassword as any },
});
} catch (e) {
console.log(e);
throw e;
}
}
users.module.ts
import { Module } from "@nestjs/common";
import { UsersService } from "./users.service";
import { UsersController } from "./users.controller";
import { TYPES } from "../app.types";
import { UserRepository } from "./users.repository";
@Module({
controllers: [UsersController],
providers: [
UsersService,
{
provide: TYPES.User,
useClass: UserRepository,
},
],
exports: [UsersService],
})
export class UsersModule {}
auth.module.ts:
import { Global, Module } from "@nestjs/common";
import { UsersModule } from "../users/users.module";
import { ValidateService } from "./validate.token.service";
@Global()
@Module({
imports: [UsersModule],
providers: [ValidateService],
exports: [ValidateService],
})
export class AuthModule {}
auth.service.ts:
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { Request } from "express";
import { ConfigService } from "@nestjs/config";
import { IEnv } from "../env.types";
import jwt from "jwt-simple";
import { UsersService } from "../users/users.service";
@Injectable()
export class AuthService {
constructor(
private readonly userService: UsersService,
private readonly configService: ConfigService<IEnv>
) {}
async verifyToken(request: Request): Promise<boolean> {
const token = request.headers.authorization;
if (!token) throw new UnauthorizedException();
try {
const secretKey = this.configService.get("SECRET_KEY");
const payload = jwt.decode(token, secretKey);
const user = await this.userService.findOne(payload.sub);
if (user) {
return true;
}
return false;
} catch (e) {
return false;
}
}
}
顺便说一句,TYPES.user = 符号('User')
在这种情况下,他们通常建议使用 forwardRef 来解决循环依赖。
我正在做一个个人项目,我遵循存储库模式并将存储库注入我的服务(我不使用 typeorm,我使用 prisma)。现在我 运行 遇到了一个问题,我想在 auth 模块中使用 usersService 访问数据,它在我的 usersModule 中导出,而我的 auth 模块也导入了 usersModule,但它总是给出错误nest 无法解析 authService 中 usersService 的依赖关系。你们能帮我解决这个问题吗?
users.service.ts:
import { Inject, Injectable } from "@nestjs/common";
import { CreateUserDto } from "./dto/create-user.dto";
import { IUserRepository } from "./user.types";
import { TYPES } from "../app.types";
import { UserOutput } from "./dto/user.output";
@Injectable()
export class UsersService {
constructor(
@Inject(TYPES.User) private readonly userRepository: IUserRepository
) {}
async create(data: CreateUserDto): Promise<UserOutput | null> {
return await this.userRepository.createUser(data);
}
}
users.repository.ts:
import { HttpStatus, Injectable } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { CreateUserDto } from "./dto/create-user.dto";
import { UserOutput } from "./dto/user.output";
import { IUserRepository } from "./user.types";
import { ConfigService } from "@nestjs/config";
import { IEnv } from "../env.types";
import { HttpException } from "@nestjs/common";
@Injectable()
export class UserRepository implements IUserRepository {
constructor(
private readonly prismaService: PrismaService,
private readonly configService: ConfigService<IEnv>
) {}
async createUser(data: CreateUserDto): Promise<UserOutput> {
let { userName, password } = data;
try {
const user = await this.prismaService.user.findFirst({
where: { userName: userName },
});
if (user) {
throw new HttpException(
"User Already Exists",
HttpStatus.UNPROCESSABLE_ENTITY
);
}
const userCreated = await this.prismaService.user.create({
data: { userName: userName, password: hashedPassword as any },
});
} catch (e) {
console.log(e);
throw e;
}
}
users.module.ts
import { Module } from "@nestjs/common";
import { UsersService } from "./users.service";
import { UsersController } from "./users.controller";
import { TYPES } from "../app.types";
import { UserRepository } from "./users.repository";
@Module({
controllers: [UsersController],
providers: [
UsersService,
{
provide: TYPES.User,
useClass: UserRepository,
},
],
exports: [UsersService],
})
export class UsersModule {}
auth.module.ts:
import { Global, Module } from "@nestjs/common";
import { UsersModule } from "../users/users.module";
import { ValidateService } from "./validate.token.service";
@Global()
@Module({
imports: [UsersModule],
providers: [ValidateService],
exports: [ValidateService],
})
export class AuthModule {}
auth.service.ts:
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { Request } from "express";
import { ConfigService } from "@nestjs/config";
import { IEnv } from "../env.types";
import jwt from "jwt-simple";
import { UsersService } from "../users/users.service";
@Injectable()
export class AuthService {
constructor(
private readonly userService: UsersService,
private readonly configService: ConfigService<IEnv>
) {}
async verifyToken(request: Request): Promise<boolean> {
const token = request.headers.authorization;
if (!token) throw new UnauthorizedException();
try {
const secretKey = this.configService.get("SECRET_KEY");
const payload = jwt.decode(token, secretKey);
const user = await this.userService.findOne(payload.sub);
if (user) {
return true;
}
return false;
} catch (e) {
return false;
}
}
}
顺便说一句,TYPES.user = 符号('User')
在这种情况下,他们通常建议使用 forwardRef 来解决循环依赖。