git ssb

1+

bencevans / ssb-news



Tree: bb1d879ac72e9462c12547ce70a4ccba104a1066

Files: bb1d879ac72e9462c12547ce70a4ccba104a1066 / src / server.js

1726 bytesRaw
1const http = require('http')
2const app = require('./main')
3const SSBNews = require('.')
4const async = require('async')
5const getUserAbout = require('./helpers/get-user-about')
6const body = require('body/form')
7
8module.exports = function createServer (sbot) {
9 const state = {
10 recent: [],
11 user: ''
12 }
13
14 const news = new SSBNews(sbot)
15 state.user = sbot.id
16
17 news.recent((err, stories) => {
18 if (err) {
19 throw err
20 }
21
22 async.map(stories, (story, cb) => {
23 getUserAbout(sbot, story.value.author, (err, author) => {
24 if (err) return cb(err)
25 story._author = author
26 cb(null, story)
27 })
28 }, (err, storiesWithAuthor) => {
29 if (err) {
30 throw err
31 }
32 state.recent = storiesWithAuthor
33 })
34 })
35
36 const server = http.createServer((req, res) => {
37 try {
38 if (req.url.match(/^\/story\/(.+)/)) {
39 const key = '%' + req.url.match(/^\/story\/(.+)/)[1]
40 news.story(key, (err, story) => {
41 if (err) throw err
42 getUserAbout(sbot, story.author, (err, author) => {
43 if (err) throw err
44 story._author = author
45 const dom = app.toString(req.url, Object.assign({}, state, { story }))
46 res.end(dom)
47 })
48 })
49 } else if (req.method === 'POST' && req.url === '/new') {
50 body(req, (err, form) => {
51 if (err) { throw err }
52 news.publish(form, (err, msg) => {
53 if (err) throw err
54 res.end(msg.key)
55 })
56 })
57 } else {
58 const dom = app.toString(req.url, state)
59 res.end(dom)
60 }
61 } catch (err) {
62 console.error(err)
63 res.end('404')
64 }
65 })
66
67 server.listen(3000)
68}
69

Built with git-ssb-web