git ssb

1+

bencevans / ssb-news



Tree: a2cedde098e0580bb46ca8ac1946939cc48fac90

Files: a2cedde098e0580bb46ca8ac1946939cc48fac90 / src / server.js

2104 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.url.match(/^\/user\/(.+)/)) {
50 const userKey = decodeURIComponent(req.url.match(/^\/user\/(.+)/)[1])
51 getUserAbout(sbot, userKey, (err, user) => {
52 if (err) throw err
53 const dom = app.toString(req.url, Object.assign({}, state, { user }))
54 res.end(dom)
55 })
56 } else if (req.method === 'POST' && req.url === '/new') {
57 body(req, (err, form) => {
58 if (err) { throw err }
59 news.publish(form, (err, msg) => {
60 if (err) throw err
61 res.end(msg.key)
62 })
63 })
64 } else {
65 const dom = app.toString(req.url, state)
66 res.end(dom)
67 }
68 } catch (err) {
69 console.error(err)
70 res.end('404')
71 }
72 })
73
74 server.listen(3000)
75
76 console.log('Listening on http://127.0.0.1:3000')
77}
78

Built with git-ssb-web