@sonoransoftware/sonoran.js 1.0.11 → 1.0.12

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.
@@ -55,4 +55,5 @@ export declare class RequestManager extends EventEmitter {
55
55
  removeRateLimit(id: string): void;
56
56
  private createHandler;
57
57
  private static resolveRequestData;
58
+ debug(log: string): void;
58
59
  }
@@ -186,5 +186,8 @@ class RequestManager extends events_1.EventEmitter {
186
186
  };
187
187
  return apiData;
188
188
  }
189
+ debug(log) {
190
+ return this.instance._debugLog(log);
191
+ }
189
192
  }
190
193
  exports.RequestManager = RequestManager;
@@ -94,6 +94,7 @@ class SequentialHandler {
94
94
  const controller = new node_abort_controller_1.AbortController();
95
95
  const timeout = setTimeout(() => controller.abort(), 30000).unref();
96
96
  let res;
97
+ void this.manager.debug(`[${url} Request] - ${JSON.stringify({ url, options, data })}`);
97
98
  try {
98
99
  // node-fetch typings are a bit weird, so we have to cast to any to get the correct signature
99
100
  // Type 'AbortSignal' is not assignable to type 'import('discord.js-modules/node_modules/@types/node-fetch/externals').AbortSignal'
@@ -106,13 +107,13 @@ class SequentialHandler {
106
107
  finally {
107
108
  clearTimeout(timeout);
108
109
  }
110
+ void this.manager.debug(`[${url} Response] - ${JSON.stringify(res)}`);
109
111
  if (res.ok) {
110
112
  const parsedRes = await SequentialHandler.parseResponse(res);
111
113
  return parsedRes;
112
114
  }
113
115
  else if (res.status === 400 || res.status === 401 || res.status === 404) {
114
116
  const parsedRes = await SequentialHandler.parseResponse(res);
115
- // throw new HTTPError(String(parsedRes), res.constructor.name, res.status, data.method, url);
116
117
  throw new errors_1.APIError(parsedRes, data.type, data.fullUrl, res.status, data);
117
118
  }
118
119
  else if (res.status === 429) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sonoransoftware/sonoran.js",
3
- "version": "1.0.11",
3
+ "version": "1.0.12",
4
4
  "description": "Sonoran.js is a library that allows you to interact with the Sonoran CAD and Sonoran CMS API. Based off of and utilizes several Discord.js library techniques for ease of use.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -253,4 +253,8 @@ export class RequestManager extends EventEmitter {
253
253
 
254
254
  return apiData;
255
255
  }
256
+
257
+ debug(log: string) {
258
+ return this.instance._debugLog(log);
259
+ }
256
260
  }
@@ -1,158 +1,161 @@
1
- // import { setTimeout as sleep } from 'node:timers/promises';
2
- import { AsyncQueue } from '@sapphire/async-queue';
3
- import fetch, { RequestInit, Response } from 'node-fetch';
4
- import { AbortController } from "node-abort-controller";
5
- // import { DiscordAPIError, DiscordErrorData, OAuthErrorData } from '../errors/DiscordAPIError';
6
- import { APIError } from '../errors';
7
- import { HTTPError } from '../errors/HTTPError';
8
- // import { RateLimitError } from '../errors/RateLimitError';
9
- import type { RequestManager, APIData, /**RequestData*/ } from '../RequestManager';
10
- import { RateLimitData } from '../REST';
11
- // import { RESTEvents } from '../utils/constants';
12
- // import type { RateLimitData } from '../REST';
13
- import type { IHandler } from './IHandler';
14
-
15
- export class SequentialHandler implements IHandler {
16
- /**
17
- * The unique id of the handler
18
- */
19
- public readonly id: string;
20
-
21
- /**
22
- * The total number of requests that can be made before we are rate limited
23
- */
24
- // private limit = Infinity;
25
-
26
- /**
27
- * The interface used to sequence async requests sequentially
28
- */
29
- // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
30
- #asyncQueue = new AsyncQueue();
31
-
32
- /**
33
- * @param manager The request manager
34
- * @param hash The hash that this RequestHandler handles
35
- * @param majorParameter The major parameter for this handler
36
- */
37
- public constructor(
38
- private readonly manager: RequestManager,
39
- private readonly data: APIData,
40
- ) {
41
- this.id = `${this.data.typePath}:${String(this.data.product)}`;
42
- }
43
-
44
- /**
45
- * If the bucket is currently inactive (no pending requests)
46
- */
47
- public get inactive(): boolean {
48
- return (
49
- this.#asyncQueue.remaining === 0
50
- );
51
- }
52
-
53
- public getMang(): RequestManager {
54
- return this.manager;
55
- }
56
-
57
- /**
58
- * Emits a debug message
59
- * @param message The message to debug
60
- */
61
- // private debug(message: string) {
62
- // this.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);
63
- // }
64
-
65
- /*
66
- * Determines whether the request should be queued or whether a RateLimitError should be thrown
67
- */
68
- // private async onRateLimit(rateLimitData: RateLimitData) {
69
- // const { options } = this.manager;
70
- // if (options.rejectOnRateLimit) {
71
- // throw new RateLimitError(rateLimitData);
72
- // }
73
- // }
74
-
75
- /**
76
- * Queues a request to be sent
77
- * @param routeId The generalized api route with literal ids for major parameters
78
- * @param url The url to do the request on
79
- * @param options All the information needed to make a request
80
- * @param requestData Extra data from the user's request needed for errors and additional processing
81
- */
82
- public async queueRequest(
83
- url: string,
84
- options: RequestInit,
85
- data: APIData
86
- ): Promise<unknown> {
87
- let queue = this.#asyncQueue;
88
- // Wait for any previous requests to be completed before this one is run
89
- await queue.wait();
90
- try {
91
- // Make the request, and return the results
92
- return await this.runRequest(url, options, data);
93
- } finally {
94
- // Allow the next request to fire
95
- queue.shift();
96
- }
97
- }
98
-
99
- /**
100
- * The method that actually makes the request to the api, and updates info about the bucket accordingly
101
- * @param routeId The generalized api route with literal ids for major parameters
102
- * @param url The fully resolved url to make the request to
103
- * @param options The node-fetch options needed to make the request
104
- * @param requestData Extra data from the user's request needed for errors and additional processing
105
- * @param retries The number of retries this request has already attempted (recursion)
106
- */
107
- private async runRequest(
108
- url: string,
109
- options: RequestInit,
110
- data: APIData,
111
- // retries = 0,
112
- ): Promise<unknown> {
113
- const controller = new AbortController();
114
- const timeout = setTimeout(() => controller.abort(), 30000).unref();
115
- let res: Response;
116
-
117
- try {
118
- // node-fetch typings are a bit weird, so we have to cast to any to get the correct signature
119
- // Type 'AbortSignal' is not assignable to type 'import('discord.js-modules/node_modules/@types/node-fetch/externals').AbortSignal'
120
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
121
- res = await fetch(url, { ...options, signal: controller.signal as any });
122
- } catch (error: unknown) {
123
- throw error;
124
- } finally {
125
- clearTimeout(timeout);
126
- }
127
-
128
- if (res.ok) {
129
- const parsedRes = await SequentialHandler.parseResponse(res);
130
- return parsedRes;
131
- } else if (res.status === 400 || res.status === 401 || res.status === 404) {
132
- const parsedRes = await SequentialHandler.parseResponse(res);
133
- // throw new HTTPError(String(parsedRes), res.constructor.name, res.status, data.method, url);
134
- throw new APIError(parsedRes as string, data.type, data.fullUrl, res.status, data);
135
- } else if (res.status === 429) {
136
- const timeout = setTimeout(() => {
137
- this.manager.removeRateLimit(data.requestTypeId);
138
- }, 60 * 1000);
139
- const ratelimitData: RateLimitData = {
140
- product: data.product,
141
- type: data.type,
142
- timeTill: timeout
143
- };
144
- this.manager.onRateLimit(data.requestTypeId, ratelimitData);
145
- } else if (res.status >= 500 && res.status < 600) {
146
- throw new HTTPError(res.statusText, res.constructor.name, res.status, data.method, url);
147
- }
148
- return null;
149
- }
150
-
151
- private static parseResponse(res: Response): Promise<unknown> {
152
- if (res.headers.get('Content-Type')?.startsWith('application/json')) {
153
- return res.json();
154
- }
155
-
156
- return res.text();
157
- }
1
+ // import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { AsyncQueue } from '@sapphire/async-queue';
3
+ import fetch, { RequestInit, Response } from 'node-fetch';
4
+ import { AbortController } from "node-abort-controller";
5
+ // import { DiscordAPIError, DiscordErrorData, OAuthErrorData } from '../errors/DiscordAPIError';
6
+ import { APIError } from '../errors';
7
+ import { HTTPError } from '../errors/HTTPError';
8
+ // import { RateLimitError } from '../errors/RateLimitError';
9
+ import type { RequestManager, APIData, /**RequestData*/ } from '../RequestManager';
10
+ import { RateLimitData } from '../REST';
11
+ // import { RESTEvents } from '../utils/constants';
12
+ // import type { RateLimitData } from '../REST';
13
+ import type { IHandler } from './IHandler';
14
+
15
+ export class SequentialHandler implements IHandler {
16
+ /**
17
+ * The unique id of the handler
18
+ */
19
+ public readonly id: string;
20
+
21
+ /**
22
+ * The total number of requests that can be made before we are rate limited
23
+ */
24
+ // private limit = Infinity;
25
+
26
+ /**
27
+ * The interface used to sequence async requests sequentially
28
+ */
29
+ // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility
30
+ #asyncQueue = new AsyncQueue();
31
+
32
+ /**
33
+ * @param manager The request manager
34
+ * @param hash The hash that this RequestHandler handles
35
+ * @param majorParameter The major parameter for this handler
36
+ */
37
+ public constructor(
38
+ private readonly manager: RequestManager,
39
+ private readonly data: APIData,
40
+ ) {
41
+ this.id = `${this.data.typePath}:${String(this.data.product)}`;
42
+ }
43
+
44
+ /**
45
+ * If the bucket is currently inactive (no pending requests)
46
+ */
47
+ public get inactive(): boolean {
48
+ return (
49
+ this.#asyncQueue.remaining === 0
50
+ );
51
+ }
52
+
53
+ public getMang(): RequestManager {
54
+ return this.manager;
55
+ }
56
+
57
+ /**
58
+ * Emits a debug message
59
+ * @param message The message to debug
60
+ */
61
+ // private debug(message: string) {
62
+ // this.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);
63
+ // }
64
+
65
+ /*
66
+ * Determines whether the request should be queued or whether a RateLimitError should be thrown
67
+ */
68
+ // private async onRateLimit(rateLimitData: RateLimitData) {
69
+ // const { options } = this.manager;
70
+ // if (options.rejectOnRateLimit) {
71
+ // throw new RateLimitError(rateLimitData);
72
+ // }
73
+ // }
74
+
75
+ /**
76
+ * Queues a request to be sent
77
+ * @param routeId The generalized api route with literal ids for major parameters
78
+ * @param url The url to do the request on
79
+ * @param options All the information needed to make a request
80
+ * @param requestData Extra data from the user's request needed for errors and additional processing
81
+ */
82
+ public async queueRequest(
83
+ url: string,
84
+ options: RequestInit,
85
+ data: APIData
86
+ ): Promise<unknown> {
87
+ let queue = this.#asyncQueue;
88
+ // Wait for any previous requests to be completed before this one is run
89
+ await queue.wait();
90
+ try {
91
+ // Make the request, and return the results
92
+ return await this.runRequest(url, options, data);
93
+ } finally {
94
+ // Allow the next request to fire
95
+ queue.shift();
96
+ }
97
+ }
98
+
99
+ /**
100
+ * The method that actually makes the request to the api, and updates info about the bucket accordingly
101
+ * @param routeId The generalized api route with literal ids for major parameters
102
+ * @param url The fully resolved url to make the request to
103
+ * @param options The node-fetch options needed to make the request
104
+ * @param requestData Extra data from the user's request needed for errors and additional processing
105
+ * @param retries The number of retries this request has already attempted (recursion)
106
+ */
107
+ private async runRequest(
108
+ url: string,
109
+ options: RequestInit,
110
+ data: APIData,
111
+ // retries = 0,
112
+ ): Promise<unknown> {
113
+ const controller = new AbortController();
114
+ const timeout = setTimeout(() => controller.abort(), 30000).unref();
115
+ let res: Response;
116
+
117
+ void this.manager.debug(`[${url} Request] - ${JSON.stringify({ url, options, data })}`);
118
+
119
+ try {
120
+ // node-fetch typings are a bit weird, so we have to cast to any to get the correct signature
121
+ // Type 'AbortSignal' is not assignable to type 'import('discord.js-modules/node_modules/@types/node-fetch/externals').AbortSignal'
122
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
123
+ res = await fetch(url, { ...options, signal: controller.signal as any });
124
+ } catch (error: unknown) {
125
+ throw error;
126
+ } finally {
127
+ clearTimeout(timeout);
128
+ }
129
+
130
+ void this.manager.debug(`[${url} Response] - ${JSON.stringify(res)}`);
131
+
132
+ if (res.ok) {
133
+ const parsedRes = await SequentialHandler.parseResponse(res);
134
+ return parsedRes;
135
+ } else if (res.status === 400 || res.status === 401 || res.status === 404) {
136
+ const parsedRes = await SequentialHandler.parseResponse(res);
137
+ throw new APIError(parsedRes as string, data.type, data.fullUrl, res.status, data);
138
+ } else if (res.status === 429) {
139
+ const timeout = setTimeout(() => {
140
+ this.manager.removeRateLimit(data.requestTypeId);
141
+ }, 60 * 1000);
142
+ const ratelimitData: RateLimitData = {
143
+ product: data.product,
144
+ type: data.type,
145
+ timeTill: timeout
146
+ };
147
+ this.manager.onRateLimit(data.requestTypeId, ratelimitData);
148
+ } else if (res.status >= 500 && res.status < 600) {
149
+ throw new HTTPError(res.statusText, res.constructor.name, res.status, data.method, url);
150
+ }
151
+ return null;
152
+ }
153
+
154
+ private static parseResponse(res: Response): Promise<unknown> {
155
+ if (res.headers.get('Content-Type')?.startsWith('application/json')) {
156
+ return res.json();
157
+ }
158
+
159
+ return res.text();
160
+ }
158
161
  }