Как настроить длинный опрос для получения данных из db (scrum poker) - PullRequest
0 голосов
/ 06 октября 2019

В настоящее время я работаю над проектом Scrum Poker, включая небольшой форум, где вы можете писать заметки и многое другое.

Я использовал этот шаблон (https://github.com/adrianbus/scrumPoker) и включил его в свой текущий проект Laravel.

Итак, я почти закончил. Пользователь может создавать комнаты, объединять комнаты и т. Д. Последнее, что мне нужно сделать, - это создать соединение для обмена данными. Исходный код относится к веб-сокетам, но я предпочитаючто-то вроде длинного опроса.

Не могли бы вы сказать, что я мог бы записать, чтобы заменить код веб-сокета чем-то другим, чтобы я наконец смог установить соединение между пользователями, чтобы получить значения их карт, текущиепользователь в комнате и т. д .?

Session.vue

<template>
  <div class="container">

    <div class="container">
        <h3>Session ID: <strong>{{sessionId}}</strong></h3>
        <h5>Name: <strong>{{sessionName}}</strong></h5>
    </div>

    <div class="container">
        <div class="row">
          <!-- Stats -->
          <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
            <div class="card">
              <div class="card-header">
                  Statistics
              </div>
              <div class="card-body">
                  <p class="card-text">Average: {{average}}</p>
                  <p class="card-text">Users: {{size}}</p>
                  <br>
                  <button class="button button2" v-on:click="show()">Show votes</button>
                  <button class="button button2" v-on:click="reset()">Reset</button>
              </div>
            </div>
          </div>
          <!-- /Stats -->
          <!-- Users -->
          <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
            <div class="card">
              <div class="card-header">
                  Users
              </div>
              <div class="card-body">
                  <p v-for="user in sessionUsers" :key="user.userId" class="card-text">
                    {{user.userName}}:
                    <span v-if="user.userVote!=0 && !showVotes">VOTED</span>
                    <span v-if="showVotes">{{user.userVote}}</span></p>
              </div>
            </div>
          </div>
          <!-- /Users -->
        </div>
    </div>

    <div class="container">
        <p>Invite members to session. Your session ID: <strong>{{sessionId}}</strong></p>
        <p>Link to your session: <strong><a :href=" 'http://localhost:8080/join/' + sessionId">http://localhost:8080/join/{{sessionId}}</a></strong></p>
    </div>

  </div>
</template>

<script>
export default {
  data() {
    return {
      socket: null,
      showVotes: false,
      sessionId: this.$route.params.sessionId,
      sessionName: "",
      sessionUsers: [], //userId, userName, userVote
      users: 0,
      average: 0,
      size: 0
    };
  },
  created() {
    this.getSession();
  },
  methods: {
    getUsers() {
      this.$http.get('/readplayers/' + this.sessionId).then(
        response => {
          this.sessionUsers = response.body.users;
        },
        response => {
          alert("Unable to read users, refresh page");
        }
      );
    },
    getSession() {
      let self = this;
      this.$http.get('/getsession/' + this.sessionId).then(
        response => {
          this.sessionName = response.body.sessionName;
          self.getUsers();
          self.socketConnection();
        },
        response => {
          this.$router.push("/404");
        }
      );
    },
    socketConnection() {
      var self = this;
      this.socket = new WebSocket("ws://localhost:8080");
      this.socket.onerror = function(e) {
        alert("Server connection error. Unable to connect with users");
      };
      this.socket.onclose = function() {
        alert("Server connection error. Unable to connect with users");
      };
      this.socket.onmessage = function(e) {
        console.log(e.data);
        self.getUsers();
      };
    },
    show() {
      this.showVotes = true;
      var sum = null;
      this.sessionUsers.forEach(element => {
        sum += Number(element.userVote);
      });
       this.size = sizeof((this.sessionUsers));
      this.average = sum / size;
      this.size = sizeof((this.sessionUsers));
    },
    reset() {
      this.showVotes = false;
      this.average = 0;
      this.socket.send("RESET");
      this.sessionUsers.forEach(element => {
        this.$http
          .post(Config.User.update + element.userId, {
            userId: element.userId,
            userVote: 0
          })
          .then(
            () => {
              this.getUsers();
            },
            () => {
              alert("Unable to reset");
            }
          );
      });
    }
  }
};
</script>

<style>
p a {
  color: #343a40;
}

p a:hover {
  color: #007bff;
}
</style>

User.vue

<template>
  <div class="container">

    <div class="container">
        <h3>Session ID: <strong>{{sessionId}}</strong></h3>
        <h5>Name: <strong>{{userName}}</strong></h5>
    </div>

    <div class="row">
        <div v-for="(card, index) in cards" v-on:click="makeVote()" :key="index" class="col-5 col-sm-3 col-md-2 text-center">
            <div v-on:click="selectedCard=index" :class="{'card bg-dark text-white text-center': !wasVoted, 'card bg-light text-center': wasVoted}">
                <span ref="card">{{card}}</span>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      socket: null,
      wasVoted: false,
      cards: [1, 2, 3, 5, 8, 13, 20, 40, 100],
      selectedCard: null,
      userName: "",
      sessionId: this.$route.params.sessionId,
      userId: this.$route.params.userId,
      vote: null
    };
  },
  created() {
    this.socketConnection();
    this.$http
      .get('/readplayers/' + this.userId +'/usersession/'+ this.sessionId)
      .then(
        data => {
          this.userName = data.body.userName;
        },
        data => {
          this.$router.push("/404");
        }
      );
  },
  methods: {
    makeVote() {
      if (!this.wasVoted) {
        this.vote = this.$refs.card[this.selectedCard].textContent;
        this.wasVoted = true;
        this.$http
          .post('/update/' + this.userId, {
            userId: this.userId,
            userVote: this.vote
          })
          .then(
            data => {
              this.socket.send(this.userName + " voted");
            },
            data => {
              alert("Unable to make vote");
            }
          );
      }
    },
    socketConnection() {
      self = this;
      this.socket = new WebSocket("ws://localhost:8080");
      this.socket.onerror = function(e) {
        alert("Server connection error. Unable to connect with scrum master");
      };
      this.socket.onopen = () => this.socket.send(this.userName + " connected");
      this.socket.onmessage = function(e) {
        if (e.data == "RESET") {
          self.wasVoted = false;
        }
      };
      this.socket.onclose = function() {
        alert("Server connection error. Unable to connect with scrum master");
      };
    }
  }
};
</script>

<style scoped>
.card {
  margin: 5px;
  padding: 50px 0;
  font-size: 24px;
}
</style>

Как видите, я ссылаюсь на функции в файлах .vueэто относится к веб-сокету. Цикл или что-то подобное, который запрашивает данные за определенный период, достаточно хорош.

Я получил App.vue в качестве основного файла VUE, который содержит несколько файлов .vue, таких какте, которые я разместил здесь

...