@gandalan/weblibs 1.5.11 → 1.5.13

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/README.md CHANGED
@@ -8,6 +8,7 @@ Example:
8
8
  import { fetchEnvConfig, fluentApi, fluentIdasAuthManager } from '@gandalan/weblibs';
9
9
 
10
10
  async function initializeAuthAndApi() {
11
+ const serviceName = 'myService'
11
12
  const appToken = 'your-app-token';
12
13
  const envConfig = await fetchEnvConfig('dev'); // Replace 'dev' with your desired environment
13
14
 
@@ -16,8 +17,8 @@ async function initializeAuthAndApi() {
16
17
  return; // init() has redirected to login.
17
18
  }
18
19
 
19
- globalThis.idas = fluentApi(envConfig.idas, authManager); // IDAS-API instance
20
- globalThis.api = fluentApi("/api/", authManager); // Local API instance
20
+ globalThis.idas = fluentApi(envConfig.idas, authManager, serviceName); // IDAS-API instance
21
+ globalThis.api = fluentApi("/api/", authManager, serviceName); // Local API instance
21
22
  }
22
23
  ```
23
24
 
package/api/fluentApi.js CHANGED
@@ -4,8 +4,10 @@ import { restClient } from "./fluentRestClient";
4
4
  * @typedef {Object} FluentApi
5
5
  * @property {string} baseUrl - The base URL for API requests.
6
6
  * @property {import("./fluentAuthManager").FluentAuthManager} authManager - The authentication manager.
7
+ * @property {string} serviceName - The name of the service using this API.
7
8
  * @property {function(string) : FluentApi} useBaseUrl - Sets the base URL for API requests and returns the FluentApi object.
8
9
  * @property {function(fluentAuthManager) : FluentApi} useAuthManager - Sets the auth manager and returns the FluentApi object.
10
+ * @property {function(string) : FluentApi} useServiceName - Sets the service name and returns the FluentApi object.
9
11
  * @property {function(string) : Promise<object|Array<any>>} get - Async function to perform GET requests.
10
12
  * @property {function(string, object|null) : Promise<object|Array<any>>} put - Async function to perform PUT requests with a payload.
11
13
  * @property {function(string, object|null) : Promise<object|Array<any>>} post - Async function to perform POST requests with a payload.
@@ -21,6 +23,7 @@ export function createApi() {
21
23
  return {
22
24
  authManager: {},
23
25
  baseUrl: "",
26
+ serviceName: "unknownService",
24
27
 
25
28
  /**
26
29
  * Sets the base URL for API requests.
@@ -44,6 +47,17 @@ export function createApi() {
44
47
  return this;
45
48
  },
46
49
 
50
+ /**
51
+ * Sets the service name for this API client.
52
+ *
53
+ * @param {string} name - The name of the service using this API.
54
+ * @return {FluentApi}
55
+ */
56
+ useServiceName(name) {
57
+ this.serviceName = name ?? this.serviceName;
58
+ return this;
59
+ },
60
+
47
61
  /**
48
62
  * Sends a GET request, ensuring authentication if needed.
49
63
  *
@@ -105,7 +119,10 @@ export function createApi() {
105
119
  * @returns {import("./fluentRestClient").FluentRESTClient}
106
120
  */
107
121
  createRestClient() {
108
- return restClient().useBaseUrl(this.baseUrl).useToken(this.authManager?.token);
122
+ return restClient()
123
+ .useBaseUrl(this.baseUrl)
124
+ .useToken(this.authManager?.token)
125
+ .useUserAgent(`gandalan/weblibs-${this.serviceName}`);
109
126
  },
110
127
 
111
128
  /**
@@ -129,16 +146,18 @@ export function createApi() {
129
146
  *
130
147
  * - Requests will be sent to the url provided.
131
148
  * - Example usage:
132
- * const api = fluentApi("https://jsonplaceholder.typicode.com/todos/", null);
149
+ * const api = fluentApi("https://jsonplaceholder.typicode.com/todos/", null, "myService");
133
150
  * api.get("1"); // Sends a GET request to https://jsonplaceholder.typicode.com/todos/1.
134
151
  *
135
152
  * @export
136
153
  * @param {string} url - The base URL for API requests.
137
154
  * @param {import("./fluentAuthManager").FluentAuthManager} authManager - The authentication manager instance.
155
+ * @param {string} serviceName - The name of the service using this API.
138
156
  * @return {FluentApi} Configured API instance for local use.
139
157
  */
140
- export function fluentApi(url, authManager) {
158
+ export function fluentApi(url, authManager, serviceName) {
141
159
  return createApi()
142
160
  .useAuthManager(authManager)
143
- .useBaseUrl(url);
161
+ .useBaseUrl(url)
162
+ .useServiceName(serviceName);
144
163
  }
@@ -4,6 +4,7 @@
4
4
  * @property {string} token - The JWT token for authorization.
5
5
  * @property {function(string) : FluentRESTClient} useBaseUrl - Function to set the base URL and return the FluentApi object.
6
6
  * @property {function(string) : FluentRESTClient} useToken - Function to set the JWT token and return the FluentApi object.
7
+ * @property {function(string) : FluentRESTClient} useUserAgent - Function to set the user agent and return the FluentApi object.
7
8
  * @property {function(string) : object|Array<any>} get - Async function to perform GET requests.
8
9
  * @property {function(string, object) : object|Array<any>} put - Async function to perform PUT requests with a payload.
9
10
  * @property {function(string, object|FormData) : object|Array<any>} post - Async function to perform POST requests with a payload.
@@ -18,6 +19,7 @@ export function restClient() {
18
19
  return {
19
20
  baseUrl: "",
20
21
  token: "",
22
+ userAgent: "",
21
23
 
22
24
  /**
23
25
  * set the base URL for all requests
@@ -39,6 +41,16 @@ export function restClient() {
39
41
  this.token = jwtToken; return this;
40
42
  },
41
43
 
44
+ /**
45
+ * set the user agent for all requests
46
+ *
47
+ * @param {string} [userAgent=""]
48
+ * @returns {FluentRESTClient}
49
+ */
50
+ useUserAgent(userAgent = "") {
51
+ this.userAgent = userAgent; return this;
52
+ },
53
+
42
54
  /**
43
55
  * GET request to the specified URL
44
56
  *
@@ -49,7 +61,7 @@ export function restClient() {
49
61
  */
50
62
  async get(url = "", auth = true) {
51
63
  const finalUrl = `${this.baseUrl}${url}`;
52
- const headers = this.token ? { "Authorization": `Bearer ${this.token}` } : {};
64
+ const headers = this._createHeaders();
53
65
  const res = await fetch(finalUrl, { method: "GET", headers });
54
66
  if (res.ok) {
55
67
  return await this._parseReponse(res);
@@ -68,7 +80,7 @@ export function restClient() {
68
80
  */
69
81
  async put(url = "", payload = {}) {
70
82
  const finalUrl = `${this.baseUrl}${url}`;
71
- const headers = this.token ? { "Authorization": `Bearer ${this.token}`, "Content-Type": "application/json" } : {};
83
+ const headers = this._createHeaders("application/json");
72
84
  const res = await fetch(finalUrl, { method: "PUT", body: JSON.stringify(payload), headers });
73
85
  if (res.ok) {
74
86
  return await this._parseReponse(res);
@@ -87,15 +99,16 @@ export function restClient() {
87
99
  */
88
100
  async post(url = "", payload = {}) {
89
101
  const finalUrl = `${this.baseUrl}${url}`;
90
- const headers = this.token ? { "Authorization": `Bearer ${this.token}` } : {};
102
+ let headers;
91
103
 
92
104
  // Determine the body and headers based on the payload type
93
105
  let body;
94
106
  if (payload instanceof FormData) {
107
+ headers = this._createHeaders();
95
108
  body = payload;
96
109
  } else {
110
+ headers = this._createHeaders("application/json");
97
111
  body = JSON.stringify(payload);
98
- headers["Content-Type"] = "application/json";
99
112
  }
100
113
 
101
114
  const res = await fetch(finalUrl, { method: "POST", body, headers });
@@ -115,7 +128,7 @@ export function restClient() {
115
128
  */
116
129
  async delete(url = "") {
117
130
  const finalUrl = `${this.baseUrl}${url}`;
118
- const headers = this.token ? { "Authorization": `Bearer ${this.token}` } : {};
131
+ const headers = this._createHeaders();
119
132
  const res = await fetch(finalUrl, { method: "DELETE", headers });
120
133
  if (res.ok) {
121
134
  return await this._parseReponse(res);
@@ -124,6 +137,14 @@ export function restClient() {
124
137
  throw new Error(`DELETE ${finalUrl} failed: ${res.status} ${res.statusText}`);
125
138
  },
126
139
 
140
+ _createHeaders(contentType) {
141
+ return new Headers({
142
+ ...(contentType && { "Content-Type": contentType }),
143
+ ...(this.token && { "Authorization": `Bearer ${this.token}` }),
144
+ ...(this.userAgent && { "User-Agent": this.userAgent })
145
+ });
146
+ },
147
+
127
148
  async _parseReponse(res) {
128
149
  // check if repsonse is JSON, then return parsed JSON, otherwise return text
129
150
  const contentType = res.headers.get("content-type");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gandalan/weblibs",
3
- "version": "1.5.11",
3
+ "version": "1.5.13",
4
4
  "description": "WebLibs for Gandalan JS/TS projects",
5
5
  "keywords": [
6
6
  "gandalan"