@matdata/yasqe 4.6.1 → 4.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sparql.ts CHANGED
@@ -1,215 +1,215 @@
1
- import { default as Yasqe, Config, RequestConfig } from "./";
2
- import { merge, isFunction } from "lodash-es";
3
- import * as queryString from "query-string";
4
- export type YasqeAjaxConfig = Config["requestConfig"];
5
- export interface PopulatedAjaxConfig {
6
- url: string;
7
- reqMethod: "POST" | "GET";
8
- headers: { [key: string]: string };
9
- accept: string;
10
- args: RequestArgs;
11
- withCredentials: boolean;
12
- }
13
- function getRequestConfigSettings(yasqe: Yasqe, conf?: Partial<Config["requestConfig"]>): RequestConfig<Yasqe> {
14
- if (isFunction(conf)) {
15
- return conf(yasqe) as RequestConfig<Yasqe>;
16
- }
17
- return (conf ?? {}) as RequestConfig<Yasqe>;
18
- }
19
- // type callback = AjaxConfig.callbacks['complete'];
20
- export function getAjaxConfig(
21
- yasqe: Yasqe,
22
- _config: Partial<Config["requestConfig"]> = {},
23
- ): PopulatedAjaxConfig | undefined {
24
- const config: RequestConfig<Yasqe> = merge(
25
- {},
26
- getRequestConfigSettings(yasqe, yasqe.config.requestConfig),
27
- getRequestConfigSettings(yasqe, _config),
28
- );
29
- if (!config.endpoint || config.endpoint.length == 0) return; // nothing to query!
30
-
31
- var queryMode = yasqe.getQueryMode();
32
- /**
33
- * initialize ajax config
34
- */
35
- const endpoint = isFunction(config.endpoint) ? config.endpoint(yasqe) : config.endpoint;
36
- var reqMethod: "GET" | "POST" =
37
- queryMode == "update" ? "POST" : isFunction(config.method) ? config.method(yasqe) : config.method;
38
- const headers = isFunction(config.headers) ? config.headers(yasqe) : config.headers;
39
- // console.log({headers})
40
- const withCredentials = isFunction(config.withCredentials) ? config.withCredentials(yasqe) : config.withCredentials;
41
- return {
42
- reqMethod,
43
- url: endpoint,
44
- args: getUrlArguments(yasqe, config),
45
- headers: headers,
46
- accept: getAcceptHeader(yasqe, config),
47
- withCredentials,
48
- };
49
- /**
50
- * merge additional request headers
51
- */
52
- }
53
-
54
- export async function executeQuery(yasqe: Yasqe, config?: YasqeAjaxConfig): Promise<any> {
55
- const queryStart = Date.now();
56
- try {
57
- yasqe.emit("queryBefore", yasqe, config);
58
- const populatedConfig = getAjaxConfig(yasqe, config);
59
- if (!populatedConfig) {
60
- return; // Nothing to query
61
- }
62
- const abortController = new AbortController();
63
-
64
- const fetchOptions: RequestInit = {
65
- method: populatedConfig.reqMethod,
66
- headers: {
67
- Accept: populatedConfig.accept,
68
- ...(populatedConfig.headers || {}),
69
- },
70
- credentials: populatedConfig.withCredentials ? "include" : "same-origin",
71
- signal: abortController.signal,
72
- };
73
- if (fetchOptions?.headers && populatedConfig.reqMethod === "POST") {
74
- (fetchOptions.headers as Record<string, string>)["Content-Type"] = "application/x-www-form-urlencoded";
75
- }
76
- const searchParams = new URLSearchParams();
77
- for (const key in populatedConfig.args) {
78
- const value = populatedConfig.args[key];
79
- if (Array.isArray(value)) {
80
- value.forEach((v) => searchParams.append(key, v));
81
- } else {
82
- searchParams.append(key, value);
83
- }
84
- }
85
- if (populatedConfig.reqMethod === "POST") {
86
- fetchOptions.body = searchParams.toString();
87
- } else {
88
- const url = new URL(populatedConfig.url);
89
- searchParams.forEach((value, key) => {
90
- url.searchParams.append(key, value);
91
- });
92
- populatedConfig.url = url.toString();
93
- }
94
- const request = new Request(populatedConfig.url, fetchOptions);
95
- yasqe.emit("query", request, abortController);
96
- const response = await fetch(request);
97
- if (!response.ok) {
98
- throw new Error((await response.text()) || response.statusText);
99
- }
100
- // Await the response content and merge with the `Response` object
101
- const queryResponse = {
102
- ok: response.ok,
103
- status: response.status,
104
- statusText: response.statusText,
105
- headers: response.headers,
106
- type: response.type,
107
- content: await response.text(),
108
- };
109
- yasqe.emit("queryResponse", queryResponse, Date.now() - queryStart);
110
- yasqe.emit("queryResults", queryResponse.content, Date.now() - queryStart);
111
- return queryResponse;
112
- } catch (e) {
113
- if (e instanceof Error && e.message === "Aborted") {
114
- // The query was aborted. We should not do or draw anything
115
- } else {
116
- yasqe.emit("queryResponse", e, Date.now() - queryStart);
117
- }
118
- yasqe.emit("error", e);
119
- throw e;
120
- }
121
- }
122
-
123
- export type RequestArgs = { [argName: string]: string | string[] };
124
- export function getUrlArguments(yasqe: Yasqe, _config: Config["requestConfig"]): RequestArgs {
125
- var queryMode = yasqe.getQueryMode();
126
-
127
- var data: RequestArgs = {};
128
- const config: RequestConfig<Yasqe> = getRequestConfigSettings(yasqe, _config);
129
- var queryArg = isFunction(config.queryArgument) ? config.queryArgument(yasqe) : config.queryArgument;
130
- if (!queryArg) queryArg = yasqe.getQueryMode();
131
- data[queryArg] = config.adjustQueryBeforeRequest ? config.adjustQueryBeforeRequest(yasqe) : yasqe.getValue();
132
- /**
133
- * add named graphs to ajax config
134
- */
135
- const namedGraphs = isFunction(config.namedGraphs) ? config.namedGraphs(yasqe) : config.namedGraphs;
136
- if (namedGraphs && namedGraphs.length > 0) {
137
- let argName = queryMode === "query" ? "named-graph-uri" : "using-named-graph-uri ";
138
- data[argName] = namedGraphs;
139
- }
140
- /**
141
- * add default graphs to ajax config
142
- */
143
- const defaultGraphs = isFunction(config.defaultGraphs) ? config.defaultGraphs(yasqe) : config.defaultGraphs;
144
- if (defaultGraphs && defaultGraphs.length > 0) {
145
- let argName = queryMode == "query" ? "default-graph-uri" : "using-graph-uri ";
146
- data[argName] = namedGraphs;
147
- }
148
-
149
- /**
150
- * add additional request args
151
- */
152
- const args = isFunction(config.args) ? config.args(yasqe) : config.args;
153
- if (args && args.length > 0)
154
- merge(
155
- data,
156
- args.reduce((argsObject: { [key: string]: string[] }, arg) => {
157
- argsObject[arg.name] ? argsObject[arg.name].push(arg.value) : (argsObject[arg.name] = [arg.value]);
158
- return argsObject;
159
- }, {}),
160
- );
161
-
162
- return data;
163
- }
164
- export function getAcceptHeader(yasqe: Yasqe, _config: Config["requestConfig"]) {
165
- const config: RequestConfig<Yasqe> = getRequestConfigSettings(yasqe, _config);
166
- var acceptHeader = null;
167
- if (yasqe.getQueryMode() == "update") {
168
- acceptHeader = isFunction(config.acceptHeaderUpdate) ? config.acceptHeaderUpdate(yasqe) : config.acceptHeaderUpdate;
169
- } else {
170
- var qType = yasqe.getQueryType();
171
- if (qType == "DESCRIBE" || qType == "CONSTRUCT") {
172
- acceptHeader = isFunction(config.acceptHeaderGraph) ? config.acceptHeaderGraph(yasqe) : config.acceptHeaderGraph;
173
- } else {
174
- acceptHeader = isFunction(config.acceptHeaderSelect)
175
- ? config.acceptHeaderSelect(yasqe)
176
- : config.acceptHeaderSelect;
177
- }
178
- }
179
- return acceptHeader;
180
- }
181
- export function getAsCurlString(yasqe: Yasqe, _config?: Config["requestConfig"]) {
182
- let ajaxConfig = getAjaxConfig(yasqe, getRequestConfigSettings(yasqe, _config));
183
- if (!ajaxConfig) return "";
184
- let url = ajaxConfig.url;
185
- if (ajaxConfig.url.indexOf("http") !== 0) {
186
- //this is either a relative or absolute url, which is not supported by CURL.
187
- //Add domain, schema, etc etc
188
- url = `${window.location.protocol}//${window.location.host}`;
189
- if (ajaxConfig.url.indexOf("/") === 0) {
190
- //its an absolute path
191
- url += ajaxConfig.url;
192
- } else {
193
- //relative, so append current location to url first
194
- url += window.location.pathname + ajaxConfig.url;
195
- }
196
- }
197
- const segments: string[] = ["curl"];
198
-
199
- if (ajaxConfig.reqMethod === "GET") {
200
- url += `?${queryString.stringify(ajaxConfig.args)}`;
201
- segments.push(url);
202
- } else if (ajaxConfig.reqMethod === "POST") {
203
- segments.push(url);
204
- segments.push("--data", queryString.stringify(ajaxConfig.args));
205
- } else {
206
- // I don't expect to get here but let's be sure
207
- console.warn("Unexpected request-method", ajaxConfig.reqMethod);
208
- segments.push(url);
209
- }
210
- segments.push("-X", ajaxConfig.reqMethod);
211
- for (const header in ajaxConfig.headers) {
212
- segments.push(`-H '${header}: ${ajaxConfig.headers[header]}'`);
213
- }
214
- return segments.join(" ");
215
- }
1
+ import { default as Yasqe, Config, RequestConfig } from "./";
2
+ import { merge, isFunction } from "lodash-es";
3
+ import * as queryString from "query-string";
4
+ export type YasqeAjaxConfig = Config["requestConfig"];
5
+ export interface PopulatedAjaxConfig {
6
+ url: string;
7
+ reqMethod: "POST" | "GET";
8
+ headers: { [key: string]: string };
9
+ accept: string;
10
+ args: RequestArgs;
11
+ withCredentials: boolean;
12
+ }
13
+ function getRequestConfigSettings(yasqe: Yasqe, conf?: Partial<Config["requestConfig"]>): RequestConfig<Yasqe> {
14
+ if (isFunction(conf)) {
15
+ return conf(yasqe) as RequestConfig<Yasqe>;
16
+ }
17
+ return (conf ?? {}) as RequestConfig<Yasqe>;
18
+ }
19
+ // type callback = AjaxConfig.callbacks['complete'];
20
+ export function getAjaxConfig(
21
+ yasqe: Yasqe,
22
+ _config: Partial<Config["requestConfig"]> = {},
23
+ ): PopulatedAjaxConfig | undefined {
24
+ const config: RequestConfig<Yasqe> = merge(
25
+ {},
26
+ getRequestConfigSettings(yasqe, yasqe.config.requestConfig),
27
+ getRequestConfigSettings(yasqe, _config),
28
+ );
29
+ if (!config.endpoint || config.endpoint.length == 0) return; // nothing to query!
30
+
31
+ var queryMode = yasqe.getQueryMode();
32
+ /**
33
+ * initialize ajax config
34
+ */
35
+ const endpoint = isFunction(config.endpoint) ? config.endpoint(yasqe) : config.endpoint;
36
+ var reqMethod: "GET" | "POST" =
37
+ queryMode == "update" ? "POST" : isFunction(config.method) ? config.method(yasqe) : config.method;
38
+ const headers = isFunction(config.headers) ? config.headers(yasqe) : config.headers;
39
+ // console.log({headers})
40
+ const withCredentials = isFunction(config.withCredentials) ? config.withCredentials(yasqe) : config.withCredentials;
41
+ return {
42
+ reqMethod,
43
+ url: endpoint,
44
+ args: getUrlArguments(yasqe, config),
45
+ headers: headers,
46
+ accept: getAcceptHeader(yasqe, config),
47
+ withCredentials,
48
+ };
49
+ /**
50
+ * merge additional request headers
51
+ */
52
+ }
53
+
54
+ export async function executeQuery(yasqe: Yasqe, config?: YasqeAjaxConfig): Promise<any> {
55
+ const queryStart = Date.now();
56
+ try {
57
+ yasqe.emit("queryBefore", yasqe, config);
58
+ const populatedConfig = getAjaxConfig(yasqe, config);
59
+ if (!populatedConfig) {
60
+ return; // Nothing to query
61
+ }
62
+ const abortController = new AbortController();
63
+
64
+ const fetchOptions: RequestInit = {
65
+ method: populatedConfig.reqMethod,
66
+ headers: {
67
+ Accept: populatedConfig.accept,
68
+ ...(populatedConfig.headers || {}),
69
+ },
70
+ credentials: populatedConfig.withCredentials ? "include" : "same-origin",
71
+ signal: abortController.signal,
72
+ };
73
+ if (fetchOptions?.headers && populatedConfig.reqMethod === "POST") {
74
+ (fetchOptions.headers as Record<string, string>)["Content-Type"] = "application/x-www-form-urlencoded";
75
+ }
76
+ const searchParams = new URLSearchParams();
77
+ for (const key in populatedConfig.args) {
78
+ const value = populatedConfig.args[key];
79
+ if (Array.isArray(value)) {
80
+ value.forEach((v) => searchParams.append(key, v));
81
+ } else {
82
+ searchParams.append(key, value);
83
+ }
84
+ }
85
+ if (populatedConfig.reqMethod === "POST") {
86
+ fetchOptions.body = searchParams.toString();
87
+ } else {
88
+ const url = new URL(populatedConfig.url);
89
+ searchParams.forEach((value, key) => {
90
+ url.searchParams.append(key, value);
91
+ });
92
+ populatedConfig.url = url.toString();
93
+ }
94
+ const request = new Request(populatedConfig.url, fetchOptions);
95
+ yasqe.emit("query", request, abortController);
96
+ const response = await fetch(request);
97
+ if (!response.ok) {
98
+ throw new Error((await response.text()) || response.statusText);
99
+ }
100
+ // Await the response content and merge with the `Response` object
101
+ const queryResponse = {
102
+ ok: response.ok,
103
+ status: response.status,
104
+ statusText: response.statusText,
105
+ headers: response.headers,
106
+ type: response.type,
107
+ content: await response.text(),
108
+ };
109
+ yasqe.emit("queryResponse", queryResponse, Date.now() - queryStart);
110
+ yasqe.emit("queryResults", queryResponse.content, Date.now() - queryStart);
111
+ return queryResponse;
112
+ } catch (e) {
113
+ if (e instanceof Error && e.message === "Aborted") {
114
+ // The query was aborted. We should not do or draw anything
115
+ } else {
116
+ yasqe.emit("queryResponse", e, Date.now() - queryStart);
117
+ }
118
+ yasqe.emit("error", e);
119
+ throw e;
120
+ }
121
+ }
122
+
123
+ export type RequestArgs = { [argName: string]: string | string[] };
124
+ export function getUrlArguments(yasqe: Yasqe, _config: Config["requestConfig"]): RequestArgs {
125
+ var queryMode = yasqe.getQueryMode();
126
+
127
+ var data: RequestArgs = {};
128
+ const config: RequestConfig<Yasqe> = getRequestConfigSettings(yasqe, _config);
129
+ var queryArg = isFunction(config.queryArgument) ? config.queryArgument(yasqe) : config.queryArgument;
130
+ if (!queryArg) queryArg = yasqe.getQueryMode();
131
+ data[queryArg] = config.adjustQueryBeforeRequest ? config.adjustQueryBeforeRequest(yasqe) : yasqe.getValue();
132
+ /**
133
+ * add named graphs to ajax config
134
+ */
135
+ const namedGraphs = isFunction(config.namedGraphs) ? config.namedGraphs(yasqe) : config.namedGraphs;
136
+ if (namedGraphs && namedGraphs.length > 0) {
137
+ let argName = queryMode === "query" ? "named-graph-uri" : "using-named-graph-uri ";
138
+ data[argName] = namedGraphs;
139
+ }
140
+ /**
141
+ * add default graphs to ajax config
142
+ */
143
+ const defaultGraphs = isFunction(config.defaultGraphs) ? config.defaultGraphs(yasqe) : config.defaultGraphs;
144
+ if (defaultGraphs && defaultGraphs.length > 0) {
145
+ let argName = queryMode == "query" ? "default-graph-uri" : "using-graph-uri ";
146
+ data[argName] = namedGraphs;
147
+ }
148
+
149
+ /**
150
+ * add additional request args
151
+ */
152
+ const args = isFunction(config.args) ? config.args(yasqe) : config.args;
153
+ if (args && args.length > 0)
154
+ merge(
155
+ data,
156
+ args.reduce((argsObject: { [key: string]: string[] }, arg) => {
157
+ argsObject[arg.name] ? argsObject[arg.name].push(arg.value) : (argsObject[arg.name] = [arg.value]);
158
+ return argsObject;
159
+ }, {}),
160
+ );
161
+
162
+ return data;
163
+ }
164
+ export function getAcceptHeader(yasqe: Yasqe, _config: Config["requestConfig"]) {
165
+ const config: RequestConfig<Yasqe> = getRequestConfigSettings(yasqe, _config);
166
+ var acceptHeader = null;
167
+ if (yasqe.getQueryMode() == "update") {
168
+ acceptHeader = isFunction(config.acceptHeaderUpdate) ? config.acceptHeaderUpdate(yasqe) : config.acceptHeaderUpdate;
169
+ } else {
170
+ var qType = yasqe.getQueryType();
171
+ if (qType == "DESCRIBE" || qType == "CONSTRUCT") {
172
+ acceptHeader = isFunction(config.acceptHeaderGraph) ? config.acceptHeaderGraph(yasqe) : config.acceptHeaderGraph;
173
+ } else {
174
+ acceptHeader = isFunction(config.acceptHeaderSelect)
175
+ ? config.acceptHeaderSelect(yasqe)
176
+ : config.acceptHeaderSelect;
177
+ }
178
+ }
179
+ return acceptHeader;
180
+ }
181
+ export function getAsCurlString(yasqe: Yasqe, _config?: Config["requestConfig"]) {
182
+ let ajaxConfig = getAjaxConfig(yasqe, getRequestConfigSettings(yasqe, _config));
183
+ if (!ajaxConfig) return "";
184
+ let url = ajaxConfig.url;
185
+ if (ajaxConfig.url.indexOf("http") !== 0) {
186
+ //this is either a relative or absolute url, which is not supported by CURL.
187
+ //Add domain, schema, etc etc
188
+ url = `${window.location.protocol}//${window.location.host}`;
189
+ if (ajaxConfig.url.indexOf("/") === 0) {
190
+ //its an absolute path
191
+ url += ajaxConfig.url;
192
+ } else {
193
+ //relative, so append current location to url first
194
+ url += window.location.pathname + ajaxConfig.url;
195
+ }
196
+ }
197
+ const segments: string[] = ["curl"];
198
+
199
+ if (ajaxConfig.reqMethod === "GET") {
200
+ url += `?${queryString.stringify(ajaxConfig.args)}`;
201
+ segments.push(url);
202
+ } else if (ajaxConfig.reqMethod === "POST") {
203
+ segments.push(url);
204
+ segments.push("--data", queryString.stringify(ajaxConfig.args));
205
+ } else {
206
+ // I don't expect to get here but let's be sure
207
+ console.warn("Unexpected request-method", ajaxConfig.reqMethod);
208
+ segments.push(url);
209
+ }
210
+ segments.push("-X", ajaxConfig.reqMethod);
211
+ for (const header in ajaxConfig.headers) {
212
+ segments.push(`-H '${header}: ${ajaxConfig.headers[header]}'`);
213
+ }
214
+ return segments.join(" ");
215
+ }