首页 > 解决方案 > 如何在嵌套 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
}

标签: typescriptschemanestjsdto

解决方案


更新

使用猫鼬,您可以这样做:

学生界面.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/addStudentNestJS 会创建一个studentdto.


推荐阅读