showing results for - "nestjs typeorm update entity"
Alonso
02 May 2018
1import { Injectable } from '@nestjs/common';
2import { Todo } from './todo.entity';
3import { Repository, DeleteResult } from 'typeorm';
4import { InjectRepository } from '@nestjs/typeorm';
5import { CreateTodoDto } from './todos.dto';
6
7@Injectable()
8export class TodosService {
9  constructor(
10    @InjectRepository(Todo)
11    private readonly todoRepository: Repository<Todo>,
12  ) {}
13
14  public async findAll(): Promise<Todo[]> {
15    return await this.todoRepository.find();
16  }
17
18
19  public async findById(id: number): Promise<Todo | null> {
20    return await this.todoRepository.findOneOrFail(id);
21  }
22
23  public async create(todo: CreateTodoDto): Promise<Todo> {
24    return await this.todoRepository.save(todo);
25  }
26
27  public async update(
28    id: number,
29    newValue: CreateTodoDto,
30  ): Promise<Todo | null> {
31    const todo = await this.todoRepository.findOneOrFail(id);
32    if (!todo.id) {
33      // tslint:disable-next-line:no-console
34      console.error("Todo doesn't exist");
35    }
36    await this.todoRepository.update(id, newValue);
37    return await this.todoRepository.findOne(id);
38  }
39
40  public async delete(id: number): Promise<DeleteResult> {
41    return await this.todoRepository.delete(id);
42  }
43}
44Copy