我应该返回的对象:
@ObjectType()
export class User {
@Field(() => String)
email: string
@Field(() => [Level])
level: Level[]
}
Run Code Online (Sandbox Code Playgroud)
Level 是 prisma 生成的枚举,在 schema.prisma 中定义:
enum Level {
EASY
MEDIUM
HARD
}
Run Code Online (Sandbox Code Playgroud)
现在我尝试在 GraphQL Mutation 中返回此 User 对象:
enum Level {
EASY
MEDIUM
HARD
}
Run Code Online (Sandbox Code Playgroud)
运行此代码时,我收到以下错误:
UnhandledPromiseRejectionWarning: Error: Cannot determine a GraphQL output type for the "Level". Make sure your class is decorated with an appropriate decorator.
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?prisma 的枚举不能用作字段吗?
我想用这样的东西:
猫接口.ts
export interface ICats {
meow(): void
}
Run Code Online (Sandbox Code Playgroud)
猫服务.ts
@Injectable()
export class CatsService implements ICats {
constructor()
meow(): void {
return;
}
}
Run Code Online (Sandbox Code Playgroud)
猫模块.ts
@Module({
providers: [CatsService]
exports: [CatsService]
})
export class CatsModule {}
Run Code Online (Sandbox Code Playgroud)
动物.service.ts
@Injectable()
export class AnimalsService {
constructor(@Inject('ICats') private readonly cats: ICats)
test(): void {
return this.cats.meow();
}
}
Run Code Online (Sandbox Code Playgroud)
动物模块.ts
@Module({
imports: [CatsModule],
providers: [AnimalsService],
exports: [AnimalsService]
Run Code Online (Sandbox Code Playgroud)
但收到
Nest can't resolve dependencies of the
我有一个 Nestjs 和 MongoDB 应用程序。
auth.module.ts-
@Module({
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
],
controllers: [AuthController],
providers: [AuthService],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)
auth.service.ts-
@Injectable()
export class AuthService {
// Inject User model into AuthService
constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}
getUser(username: string) {
const user = this.userModel.find({ name: username });
return user;
}
}
Run Code Online (Sandbox Code Playgroud)
@nestjs/mongoose我使用和创建了一个 UserSchema mongoose。
根据文档,当我导入MongooseModule模块中使用的架构时,该架构只能在该特定模块中使用。
如果我想访问我的模块和服务中的多个模型怎么办?有办法吗?
如何将多个模型注入到服务中?
我使用带有 M1 芯片的 MacOS monterey 作为操作系统。使用以下命令安装 NestJS cli:sudo npm install -g @nestjs/cli
当使用nest new message一切正常创建新的嵌套项目时,但是当我尝试使用此命令创建新模块时,nest generate module messages我遇到错误。
为什么会发生这种情况?我尝试使用安装原理图npm i -g @nestjs/schematics,我不知道是否应该安装它,但这无论如何都没有帮助。
我面临的错误是:
/Users/homayoun/training/messages/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:338
throw new Error(`Unknown argument ${key}. Did you mean ${(0, yargs_parser_1.decamelize)(key)}?`);
^
Error: Unknown argument skipImport. Did you mean skip-import?
at parseArgs (/Users/homayoun/training/messages/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:338:19)
at main (/Users/homayoun/training/messages/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:122:49)
at Object.<anonymous> (/Users/homayoun/training/messages/node_modules/@angular-devkit/schematics-cli/bin/schematics.js:367:5)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Failed to …Run Code Online (Sandbox Code Playgroud) 我使用 NestJS 连接到数据库,并使用 TypeORM 作为 db 包。我的 postgres 正在 docker 中运行,ip 172.17.0.3: 5432
sudo docker run --name postgre -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=密码 -p 5432:5432 -v /data/postgres:/var/lib/postgresql/data -d postgres
这是我的存储模块文件:
import { Module } from '@nestjs/common';
import { storageConfig, StorageService } from './storage.service';
import { TypeOrmModule} from '@nestjs/typeorm'
import { User } from './entities/user.entity';
@Module({
providers: [StorageService],
imports: [
TypeOrmModule.forRoot({
driver: 'pg',
type: 'postgres',
host: '172.17.0.3',
port: 5432,
username: 'admin',
password: 'password',
database: 'user_storage',
schema: 'public',
entities: [User]
})
]
}) …Run Code Online (Sandbox Code Playgroud) 我正在使用 @UseGuards 来验证标头中的两个 api 密钥。
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
// check two api keys('some' and 'thing') in header at once
}
Run Code Online (Sandbox Code Playgroud)
另外,我在控制器中使用 @ApiHeader 来大肆展示。
@ApiOperation({ summary: 'blah blah' })
@ApiHeader({ name: 'some'}, {name: 'thing'})
@UseGuards(AuthGuard)
@Get('/hello')
async adminableCollections() {
// do something
}
Run Code Online (Sandbox Code Playgroud)
我想使用 @ApiSecurity 或其他东西代替 @ApiHeader 使用授权按钮(如图中)一次性授权,而不是为每个方法输入值。

