简体   繁体   中英

NESTJS - How to send an object with an array and an object

i'm having a trouble with nest. What I want is a little bit difficult, and i don't know how to do that. First, with the ID of a site, I retrieve the users from this site and i want to be able to make a pagination, a sort by order (desc or asc i don't care) and to filtrate the results by value (a string). And in the output, i want to make an object with an array of the results and the synthesis. Example :

{
results : [{audit}],
syhthesis: {pageNumber: number, numberOfResults: number}
}

Honnestly, i've been trying for a while but i just cant understand how to do it. Here is my actual code :

the controller :


    import { Controller, Get, Query, Param, Post, Body } from '@nestjs/common';

    import { UserAuditService } from './user-audit.service';

    import { UserAudit } from 'src/entities/user-audit.entity';



    @Controller('useraudit')

    export class UserAuditController {

        constructor(private readonly userAuditService : UserAuditService){};


        @Post("/userpersite/{:id}")

        async getUsers(@Body()id: string, @Query('page') page: number): Promise<UserAudit[]>{

            return this.userAuditService.getAuditsForSite(id, page)

        }

    }

the service :


    import { Injectable } from '@nestjs/common';

    import { InjectRepository } from '@nestjs/typeorm';

    import { UserAudit } from '../entities/user-audit.entity';

    import { Repository } from 'typeorm';



    @Injectable()

    export class UserAuditService {



        constructor(

            @InjectRepository(UserAudit)

            private readonly userAuditRepository : Repository<UserAudit>

        ){}



        async getAuditsForSite(_siteId : string, page: number = 1) : Promise<UserAudit[]>{



            return this.userAuditRepository

            .find({

                join : {

                    alias : "user-audit",

                    innerJoinAndSelect: {

                        user : "user-audit.who"

                    }

                },

                where : {

                    site : _siteId

                },

                take: 10,

                skip: 10 * (page -1)

            })

        }

    }

and the entity :


    import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';

    import { User } from './user.entity';

    import { Site } from './site.entity';



    @Entity('user-audit')

    export class UserAudit {



        @PrimaryGeneratedColumn()

        id : string;



        @ManyToOne(type => User, user => user.id)

        who : User



        @Column({ length : 100 })

        action : string



        @ManyToOne(type => Site, site => site.id)

        site : Site



        @Column({ type : 'date' })

        date : Date



        @Column({ length : 1000 })

        before : string



        @Column({ length : 1000 })

        after : string

    }

I have try many things in my controller, but now, i am stuck, i know i am missing something, perhaps a lot of things, so if someone can help me, it will be very thankful :)

In the UserAuditService you can use findAndCount instead of find . It will return an array with 2 elements. The first element will be the entities and the second will be the total count. Then you need to make the appropriate response object:

async getUsers(@Body()id: string, @Query('page') page: number): Promise<object>{
  const [audits, total] = await this.userAuditService.getAuditsForSite(id, page)
  return {
    results : audits,
    syhthesis: {
      pageNumber: page,
      numberOfResults: total,
  }
}

sorry to bother you again. So i've tried it, and it doesn't work :/ I was certain this to be the solution. So I thought of something : to work with models, but again, i am stuck. Here is the new code :

the service :

import { Injectable } from '@nestjs/common';

import { InjectRepository } from '@nestjs/typeorm';

import { UserAudit } from '../entities/user-audit.entity';

import { Repository } from 'typeorm';

import { UserAuditRequest } from '../entities/user-audit-request';



@Injectable()

export class UserAuditService {



    constructor(

        @InjectRepository(UserAudit)

        private readonly userAuditRepository : Repository<UserAudit>,

        private readonly userRequest: Repository<UserAuditRequest>

    ){}



    async getAuditsForSite(_siteId : string, page: number = 1, filter: any) : Promise<any>{



        const joinAndSort = this.userAuditRepository

        .findAndCount({

            join : {

                alias : "user-audit",

                innerJoinAndSelect: {

                    user : "user-audit.who"

                }

            },

            where : {

                site : _siteId

            },

            take: 10,

            skip: 10 * (page -1)

        })

        joinAndSort



        const sortElement = this.userRequest.find({

            where: {

                pagination: page

            }

        })

        sortElement



        const filterElement = this.userRequest.findAndCount({

            where: {

                filter: filter

            }

        })

        filterElement

    }



}

the controller :

import { Controller, Get, Query, Param, Post, Body } from '@nestjs/common';

import { UserAuditService } from './user-audit.service';

import { UserAudit } from 'src/entities/user-audit.entity';

import { UserAuditRequest } from '../entities/user-audit-request';

import { ResultUserAudit } from '../entities/result-user-audit';

import { Any } from 'typeorm';



@Controller('useraudit')

export class UserAuditController {



    constructor(private readonly userAuditService : UserAuditService, private readonly resultUserAudit: ResultUserAudit){};


    @Post("/userpersite/:id")

    async postUserPerSite(@Param()id: string,@Body() request : UserAuditRequest): Promise<ResultUserAudit>{

       return await this.userAuditService.getAuditsForSite(id, request.pagination.pageNumber, request.filter);

the request model :

import { Injectable } from "@nestjs/common";



@Injectable()

export class UserAuditRequest {

    constructor(){}



    pagination: {



        resultNumber: number;



        pageNumber: number;

    }



    sort: {

        columnSorted: any;



        orderBy: any;



    }



    filter: {



        columnFilter: any;



        filtervalue: string;

    }

}

and the result model :

import { Injectable } from "@nestjs/common";

import { UserAudit } from "./user-audit.entity";



@Injectable()

export class ResultUserAudit {

    constructor(private userAudit: UserAudit){}



    result: UserAudit[];



    synthesis: {



        pageNumber: number,



        resultNumber: number;



    }



}

I am trying to get the logic for my code, but i don't know, i just can't succed :( I see what i want to do as explain in my first post (hopefully) but i am not able to do it. I hope someone will be able to help and explain. Thank you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM