SUW15 – v42 – En enkel Chat klass utan DB

Nedan hittar du en enkel Chat klass som tar emot en express instans och skapar en enkelt chatt för användare. Klassen lagrar inte meddelanden i databas.

'use strict';

module.exports = class Chat {

  constructor(expressApp) {
    // save our settings to this
    this.settings = g.settings.Chat;

    // the express server instance
    this.app = expressApp;

    // all messages
    this.messages = [];

    // console.log("Chat intantiated, expressApp", expressApp);

    // setup express routes
    this.setup();
  }

  setup() {
    // route for getting all messages
    this.app.get(this.settings.endpoint, (req, res) => {
      // send all messages
      res.json(this.messages);
    });


    // route for creating a message
    this.app.post(this.settings.endpoint, (req, res) => {
      // do we have a user?
      if (!req.params.user) {
        // send status "Not found" and terminate
        res.sendStatus(404);
        return;
      }

      // create a new message 
      var msg = {
        user: req.params.user,
        msg: req.body.msg,
        time: new Date().getTime()
      });

      // add to all messages
      this.messages.push(msg);

      res.json(msg);
    });
  }

};

Ladda ner .js filen här

0 votes