How to return inserted data in typeorm and nest.js

Viewed 5994

I can insert following json data via Post method.

{
"userId":1,
"title":"mytest",
}

I'd like to return this data to client

Here is my controller

@Controller('event')
export class EventController {
  constructor(private readonly eventService: EventService) {}

  @Post()
  createEvent(@Body() param: EventRequest) {
    return this.eventService.createEvent(param);
  }
}

Following is my service

@Injectable()
export class EventService {
  constructor(private readonly eventRepository: eventRepository) {}
  async createEvent(eventParam: EventRequest): Promise<InsertResult> {
    const event = new Event();
    Object.entries(eventParam).forEach(param => {
      event[param[0]] = param[1];
    });
    try {
      return this.eventRepository.insert(event);
    } catch (error) {
      throw new InternalServerErrorException();
    }
  }
}

In my opinion,some code must be inserted after following.

return this.eventRepository.insert(event);

Now it returned following data. it seems not the body data.

{
    "identifiers": [
        {
            "id": 15
        }
    ],
    "generatedMaps": [
        {
            "id": 15,
            "createdAt": "2020-10-05T12:36:51.091Z",
            "updatedAt": "2020-10-05T12:36:51.091Z",
            "deletedAt": null
        }
    ],
    "raw": {
        "fieldCount": 0,
        "affectedRows": 1,
        "insertId": 15,
        "serverStatus": 2,
        "warningCount": 0,
        "message": "",
        "protocol41": true,
        "changedRows": 0
    }
}

My desired result is like following,id is autoincrement column.

{
id: events.id,
userId: events.userid,
title: events.title
}

Are there any information ? are there any method to achieve this?

If someone has opinion,please let me know.

Thanks

1 Answers

Are you using the repository pattern mentioned in the Nest.js docs here

I suggest you should try that out. I am able to get the required response. Checkout the sample given on Nest.js GitHub.

GitHub Repo

Related