-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
100 lines (82 loc) · 2.33 KB
/
index.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
module.exports = hapiCouchDbStore
hapiCouchDbStore.attributes = {
name: 'store'
}
var url = require('url')
var boom = require('boom')
var hapiToExpress = require('@gr2m/hapi-to-express')
var StoreFactory = require('@hoodie/store-server-api')
var toCouchDbUrl = require('./utils/pouchdb-options-to-couchdb-url')
var validDbName = /^[a-z]/ // must begin with a lowercase letter
function hapiCouchDbStore (server, options, next) {
var api = StoreFactory(options.PouchDB)
// if connected to a CouchDb, we proxy the requests right through.
// Otherwise we load express-pouchdb and proxy the request to the express app
if (api.adapter === 'http') {
// workaround for https://github.com/pouchdb/pouchdb/issues/5548
var couchDbUrl = toCouchDbUrl(new options.PouchDB('hack', {skip_setup: true}).__opts)
server.register({
register: require('h2o2'),
once: true
})
} else {
var xapp = require('express-pouchdb')(options.PouchDB, {
mode: 'minimumForPouchDB'
})
xapp.disable('x-powered-by')
}
if (options.hooks) {
Object.keys(options.hooks).forEach(function (type) {
server.ext({
type: type,
method: options.hooks[type],
options: {
sandbox: 'plugin'
}
})
})
}
server.expose({
api: api
})
server.route({
method: 'GET',
path: '/{path*}',
handler: handler
})
server.route({
method: ['PUT', 'POST', 'COPY', 'DELETE'],
path: '/{path*}',
config: {
payload: {
output: 'stream',
parse: false
}
},
handler: handler
})
function handler (request, reply) {
var rawUrl = request.raw.req.url.replace((server.realm.modifiers.route.prefix || '') + '/', '')
var path = rawUrl.split('/')
var dbname = path.shift()
if (!dbname) {
return reply({couchdb: 'Welcome', ok: true})
}
if (!validDbName.test(dbname)) {
return reply(boom.notFound('database not found'))
}
var newUrl = '/' + dbname + '/' + path.join('/')
if (api.adapter === 'http') {
return reply.proxy({
passThrough: true,
mapUri: function (request, callback) {
callback(null, url.resolve(couchDbUrl, newUrl))
}
})
}
var hapress = hapiToExpress(request, reply)
hapress.req.url = newUrl
xapp(hapress.req, hapress.res)
}
next()
}