From a4c7b84616ab1e3f50d0d1f7875e294e8abe4693 Mon Sep 17 00:00:00 2001 From: Dragory <2606411+Dragory@users.noreply.github.com> Date: Fri, 14 Aug 2020 01:18:45 +0300 Subject: [PATCH] Add next_message_number to threads, use it for reply numbers --- ...1007_add_next_message_number_to_threads.js | 11 ++++++++ src/data/Thread.js | 26 ++++++++++++------- 2 files changed, 28 insertions(+), 9 deletions(-) create mode 100644 db/migrations/20200814011007_add_next_message_number_to_threads.js diff --git a/db/migrations/20200814011007_add_next_message_number_to_threads.js b/db/migrations/20200814011007_add_next_message_number_to_threads.js new file mode 100644 index 0000000..a5649d3 --- /dev/null +++ b/db/migrations/20200814011007_add_next_message_number_to_threads.js @@ -0,0 +1,11 @@ +exports.up = async function(knex) { + await knex.schema.table("threads", table => { + table.integer("next_message_number").defaultTo(1); + }); +}; + +exports.down = async function(knex) { + await knex.schema.table("threads", table => { + table.dropColumn("next_message_number"); + }); +}; diff --git a/src/data/Thread.js b/src/data/Thread.js index 83fc5eb..42f0b41 100644 --- a/src/data/Thread.js +++ b/src/data/Thread.js @@ -18,6 +18,7 @@ const {THREAD_MESSAGE_TYPE, THREAD_STATUS} = require("./constants"); * @property {String} user_id * @property {String} user_name * @property {String} channel_id + * @property {Number} next_message_number * @property {String} scheduled_close_at * @property {String} scheduled_close_id * @property {String} scheduled_close_name @@ -116,7 +117,7 @@ class Thread { */ async _addThreadMessageToDB(data) { if (data.message_type === THREAD_MESSAGE_TYPE.TO_USER) { - data.message_number = knex.raw(`IFNULL((${this._lastMessageNumberInThreadSQL()}), 0) + 1`); + data.message_number = await this._getAndIncrementNextMessageNumber(); } const dmChannel = await this.getDMChannel(); @@ -159,15 +160,22 @@ class Thread { } /** - * @returns {string} - * @private + * @returns {Promise} */ - _lastMessageNumberInThreadSQL() { - return knex("thread_messages AS tm_msg_num_ref") - .select(knex.raw("MAX(tm_msg_num_ref.message_number)")) - .whereRaw(`tm_msg_num_ref.thread_id = '${this.id}'`) - .toSQL() - .sql; + async _getAndIncrementNextMessageNumber() { + return knex.transaction(async trx => { + const nextNumberRow = await trx("threads") + .where("id", this.id) + .select("next_message_number") + .first(); + const nextNumber = nextNumberRow.next_message_number; + + await trx("threads") + .where("id", this.id) + .update({ next_message_number: nextNumber + 1 }); + + return nextNumber; + }); } /**