我有 KeysModule,可用于添加或删除 API 密钥。我需要这些密钥来保护某些路由免遭未经授权的访问。为了保护这些路由,我创建了 ApiGuard:
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class ApiGuard implements CanActivate {
async canActivate(
context: ExecutionContext,
): Promise<boolean> {
const request = context.switchToHttp().getRequest();
return request.headers.api_key;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我在路由中使用它:
@Get('/protected')
@UseGuards(ApiGuard)
async protected(@Headers() headers: Api) {
const key = await this.ks.findKey({ key: headers.api_key });
if (!key || !key.active) return 'Invalid Key';
return 'Your API key works';
}
Run Code Online (Sandbox Code Playgroud)
其中 ks 是 KeyService 用于检查密钥是否正确。此解决方案有效,但很愚蠢。我必须在我想使用这个守卫的任何地方复制和粘贴一些代码行(我的意思是路线中的行)。
我试图将所有逻辑移至 ApiGuard,但出现错误,即 KeyService 无法注入 ApiGuard 类。解释一下,我在 KeysModule 的提供者中有 KeyService,但 ApiGuard 是全局使用的。 …
假设我们有 2 个服务,A 和 B。服务 A 具有执行以下操作的功能:
现在,让我们假设以下步骤 3 或 4 之一失败。由于服务 B 在数据库中进行了更改,因此这些更改仍然存在。
在这种情况下,有没有办法回滚数据库?我虽然是关于数据库事务的,但是我在 nest js 中找不到任何方法来做到这一点,尽管 TypeOrm 支持它,但嵌套看起来并不自然。如果没有,我现在“卡住”了服务 B 发生的更改,但没有更改应该由 A 发生。
非常感谢。
我正在尝试使用 aValidationPipe但无论我如何编写代码,在发送请求时都会收到以下警告:No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies.
我的路线看起来像这样:
@Get()
@UsePipes(new ValidationPipe({ transform: true }))
async findAll(@Query() queryDto: QueryDto) {
return await this.myService.findAll(queryDto);
}
Run Code Online (Sandbox Code Playgroud)
我的 DTO 看起来像这样:
export class queryDto
{
@ApiModelProperty({
description: 'Maximum number of results',
type: Number,
example: 50,
default: 50,
required: false
})
readonly limit: number = 50;
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用ValidationPipe多种方法,遵循doc,但没有任何效果对我有用。我知道这是行不通的,因为虽然请求得到响应,默认值,我在我的DTO写的财产limit,这是50,是不是当查询是空的使用。因此,当limit查询中提供no 时,limit …
I want to achieve something like this using nest.js: (something very similar with Spring framework)
@Controller('/test')
class TestController {
@Get()
get(@Principal() principal: Principal) {
}
}
Run Code Online (Sandbox Code Playgroud)
After hours of reading documentation, I found that nest.js supports creating custom decorator. So I decided to implement my own @Principal decorator. The decorator is responsible for retrieving access token from http header and get principal of user from my own auth service using the token.
import { createParamDecorator } from '@nestjs/common';
export const …Run Code Online (Sandbox Code Playgroud) 如何?我如何捆绑 NestJS 项目,包括用于离线应用的 node_module?
const path = require('path');
module.exports = {
entry: path.join(__dirname, 'dist/main.js'),
target: 'node',
output: {
filename: 'compiled.js',
path: __dirname,
},
resolve: {
alias: {
node_modules: path.join(__dirname, 'node_modules'),
},
extensions: ['.js'],
},
};
Run Code Online (Sandbox Code Playgroud)
{
"name": "kai-brs",
"version": "0.9.1",
"author": "Sovgut Sergey",
"private": true,
"scripts": {
"build:webpack": "rimraf dist && tsc -p tsconfig.build.json && webpack dist/main.js -o dist/main.bundle.js --mode=production",
"build": "tsc -p tsconfig.build.json",
"format": "prettier --write \"src/**/*.ts\"",
"start": "ts-node -r tsconfig-paths/register src/main.ts",
"start:dev": "nodemon",
"start:debug": "nodemon --config …Run Code Online (Sandbox Code Playgroud) 我最近从直接使用 typegraphql 和 typeorm 转向将它们与 nestjs 一起使用。大多数情况下,这是一次直接的体验。然而,我有一个关于枚举的问题。
我有一组组合在一起的自定义装饰器,这样我就可以轻松地装饰我的模型,而无需同时使用 typeorm、typegraphql 和类验证器装饰器。这以前很好用,现在在除枚举以外的所有情况下都很好用。
作为一个例子,这里是一个@OptionalDecimal 装饰器:
import { IsNumber } from 'class-validator'
import { Field, Float } from 'type-graphql'
import { Column } from 'typeorm'
export function OptionalDecimal() {
const typeDecorator = IsNumber()
const fieldDecorator = Field(type => Float, { nullable: true })
const columnDecorator = Column('decimal', { nullable: true })
return (target: any, key: string) => {
typeDecorator(target, key)
fieldDecorator(target, key)
columnDecorator(target, key)
}
}
Run Code Online (Sandbox Code Playgroud)
我的@Enum 装饰器是这样的:
import { IsEnum } from 'class-validator' …Run Code Online (Sandbox Code Playgroud) 我最近使用了 nestjs,但我意识到它过于复杂,我的意思是看下面的代码:
@post('/products')
getAllProducts(@Body('title') title, @Body('price') price, @Body('description') description) { }
Run Code Online (Sandbox Code Playgroud)
它使函数参数变得很脏,而且函数上方可能还有更多装饰器,如@Header、@Params 等。在我看来,这会降低可读性。nodejs中的相同代码
const { title: title, price: price, description: description } = req.body
Run Code Online (Sandbox Code Playgroud)
nodejs 更具可读性...
然后我研究了为什么开发人员使用 nestjs,原因是模块化。为什么我们不自己实现这个......
见下文:
在 app.js 中,我刚刚踢了应用程序:
const express = require('express');
const app = express();
// express config
require('./startup/config')(app);
// handling routes
require('./startup/routes')(app);
// db setup
require('./startup/db')(app);
Run Code Online (Sandbox Code Playgroud)
在启动文件夹中,我做了一些基本的工作,比如 mongoose 配置和连接到 db 等。
但是,在启动/路由中,我只是按如下方式踢了模块:
const shopModule = require('../shop/shop.module');
module.exports = app => {
app.use('/', shopModule);
};
Run Code Online (Sandbox Code Playgroud)
在商店模块中,我只是踢了如下路线:
const router = require('express').Router();
const productsRouter = require('./products/index'); …Run Code Online (Sandbox Code Playgroud) 我尝试在AppController 中创建一个新方法,但它没有反映更改。我什至尝试更改默认的getHello()方法,但它输出“Hello World!” . 这怎么可能?
失眠
应用控制器
应用服务
所以我有一个将部署在 docker 容器中的 API。这个 API 有authentications控制器,简单而不特别。
当我在本地机器上以开发模式启动 API 时,将找到 auth 控制器并且一切正常。在我的本地机器上构建和运行它也是如此。但是当我对项目进行 dockerize 并在虚拟机上运行它时,我将无法访问 auth 控制器。每个其他控制器都在工作,但 auth 控制器不存在。
查看 docker 日志,不会映射任何身份验证控制器。本地和构建的 docker 镜像都应该包含相同的项目文件。
身份验证控制器:
import {
Controller,
Post,
Delete,
UseGuards,
Request,
Body,
} from '@nestjs/common';
import { AuthenticationsService } from './authentications.service';
import { JwtAuthGuard } from '../shared/guards/jwtAuth.guard';
import { SignInDTO } from './dtos/addGraphNodeToGraphByGraphId.dto';
@Controller('authentications')
export class AuthenticationsController {
constructor(
private readonly authenticationsService: AuthenticationsService,
) {}
@Post()
public signIn(@Body() { username, password }: SignInDTO): Promise<string> {
return this.authenticationsService.signIn(username, password);
} …Run Code Online (Sandbox Code Playgroud) 我正在从 Udemy https://www.udemy.com/course/nestjs-zero-to-hero学习 NestJS 课程。
而且我遇到了一个奇怪的问题,我尝试了很多东西,但似乎没有任何效果。这是我拥有的问题和完整代码。
我得到的错误
我的 ORM 配置文件:
最后我在 tasks.module.ts 文件中导入配置文件

面临这个问题的人已经用不同的修复方法解决了这个问题,
我已经尝试了所有可以通过 Internet 获得的可能解决方案,但无法解决此问题。现在已经好几天了,我正在寻找堆栈溢出的帮手或救星。
同时,我将尝试查看更多可能有帮助的可能性,但如果您遇到此问题,请告诉我可能的解决方案。
nestjs ×10
node.js ×7
javascript ×5
typeorm ×4
typescript ×4
caching ×1
decorator ×1
docker ×1
enums ×1
express ×1
graphql ×1
orm ×1
typegraphql ×1
webpack ×1