How to divide the result into several messages?

Viewed 54

For example, the result of a query to the database involves the output of 50 records. These records are issued in a single chat message, which is difficult to analyze. How to divide the result into several messages with 3 records in each?

bot.on('message', async (message) => {
        const {text, chat} = message;
        const {id: chatId} = chat;

        let response = '';

        try {
            const [rows] = await sequelize.query(`SELECT book FROM books t WHERE (t.*)::text LIKE '%${text}%' LIMIT 3`);
            if (rows.length) {
                response = rows.map(row => row.book).join("\n");
            } else {
                response = 'text';
            }
        } catch (error) {
            console.error(error.message);
            response = 'book not found';
        } finally {
            if (response) {
                bot.sendMessage(chatId, response);
            }
        }
    })
1 Answers
  1. Chunk rows that came from db to N items by reducing it using splice

  2. Then that chunk to array of book names using map

  3. Convert chunk of book names to message by joining by some logic in our case with newline symbol

  4. Push it to messages array

  5. Finally iterate that array and send

bot.on('message', async (payload) => {
  const {text, chat} = payload;
  const {id: chatId} = chat;

  const BOOKS_PER_MESSAGE = 3;
  let messages = [];

  try {

    const query = `SELECT book FROM books t WHERE (t.*)::text LIKE '%${text}%'`;
    let [rows] = await sequelize.query(query);

    while(rows.length) {
      const chunk = rows.splice(0, BOOKS_PER_MESSAGE); // [1]
      const books = chunk.map(row => row.book);        // [2]
      const message = books.join("\n");                // [3]
      messages.push(message);                          // [4]
    }

  } 
  catch (error) {
    console.error(error.message);
  } 
  finally {
    if (!messages.length) {
      bot.sendMessage(chatId, 'Book not found');
      return;
    }
    messages.forEach(message => 
                     bot.sendMessage(chatId, message)); // [5]
  }
});
Related