git ssb

0+

alanz / patchwork



forked from Matt McKegg / patchwork

Tree: 8397cee5bd7b17b9f2ebf584813ed0c0a035023d

Files: 8397cee5bd7b17b9f2ebf584813ed0c0a035023d / modules / cache.js

1831 bytesRaw
1var Value = require('mutant/value')
2var computed = require('mutant/computed')
3var MutantDict = require('mutant/dict')
4var MutantStruct = require('mutant/struct')
5
6exports.gives = {
7 cache: {
8 update_from: true,
9 get_likes: true,
10 obs_channels: true
11 }
12}
13
14exports.create = function (api) {
15 var likesLookup = {}
16 var channelsLookup = MutantDict()
17
18 var obs_channels = computed(channelsLookup, (lookup) => {
19 var values = Object.keys(lookup).map(x => lookup[x]).sort((a, b) => b.updatedAt - a.updatedAt)
20 return values
21 }, {nextTick: true})
22
23 return {
24 cache: {
25 get_likes, obs_channels, update_from
26 }
27 }
28
29 function get_likes (msgId) {
30 if (!likesLookup[msgId]) {
31 likesLookup[msgId] = Value({})
32 }
33 return likesLookup[msgId]
34 }
35
36 function update_from (msg) {
37 if (msg.key && msg.value && msg.value.content) {
38 var c = msg.value.content
39 if (c.type === 'vote') {
40 if (msg.value.content.vote && msg.value.content.vote.link) {
41 var likes = get_likes(msg.value.content.vote.link)()
42 if (!likes[msg.value.author] || likes[msg.value.author][1] < msg.timestamp) {
43 likes[msg.value.author] = [msg.value.content.vote.value > 0, msg.timestamp]
44 get_likes(msg.value.content.vote.link).set(likes)
45 }
46 }
47 } else if (c.type === 'post' && typeof c.channel === 'string') {
48 var name = c.channel.trim()
49 if (name) {
50 var channel = channelsLookup.get(name)
51 if (!channel) {
52 channel = MutantStruct({
53 id: name,
54 updatedAt: Value()
55 })
56 channelsLookup.put(name, channel)
57 }
58 if (channel.updatedAt() < msg.timestamp) {
59 channel.updatedAt.set(msg.timestamp)
60 }
61 }
62 }
63 }
64 }
65}
66

Built with git-ssb-web