This repository has been archived by the owner on Jan 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpost.js
58 lines (51 loc) · 1.43 KB
/
post.js
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
const logger = require('./logger')
const fetch = require('node-fetch')
const mongoose = require('mongoose')
const ipfs = require('ipfs-http-client')(
process.env.IPFS_ADDRESS,
process.env.IPFS_PORT,
{
protocol: process.env.IPFS_PROTOCOL,
}
)
module.exports = ({ User }) => (userID, post) => new Promise(function (resolve, reject) {
if (!mongoose.Types.ObjectId.isValid(`${userID}`)) {
reject(Error(`invalid userID : ${userID}`))
}
const userOID = new mongoose.Types.ObjectId(`${userID}`)
const postString = JSON.stringify(post)
const buf = Buffer.from(postString, 'utf8')
// add to ipfs
ipfs.block.put(buf)
.then(block => {
// block has been stored
const key = block.cid.toBaseEncodedString()
logger.debug(`${key} : ${block.data.toString()}`)
return key
})
.then(key => new Promise(function (resolve, reject) {
// add post to user
const post = {
hash: key,
publishers: [
{ service: 'twitter' },
],
date: Date.now(),
}
User.updateOne(
{ '_id': userOID },
{ '$push': { 'posts': post } },
function (err, raw) {
if (err !== null) {
reject(err)
}
resolve(key)
}
)
}))
.then(key =>
// publish
fetch(`http://${process.env.PUBLISHER_ADDRESS}/twitter/${userID}/${key}`))
.then(() => resolve())
.catch(err => reject(err))
})