-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsparql-client.mjs
32 lines (28 loc) · 1 KB
/
sparql-client.mjs
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
/* Minimal SPARQL client */
import axios from 'axios';
function validURL(str) {
const pattern = new RegExp('^(https?:\\/\\/)?' // protocol
+
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' // domain name
+
'((\\d{1,3}\\.){3}\\d{1,3}))' // OR ip (v4) address
+
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' // port and path
+
'(\\?[;&a-z\\d%_.~+=-]*)?' // query string
+
'(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
return !!pattern.test(str);
}
export default class SparqlClient {
constructor(endpoint) {
if (!endpoint || !validURL(endpoint)) throw new Error(`Not valid endpoint: ${endpoint}`);
this.endpoint = endpoint;
}
query(q, params = {}) {
return axios.post(this.endpoint, new URLSearchParams({...params, query: q })).then((res) => {
if (Math.floor(res.status / 100) == 2) return res.data; // all 2xx status (200, 206, ...)
throw new Error(res.statusText);
});
}
}