LoginSignup
2
2

More than 5 years have passed since last update.

milkcocoaでデータストアへのコネクション数を自前実装で取得しようとした(が、うまくいかなかった)

Last updated at Posted at 2015-08-27

概要

Milkcocoaのデータストアへの接続数は、ダッシュボードでは確認できるのですがAPIとしては用意されておらず、ほしいなら自前で実装する必要があります(少なくともv2.0.0は)。
で、作ってみたんですがどうもガバガバで、コネクション数が無駄にカウントされちゃったりする。
どーしたもんかと粘ったんですが、これ以上は自分じゃよくわからないので、とりあえずコードを置いておくことにした(放り投げた)。

つーわけで誰か改善してください!

コード

index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Connection Counter</title>
</head>

<body>
    <div id="connection_counter"></div>
    <script src='https://cdn.mlkcca.com/v2.0.0/milkcocoa.js'></script>
    <script src="connection_count.js"></script>
    <script>connection_counter.start("connection_counter");</script>
</body>

</html>
connection_count.js
(function () {
    window.connection_counter = {

        start: function (tagId) {

            var milkcocoa = new MilkCocoa("{your-app-id}.mlkcca.com"); //
            var ds = milkcocoa.dataStore("connection_count");

            var count = 0;

            ds.get("connection_count", function (err, datum) {
                if (err) {
                    // 初回(not foundがerrに入る)はデータがないので1で初期化
                    if (err === "not found") {
                        ds.set("connection_count", {
                            "count": "1"
                        });
                        return;
                    } else {
                        console.log(err);
                        return;
                    }
                }

                // 接続数を取得し+1する
                count = parseInt(datum.value.count, 10) + 1;

                ds.set("connection_count", {
                    "count": count
                });
            });

            // コネクション数を同期する
            ds.on('set', function (set) {
                count = parseInt(set.value.count, 10);
                document.getElementById(tagId).textContent = count;
            });

            // ページ離脱の前にカウントを減らす
            window.addEventListener('beforeunload', function (e) {
                count--;
                ds.set("connection_count", {
                    "count": count
                });
            });
        }
    }
}());

おおざっぱに解説

  1. ページアクセス時には現在のコネクション数をgetし自分の分を+1してset
  2. 自分以外の誰かがアクセスしたらsetが走るのでon(set)で同期
  3. ページを離れるときはコネクション数を-1してset

という処理をしています。
あと、1でgetしたときにデータがなかったら(=初回アクセス時は)、1をsetしています。

お願い

「こうやったらコネクション数とれるんじゃないの?」っていうお知恵がございましたらお教えください。あるいは誰か作ってください。(あるいはAPIでサポートよろしくお願いします…)

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2