summaryrefslogtreecommitdiff
path: root/bucky/app/federate.js
blob: 01b85a1df70d0a6a0ed5c646c23238ab79b455e9 (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
var fetch = require('node-fetch')
var db = require('../db')

module.exports = {

  route: (app) => {
    app.put('/raw/import/thread/',  importRaw('thread', db.Thread),  (req, res) => res.send({ status: 'ok' }))
    app.put('/raw/import/keyword/', importRaw('keyword', db.Keyword), (req, res) => res.send({ status: 'ok' }))
    app.put('/raw/import/file/',    importRaw('file', db.File),    (req, res) => res.send({ status: 'ok' }))
    app.put('/raw/import/comment/', importRaw('comment', db.Comment), (req, res) => res.send({ status: 'ok' }))

    app.get('/raw/export/thread/:id',  exportThread,  (req, res) => res.send({ status: 'ok' }))
    app.get('/raw/export/keyword/:keyword', exportKeyword, (req, res) => res.send({ status: 'ok' }))

    function importRaw (type, model) {
      return (req, res, next) => {
        console.log('importing', type, req.body.id)
        new model(req.body).save().then((el) => {
          res.el = el;
          next()
        })
      }
    }
    function exportKeyword (req, res, next) {
      console.log('export keyword', req.params.keyword)
      db.getKeyword(req.params.keyword).then(keyword => {
        send("keyword", keyword)
        return db.getThreadsForKeyword(keyword)
      }).then(threads => {
        var promises = threads.map(thread => {
          exportThread({ params: { id: thread.get('id') } }, res, function(){})
        })
        return Promise.all(promises)
      }).then( () => {
        next()
      })
    }
    function exportThread (req, res, next) {
      return db.getThread(req.params.id).then(thread => {
        send("thread", thread)
        return db.getCommentsForThread(req.params.id)
      }).then(comments => {
        var promises = comments.map(comment => send("comment", comment))
        return Promise.all(promises)
      }).then( () => {
        return db.getFilesForThread(req.params.id)
      }).then(files => {
        var promises = files.map(comment => send("comment", comment))
        return promises
      }).then( () => {
        next()
      })
    }
    function send(type, data){
      console.log('sending', type, data.get('id'))
      var json = data.toJSON()
      fetch("https://bucky.asdf.us/raw/import/" + type, {
        method: 'PUT',
        body: json,
        headers: { 'content-type': 'application/json; charset=utf-8' },
      }).then(() => {})
    }

  }
}