Files: 7e467f6efa8f6320f4c92bbfbe6e905689e0b8eb / http / server.js
1553 bytesRaw
1 | const Url = require('url') |
2 | const defined = require('defined') |
3 | const getIn = require('get-in') |
4 | const toPull = require('stream-to-pull-stream') |
5 | const pull = require('pull-stream') |
6 | |
7 | const defaultSerialize = require('../serialize') |
8 | |
9 | module.exports = createHttpServerHandler |
10 | |
11 | function createHttpServerHandler (server, options) { |
12 | const serialize = defined(options.serialize, defaultSerialize) |
13 | |
14 | const handler = function (req, res, next) { |
15 | const url = Url.parse(req.headers.host + req.url, true) |
16 | const name = url.pathname.split('/').slice(1) |
17 | const options = url.query |
18 | |
19 | const type = getIn(server.manifest, name) |
20 | const call = getIn(server.methods, name) |
21 | |
22 | if (!(type && call)) return next() |
23 | |
24 | switch (type) { |
25 | case 'source': |
26 | return pull( |
27 | call(options), |
28 | serialize.stringify(), |
29 | toPull.sink(res) |
30 | ) |
31 | case 'sink': |
32 | return pull( |
33 | toPull.source(req), |
34 | serialize.parse(), |
35 | call(options) |
36 | ) |
37 | case 'async': |
38 | return call(options, cb) |
39 | case 'sync': |
40 | var value |
41 | try { |
42 | value = call(options) |
43 | } catch (err) { |
44 | return cb(err) |
45 | } |
46 | return cb(null, value) |
47 | } |
48 | |
49 | function cb (err, value) { |
50 | if (err) return next(err) |
51 | |
52 | res.setHeader('Content-Type', 'application/json') |
53 | res.end(JSON.stringify(value, null, 2)) |
54 | } |
55 | } |
56 | |
57 | return handler |
58 | } |
59 | |
60 | function isString (s) { |
61 | return 'string' === typeof s |
62 | } |
63 | |
64 | function isObject (o) { |
65 | return o && 'object' === typeof o |
66 | } |
67 |
Built with git-ssb-web