我尝试使用文档生成器添加自定义安全性,但它似乎根本不起作用。
const swaggerConfig = new DocumentBuilder()
.setTitle('My API')
.setDescription('Document for my api.')
.setVersion('0.0.1')
.addApiKey('some', { type: 'apiKey', in: 'header', name: 'some' })
.addApikey('thing', { type: …Run Code Online (Sandbox Code Playgroud) 我正在学习nestjs,并构建一个应用程序,但我的ip位于代理后面,
Nestjs 文档说启用快速信任代理,
https://docs.nestjs.com/security/rate-limiting
我在如何做到这一点以及如何找到 IP 方面遇到了麻烦。
在我的后端,我有这个端点:
@Post()
@UseInterceptors(FilesInterceptor('files'))
create(
@UploadedFiles() files: Array<Express.Multer.File>,
@Body() body: MyDto,
) {
console.log(body);
console.log(files);
}
Run Code Online (Sandbox Code Playgroud)
MyDto很简单:
export class MyDto {
year: string
}
Run Code Online (Sandbox Code Playgroud)
当我multipart/form-data仅使用字段或与一个或多个文件一起发送请求(在 Firefox、Chrome 和 Postman 上尝试使用代码)时year,我从第一个console.log(打印 的那个body)中得到:
MyDto {}
Run Code Online (Sandbox Code Playgroud)
当我从正文中删除输入时,端点变为:
@Post()
@UseInterceptors(FilesInterceptor('files'))
create(
@UploadedFiles() files: Array<Express.Multer.File>,
@Body() body,
) {
console.log(body);
console.log(files);
}
Run Code Online (Sandbox Code Playgroud)
本体如图所示:
[Object: null prototype] { year: '2022' }
Run Code Online (Sandbox Code Playgroud)
变量files总是正确的。
如何设置正文的类型?
我main.ts的如下:
const app = await NestFactory.create(AppModule, {
logger: ['log', 'error'],
});
app.enableCors(); …Run Code Online (Sandbox Code Playgroud) 我有一个带有 REST 模块和 GraphQL 模块的Nest.js应用程序。两者都导入到App.module.ts. 我正在使用 Nest 的Throttler Guard来保护整个应用程序。众所周知,GraphQL 不能与普通的 一起使用ThrottlerGuard,因此我创建了一个GqlThrottlerGuard并将其导入到 GraphQL 模块上,同时将原始的导入ThrottlerGuard到 REST 模块上。
所以,我的 graphQL 模块如下所示:
@Module({
imports: [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: true
}),
ThrottlerModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
ttl: config.get('security.throttle.ttl'),
limit: config.get('security.throttle.limit'),
}),
}),
],
providers: [
{
provide: APP_GUARD,
useClass: GqlThrottlerGuard,
},
],
})
export class GraphModule { }
Run Code Online (Sandbox Code Playgroud)
还有 REST 模块,如下所示:
@Module({
imports: [
ThrottlerModule.forRootAsync({
imports: …Run Code Online (Sandbox Code Playgroud) 当我运行此nestjs代码时,遇到错误:
SyntaxError: Invalid or unexpected token
Run Code Online (Sandbox Code Playgroud)
是什么原因?
import {Controller, Get, Bind, Req, Post} from '@nestjs/common';
@Controller('cats')
export class catsController {
@Post()
create() {
return "this is a action 1ss"
}
@Get()
@Bind(Req())
findAll(request) {
return "this is a action";
}
}
Run Code Online (Sandbox Code Playgroud) nestjs ×10
typescript ×4
node.js ×3
graphql ×2
dto ×1
enums ×1
ip ×1
javascript ×1
mongoose ×1
multer ×1
npm ×1
postgresql ×1
prisma ×1
proxy ×1
rest ×1
swagger ×1
swagger-ui ×1
syntax-error ×1
typeorm ×1