F
F
Floydreme2022-01-31 19:45:33
ORM
Floydreme, 2022-01-31 19:45:33

Why is the entity not updated in TypeORM?

I'm making a telegram bot in TypeScript to create queues. I want to implement a command to swap two members of this queue. My problem is that at the time of the swap, the queue is updated, and when I want to show this queue separately, the old one returns. Why - I do not understand. I would appreciate any help:

@Entity("users")
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    telegramId: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    short: string;

    @ManyToMany(() => Queue, queue => queue.users)
    @JoinTable()
    queues: Queue[];
}


@Entity("queues")
export class Queue {
    @PrimaryGeneratedColumn()
    id: number;

    @CreateDateColumn()
    createdAt: Date;

    @Column()
    chatId: string;

    @ManyToMany(() => User, user => user.queues, { cascade: true, onDelete: "CASCADE", onUpdate: "CASCADE"})
    users: User[];
}


//...
 this.queueRepository = this.connection.getRepository(Queue)
 this.userRepository = this.connection.getRepository(User)
//..
// Вот тут очередь не обновлена
 async showQueue(chatId: number): Promise<Queue> {
    const queue = (await this.queueRepository.findOne({ where: { chatId: chatId.toString() }, relations: ["users"] }))!

    if (!queue) throw new Error("Очереди еще нет")

    return queue!
}

// а тут возвращается обновленная очередь
async swapUsers(users: SwapDTO): Promise<Queue> {
    const queue = (await this.queueRepository.findOne({ where: { chatId: users.chatId.toString() }, relations: ["users"] }))!

    const callerPosition = queue.users.findIndex(u => u.id === users.caller.id)
    const resolverPosition = queue.users.findIndex(u => u.id === users.resolver.id)

    queue.users[callerPosition] = users.resolver
    queue.users[resolverPosition] = users.caller

    users.caller.queues[users.caller.queues.findIndex(q => q.chatId === queue.chatId)] = queue
    users.resolver.queues[users.resolver.queues.findIndex(q => q.chatId === queue.chatId)] = queue

    await this.userRepository.save(users.caller)
    await this.userRepository.save(users.resolver)


    return await this.queueRepository.save(queue)
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question