summaryrefslogtreecommitdiff
path: root/_includes/pageview-providers/leancloud/leancloud.js
blob: 32e3ba825547609344a03de546d915bc3cb8a971 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
(function() {
  function errorHandler(error, callback) {
    if (error) {
      callback && callback(error);
      throw error;
    }
  }

  function pageview(_AV, options) {
    var AV = _AV;
    var appId, appKey, appClass;
    appId = options.appId;
    appKey = options.appKey;
    appClass = options.appClass;
    AV.init({
      serverURLs: 'https://avoscloud.com',
      appId: appId,
      appKey: appKey
    });
    return {
      get: get,
      increase: increase
    };

    function searchKey(key) {
      var query = new AV.Query(appClass);
      query.equalTo('key', key);
      return query.first();
    }

    function insert(key, title) {
      var Blog = AV.Object.extend(appClass);
      var blog = new Blog();
      blog.set('title', title);
      blog.set('key', key);
      blog.set('views', 0);
      return blog.save();
    }

    function increment(result) {
      result.increment('views', 1);
      return result.save(null, {
        fetchWhenSave: true
      });
    }

    function get(key, callback) {
      searchKey(key).then(function(result) {
        if (result) {
          callback && callback(result.attributes.views);
        }
      }, errorHandler);
    }

    function increase(key, title, callback) {
      searchKey(key).then(function(result) {
        if (result) {
          increment(result).then(function(result) {
            callback && callback(result.attributes.views);
          });
        } else {
          insert(key, title).then(function(result) {
            increment(result).then(function(result) {
              callback && callback(result.attributes.views);
            });
          }, errorHandler);
        }
      }, errorHandler);
    }
  }
  window.pageview = pageview;
})();