-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (42 loc) · 1.28 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
'use strict'
var qFlat = require('q-flat')
var URL = require('mini-url')
var QS = require('mini-querystring')
var extend = require('just-extend')
module.exports = function () {
return function refreshWithMiddleware (ctx, next) {
var req = ctx.req
var res = ctx.res
res.refreshWith = function refreshWith (setters, opts) {
opts = opts || {}
var href = (opts.url === 'back' && (req.get('Referrer') || opts.alt)) || opts.url || req.href
var parsed = URL.parse(href, req.href)
var query = QS.parse(parsed.search, true)
var search = QS.stringify(cast(qFlat(extend(true, query, setters))))
if (search) search = '?' + search
res.redirect(URL.stringify({
protocol: parsed.protocol,
host: parsed.host,
pathname: parsed.pathname,
search: search,
hash: opts.hash || parsed.hash
}))
}
return next()
}
}
/**
* Ignores empty strings and undefined.
* Converts date to iso string.
* Converts everything else to a string.
*/
function cast (data) {
var result = {}
for (var key in data) {
var val = data[key]
if (val === '' || val === undefined) continue
else if (val instanceof Date && isFinite(val)) result[key] = val.toISOString()
else result[key] = String(val)
}
return result
}