|
1 | 1 | module.exports = get |
2 | 2 |
|
3 | | -const request = require('request') |
| 3 | +const fetch = require('node-fetch') |
4 | 4 | const url = require('url') |
5 | 5 |
|
6 | 6 | function get (webid, callback) { |
7 | | - const uri = url.URL(webid) |
8 | | - const options = { |
9 | | - url: uri, |
10 | | - method: 'GET', |
11 | | - headers: { |
12 | | - Accept: 'text/turtle, application/ld+json' |
13 | | - } |
| 7 | + let uri |
| 8 | + try { |
| 9 | + uri = new url.URL(webid) |
| 10 | + } catch (err) { |
| 11 | + return callback(new Error('Invalid WebID URI: ' + webid + ': ' + err.message)) |
14 | 12 | } |
15 | 13 |
|
16 | | - request(options, function (err, res, body) { |
17 | | - if (err) { |
18 | | - return callback(new Error('Failed to fetch profile from ' + uri.href + ': ' + err)) |
19 | | - } |
20 | | - |
21 | | - if (res.statusCode !== 200) { |
22 | | - return callback(new Error('Failed to retrieve WebID from ' + uri.href + ': HTTP ' + res.statusCode)) |
23 | | - } |
| 14 | + const headers = { |
| 15 | + Accept: 'text/turtle, application/ld+json' |
| 16 | + } |
24 | 17 |
|
25 | | - callback(null, body, res.headers['content-type']) |
26 | | - }) |
| 18 | + fetch(uri.href, { method: 'GET', headers }) |
| 19 | + .then(async res => { |
| 20 | + if (!res.ok) { |
| 21 | + return callback(new Error('Failed to retrieve WebID from ' + uri.href + ': HTTP ' + res.status)) |
| 22 | + } |
| 23 | + const contentType = res.headers.get('content-type') |
| 24 | + let body |
| 25 | + if (contentType && contentType.includes('json')) { |
| 26 | + body = JSON.stringify(await res.json(), null, 2) |
| 27 | + } else { |
| 28 | + body = await res.text() |
| 29 | + } |
| 30 | + callback(null, body, contentType) |
| 31 | + }) |
| 32 | + .catch(err => { |
| 33 | + return callback(new Error('Failed to fetch profile from ' + uri.href + ': ' + err)) |
| 34 | + }) |
27 | 35 | } |
0 commit comments