var fetch = require('node-fetch') var db = require('../db') module.exports = { route: (app) => { app.put('/raw/import/thread/', importRaw('thread', 'Thread'), (req, res) => res.send({ status: 'ok' })) app.put('/raw/import/keyword/', importRaw('keyword', 'Keyword'), (req, res) => res.send({ status: 'ok' })) app.put('/raw/import/file/', importRaw('file', 'File'), (req, res) => res.send({ status: 'ok' })) app.put('/raw/import/comment/', importRaw('comment', '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) db[model].forge(req.body).save().then((el) => { res.el = el; next() }).catch(e => { console.error(e) 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() }).catch(e => { console.error(e) 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.stringify(json), headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, }).then((res) => {return res.json()}) .then((json) => console.log(json)) } } }