typescript - 如何在嵌套 js 应用程序的服务文件中添加 DTO 源代码文件
问题描述
我有两个文件,一个是 DTO,我在其中声明方法验证,另一个文件是服务代码,我在其中编写 API 代码。但我不知道如何在服务构造函数()中注入 DTO 文件类。这是我的 DTO 和服务的代码。
服务代码:
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { studentdto} from './student.dto';
@Injectable()
export class CrudService {
constructor(
@InjectModel('student') private readonly studentmodel:studentmodel<studentdto>
) { Object.assign(this, studentmodel)}
async insert(name,rollno,section){
const add_stu=new this.studentmodel({studentdto})
return await add_stu.save()
}
}
这是DTO文件的代码:
import {IsString, IsInt} from 'class-validator'
import { Document } from 'mongoose';
export class studentdto{
@IsString()
name:string
@IsInt()
rollno:number
@IsString()
section:string
}
解决方案
更新
使用猫鼬,您可以这样做:
学生界面.ts
export interface Student {
name: string;
rollno: number;
section: string;
};
学生.schema.ts
import { Schema } from 'mongoose';
export const StudentSchema = new mongoose.Schema({
name: String,
rollno: Number,
section: String,
});
crudService.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { Model } from 'mongoose';
import { studentdto} from './student.dto';
import { Student } from './student.interface.ts';
import { StudentSchema } from './student.schema.ts';
@Injectable()
export class CrudService {
constructor(
@Inject('STUDENT_MODEL')
private studentModel: Model<StudentSchema>
) {}
async insert(studentDto: studentdto): Promise<Student> {
const createdUser = new this.studentModel(studentDto);
return createdUser.save()
}
}
您可以在此处找到更多信息。
您可以在控制器中使用您的 DTO。
学生控制器.ts
import {
Controller, Post, Body
} from "@nestjs/common";
import { CrudService } from './crud.service.ts';
import { studentdto} from './student.dto';
@Controller("student")
export class StudentController {
constructor(
private readonly crudService: CrudService
) {
@Post("addStudent")
addStudent(
@Body() newStudent: studentdto
): studentdto {
return this.crudService.insert(newStudent);
}
}
}
当您发送请求时,/student/addStudent
NestJS 会创建一个studentdto
.
推荐阅读
- python - 如何从字典值中推断出一个单独的元素?
- typescript - 打字稿如何安全地将一个枚举转换为另一个?
- python - 熊猫,我怎样才能避免使用 iterrow (如何根据来自另一个数据帧的值将值分配给数据帧中的新列)
- wpf - 有什么方法可以“反转”转换器吗?
- java - 签入 tpl-if-tag,如果字符在 gxt 模板中是中文
- java - Mapbox React Native Turn By Turn Navigation ANR 问题
- php - 如何以编程方式设置间隔时间并在我的自定义模块 Drupal 8 中运行 cron?
- api - 是空手道支持 <= 运算符匹配
- c++ - 使用 Bazel 构建 TensorFlow
- javascript - 如何使用 ResizeObserver 观察多个元素?