Search code examples
node.jsexpresstelegram-bothttpserver

How to combine two different logic parts of node.js application? (telegram-bot and http-server)


It's my first node.js real application. I started from create telegram bot with especial framework Node-Telegram-Bot-Api

This bot processes the sequence of questions, like name, phone, location and photo, audio message, saves files to server and joins all this staff to one object and writes it to MongoDB.

It was just file index.js, where I have done all things...

Now I faced with new task - create web interface for this data. I installed express-generator and created with it site, with ready to use handlebar view, some routes, sass support and serving static files - all useful things for making a web interface...

Question is - how to combine two parts:

  1. telegram-bot part, which fills database with data and

  2. express http-server, witch supports routs, views and displays data from database, and also serves the files: photos and voice messages...

I'm sorry if the question is stupid. But it is my first real work in node.js, please try to understand me.


Solution

  • Since you just need to interact with the data in the database with Express, you have the following choices:

    1. Expose an API that will allow whatever client to retrieve the data. Client could be a mobile app, another service, or a Web app.
    2. Create a traditional Express app (as you did with express-generator), retrieve the data from the database and pass it along with the view.

    A quick dirty example of (1) would look something like (omitted error handling):

    const express = require('express')
    const mysql = require('mysql')
    
    const app = express()
    const router = express.Router()
    const connection = mysql.createConnection({ /* ... */ })
    connection.connect()
    
    app.use(express.urlencoded({ extended: true }))
    app.use(express.json())
    
    router.get('/', async (req, res) => {
      const results = await new Promise((resolve, reject) => {
        connection.query('SELECT * FROM messages', (error, results) => {
          if (error) {
            reject(error)
            return
          }
          resolve(results)
        })
      })
    
      res.json(results)
    })
    
    app.use('/messages', router)
    app.listen(process.env.PORT)
    

    For (2), it would essentially be the same except you would call:

    res.render('viewName', results)
    

    Your Express application and telegram-bot will both be independent of each other.