-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
80 lines (60 loc) · 1.5 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
var linkParser = require('http-link').parse
var concat = require('concat-stream')
var request = require('hyperquest')
var formatTime = require('./lib/format-time')
var GATE_URL = 'http://web.archive.org/web/timemap/link/'
module.exports = memento
function memento (url, opts, cb) {
var gateway
if (!cb) {
cb = opts
opts = {}
}
gateway = opts.host || GATE_URL
if (!opts.time) {
return getAll()
}
var headers = {'accept-datetime': formatTime(opts.time)}
request(gateway + url, {headers: headers}, parseResponse)
function parseResponse (err, res) {
if (err) {
return cb(err)
}
if (!res.headers.link || !res.headers.link.length) {
return cb(null, [])
}
try {
cb(null, linkParser(res.headers.link).filter(nonMementos))
} catch (e) {
cb(e)
}
}
function getAll () {
request(gateway + url, parseTimemaps)
}
function parseTimemaps (err, res) {
if (err) {
return cb(err)
}
if (res.statusCode === 404) {
return cb(null, [])
} else if (res.statusCode !== 200) {
return cb(new Error('request failure ' + res.statusCode))
}
res.pipe(concat(parseLinks))
function parseLinks (result) {
if (!result || !result.length) {
return cb(null, [])
}
result = result.toString()
try {
cb(null, linkParser(result))
} catch (e) {
cb(e)
}
}
}
}
function nonMementos (x) {
return x && x.rel && x.rel !== 'original' && x.rel !== 'timemap'
}