我有一个 AuthGuard,负责检查控制器中的 JWT 令牌。我想在控制器中使用这个 Guard 来检查身份验证。我有这个错误:
Nest 无法解析 AuthGuard (?, +) 的依赖项。请确保索引 [0] 处的参数在当前上下文中可用。
import {
Controller,
Post,
Body,
HttpCode,
HttpStatus,
UseInterceptors,
UseGuards,
} from "@nestjs/common";
import { TestService } from "Services/TestService";
import { CreateTestDto } from "Dtos/CreateTestDto";
import { ApiConsumes, ApiProduces } from "@nestjs/swagger";
import { AuthGuard } from "Guards/AuthGuard";
@Controller("/tests")
@UseGuards(AuthGuard)
export class TestController {
constructor(
private readonly testService: TestService,
) {}
@Post("/create")
@HttpCode(HttpStatus.OK)
@ApiConsumes("application/json")
@ApiProduces("application/json")
async create(@Body() createTestDto: CreateTestDto): Promise<void> {
// this.testService.blabla();
}
}
Run Code Online (Sandbox Code Playgroud)
@Entity()
export class User {
@PrimaryColumn()
id: string;
@Column({unique: true})
username: string;
@Column({unique: true})
email: string;
@OneToMany(type => Post, post => post.id)
posts: Post[];
}
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => User, user => user.posts)
@JoinColumn({name: 'user_id'})
user: User;
@OneToMany(type => Image, image => image.id)
images: Image[];
}
@Entity()
export class Image {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => Post, post => post.images)
@JoinColumn({name : 'post_id'})
post: Post;
}
Run Code Online (Sandbox Code Playgroud)
我有这3个实体,我想查询一个用户的所有帖子,并让该帖子获取所有图像。我正在尝试使用以下代码执行此操作:
return await this.postRepository.createQueryBuilder("post")
.innerJoinAndSelect("post.images", "image")
.where("user_id = …Run Code Online (Sandbox Code Playgroud) 在我的 NestJS 项目中,我有这个 TypeORM 查询:
const users = await this.usersRepository.find({
skip,
take,
order: sortingObject,
join: {
alias: 'user',
leftJoinAndSelect: {
country: 'user.country_id',
},
},
});
Run Code Online (Sandbox Code Playgroud)
现在我只想返回John名称中的用户。在 SQL 中,这将是一个LIKE查询LIKE %John%。
在https://github.com/typeorm/typeorm/blob/master/docs/find-options.md中没有关于通配符的信息LIKE查询的。
如何执行类似查询 Typeorm作为解决方案提供:
.where("user.firstName like :name", {name: '%' + firstName + '%' })
但是后来我无法使用skip,take并且在使用时可用where()代替find().
关于如何使用 TypeORM QueryBuilder 实现这一点的任何想法?
我的后端使用 NestJS、Node 和 Express,前端使用 Angular。我有一个步进器,用户可以在其中逐步浏览并输入有关他们自己的信息以及个人资料照片和他们想要发布的任何艺术照片(这是一个草稿)。我使用以下代码将文件发送到后端:
<h2>Upload Some Photos</h2>
<label for="singleFile">Upload file</label>
<input id="singleFile" type="file" [fileUploadInputFor]= "fileUploadQueue"/>
<br>
<mat-file-upload-queue #fileUploadQueue
[fileAlias]="'file'"
[httpUrl]="'http://localhost:3000/profile/artPhotos'">
<mat-file-upload [file]="file" [id]="i" *ngFor="let file of fileUploadQueue.files; let i = index"></mat-file-upload>
</mat-file-upload-queue>
Run Code Online (Sandbox Code Playgroud)
前端将照片作为文件数组发送;我试图改变它,使它只发送一个文件,但无法让它工作。我不太关注这一点,因为用户可能需要上传多个文件,所以无论如何我都想弄清楚。在后端,我使用 multer、multer-s3 和 AWS-SDK 来帮助上传文件,但它不起作用。这是控制器代码:
@Post('/artPhotos')
@UseInterceptors(FilesInterceptor('file'))
async uploadArtPhotos(@Req() req, @Res() res): Promise<void> {
req.file = req.files[0];
delete req.files;
// tslint:disable-next-line:no-console
console.log(req);
await this._profileService.fileupload(req, res);
}
Run Code Online (Sandbox Code Playgroud)
这是 ProfileService:
import { Profile } from './profile.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import …Run Code Online (Sandbox Code Playgroud) 我在对控制器进行单元测试时遇到问题,并收到错误消息“嵌套无法解决我的服务依赖性”。
为了获得最大的覆盖范围,我想对控制器和相应的服务进行单元测试,并希望模拟像猫鼬连接之类的外部依赖项。同样,我已经尝试了以下链接中提到的建议,但没有发现任何运气:
https://github.com/nestjs/nest/issues/194#issuecomment-342219043
请在下面找到我的代码:
export const deviceProviders = [
{
provide: 'devices',
useFactory: (connection: Connection) => connection.model('devices', DeviceSchema),
inject: ['DbConnectionToken'],
},
];
export class DeviceService extends BaseService {
constructor(@InjectModel('devices') private readonly _deviceModel: Model<Device>) {
super();
}
async getDevices(group): Promise<any> {
try {
return await this._deviceModel.find({ Group: group }).exec();
} catch (error) {
return Promise.reject(error);
}
}
}
@Controller()
export class DeviceController {
constructor(private readonly deviceService: DeviceService) {
}
@Get(':group')
async getDevices(@Res() response, @Param('group') group): Promise<any> {
try {
const result …Run Code Online (Sandbox Code Playgroud) Inversify.js 中有一个multiInject装饰器,允许我们将多个对象作为数组注入。此数组中所有对象的依赖关系也已解决。
有没有办法在 Nest.js 中实现这一目标?
我在我正在构建的 NestJS 应用程序中添加了一些简单、有效的登录功能。我现在想阻止已注销用户访问某些路由,因此我添加了一个简单的AuthGuard,如下所示;
@Injectable()
export class AuthGuard implements CanActivate {
public canActivate(
context: ExecutionContext,
): boolean {
const request = context.switchToHttp().getRequest();
const response = context.switchToHttp().getResponse();
if (typeof request.session.authenticated !== "undefined" && request.session.authenticated === true) {
return true;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的方式是阻止用户访问应用了守卫的路由,但这样做只会显示此 JSON 响应;
{
"statusCode": 403,
"error": "Forbidden",
"message": "Forbidden resource"
}
Run Code Online (Sandbox Code Playgroud)
我想要的是当守卫失败时用户被重定向到登录页面。我试过用return falsewith替换response.redirect("/auth/login");,虽然它有效,但在控制台中我收到消息
(node:11526) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:11526) [DEP0018] …
我创建了一个 nestjs 应用程序,现在我正在寻找在生产环境 Heroku 中部署它的最佳方法。
当我尝试部署由 nest-cli 生成的代码时,我从 heroku 获得了以下日志:
2018-12-28T08:37:23.881261+00:00 app[api]: Release v1 created by user myemail@gmail.com
2018-12-28T08:37:24.051831+00:00 app[api]: Release v2 created by user myemail@gmail.com
2018-12-28T08:37:23.881261+00:00 app[api]: Initial release by user myemail@gmail.com
2018-12-28T09:00:47.000000+00:00 app[api]: Build started by user myemail@gmail.com
2018-12-28T09:01:37.401065+00:00 heroku[web.1]: Starting process with command `npm start`
2018-12-28T09:01:40.164685+00:00 heroku[web.1]: Process exited with status 1
2018-12-28T09:01:40.205293+00:00 heroku[web.1]: State changed from starting to crashed
2018-12-28T09:01:40.209626+00:00 heroku[web.1]: State changed from crashed to starting
2018-12-28T09:01:40.051608+00:00 app[web.1]:
2018-12-28T09:01:40.051626+00:00 app[web.1]: > nest-app-heroku@0.0.0 start /app
2018-12-28T09:01:40.051628+00:00 …Run Code Online (Sandbox Code Playgroud) 我有一些微服务,通过API网关公开。网关负责处理身份验证和路由到系统中。网关后面的服务主要是简单的CRUD服务。每个服务都公开自己的API,并通过HTTP同步通信。所有这些服务,包括API-Gateway,都是“默认” NestJS应用程序。
让我们继续坚持猫的例子。每当Cat-Service更新或创建新的时Cat,我都希望CatCreatedEvent或被CatUpdatedEvent模仿。该事件应被推送到某些消息代理中,例如RabbitMQ,而另一个服务应侦听此事件并异步处理该事件。
我不知道如何以正确的方式“注入” RabbitMQ来实现这一目标,我想知道这种方法是否合乎常理。我已经看到了NestJS的CQRS模块,但是我认为CQRS对于该域来说有点过多。尤其是因为在此域中没有好处,无法拆分读写模型。也许我完全走错了道路,所以希望您能给我一些建议。
我使用的是NestJS的mongoose模块,所以我有模式和接口,在服务中,我使用@InjectModel注入模型。我不知道如何模拟要注入服务的模型。
我的服务如下所示:
@Injectable()
export class AuthenticationService {
constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
async createUser(dto: CreateUserDto): Promise<User> {
const model = new this.userModel(dto);
model.activationToken = this.buildActivationToken();
return await model.save();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的服务测试中,我有这个:
const mockMongooseTokens = [
{
provide: getModelToken('User'),
useValue: {},
},
];
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
...mockMongooseTokens,
AuthenticationService,
],
}).compile();
service = module.get<AuthenticationService>(AuthenticationService);
});
Run Code Online (Sandbox Code Playgroud)
但是当我运行测试时,我得到了这个错误:
TypeError: this.userModel is not a constructor
Run Code Online (Sandbox Code Playgroud)
我也想让我的模型对其执行单元测试,如本文所示
nestjs ×10
node.js ×6
javascript ×2
typeorm ×2
typescript ×2
amazon-s3 ×1
events ×1
file-upload ×1
heroku ×1
inversifyjs ×1
jestjs ×1
rabbitmq ×1
redirect ×1
unit-testing ×1