@moneylion/engine-api 1.3.6 → 1.3.7

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/dist/client.d.ts CHANGED
@@ -13,12 +13,16 @@ export declare class Client {
13
13
  private auth_token;
14
14
  private fetch_impl;
15
15
  private timeout_ms;
16
+ private additional_headers;
16
17
  /**
17
18
  * Construct a new client instance.
18
19
  * @param host - The API host URL. Example: https://www.example.com. Should not include a trailing slash.
19
20
  * @param auth_token - The auth token used for authenticating with the API.
21
+ * @param timeout_ms - Request timeout in milliseconds. Defaults to 15 seconds.
22
+ * @param fetch_impl - Fetch implementation to use. Defaults to global fetch.
23
+ * @param additional_headers - Additional headers to include in all requests.
20
24
  */
21
- constructor(host: string | undefined, auth_token: string, timeout_ms?: number, fetch_impl?: typeof fetch);
25
+ constructor(host: string | undefined, auth_token: string, timeout_ms?: number, fetch_impl?: typeof fetch, additional_headers?: Record<string, string>);
22
26
  /**
23
27
  * Make a GET request.
24
28
  *
@@ -59,6 +63,11 @@ export declare class Client {
59
63
  * @returns A deserialized Javascript object wrapped in a Promise.
60
64
  */
61
65
  request(endpoint: string, method: HttpMethod, body?: string): Promise<object>;
66
+ /**
67
+ * Safely attempts to read the response body as text.
68
+ * Returns an error message if reading fails.
69
+ */
70
+ private safelyReadResponseBody;
62
71
  }
63
72
  /** The generic error class used to represent error status codes such as 400 Bad Request.
64
73
  */
@@ -72,15 +81,19 @@ export declare class ApiError extends Error {
72
81
  /** The HTTP method that was used for the request.
73
82
  */
74
83
  method: HttpMethod;
75
- /** The serialized body.
84
+ /** The serialized request body.
76
85
  */
77
86
  body?: string;
78
- constructor({ failureStatus, failureReason, url, method, body }: {
87
+ /** The response body as text.
88
+ */
89
+ responseBody: string;
90
+ constructor({ failureStatus, failureReason, url, method, body, responseBody, }: {
79
91
  failureStatus?: number;
80
92
  failureReason: string;
81
93
  url: string;
82
94
  method: HttpMethod;
83
95
  body?: string;
96
+ responseBody?: string;
84
97
  });
85
98
  }
86
99
  /**
package/dist/client.js CHANGED
@@ -20,12 +20,16 @@ export class Client {
20
20
  * Construct a new client instance.
21
21
  * @param host - The API host URL. Example: https://www.example.com. Should not include a trailing slash.
22
22
  * @param auth_token - The auth token used for authenticating with the API.
23
+ * @param timeout_ms - Request timeout in milliseconds. Defaults to 15 seconds.
24
+ * @param fetch_impl - Fetch implementation to use. Defaults to global fetch.
25
+ * @param additional_headers - Additional headers to include in all requests.
23
26
  */
24
- constructor(host = "https://api.evenfinancial.com", auth_token, timeout_ms = 15 * 1000, fetch_impl = fetch) {
27
+ constructor(host = "https://api.evenfinancial.com", auth_token, timeout_ms = 15 * 1000, fetch_impl = fetch, additional_headers = {}) {
25
28
  this.host = host;
26
29
  this.auth_token = auth_token;
27
30
  this.fetch_impl = fetch_impl;
28
31
  this.timeout_ms = timeout_ms;
32
+ this.additional_headers = additional_headers;
29
33
  }
30
34
  /**
31
35
  * Make a GET request.
@@ -81,40 +85,40 @@ export class Client {
81
85
  const response = yield Promise.race([
82
86
  this.fetch_impl(url, {
83
87
  method: method,
84
- headers: {
85
- "Content-Type": "application/json",
86
- "Accept": "application/json",
87
- "Authorization": `Bearer ${this.auth_token}`,
88
- },
88
+ headers: Object.assign({ "Content-Type": "application/json", "Accept": "application/json", "Authorization": `Bearer ${this.auth_token}` }, this.additional_headers),
89
89
  body: body,
90
90
  }),
91
- timeout
91
+ timeout,
92
92
  ]);
93
93
  if (response === undefined) {
94
94
  throw new TimeoutError({
95
95
  failureReason: "Client Timeout",
96
96
  url,
97
97
  method,
98
- body
98
+ body,
99
99
  });
100
100
  }
101
101
  if (response.status >= 500) {
102
+ const responseBody = yield this.safelyReadResponseBody(response);
102
103
  throw new ServerError({
103
104
  failureStatus: response.status,
104
105
  failureReason: response.statusText,
105
106
  url,
106
107
  method,
107
- body
108
+ body,
109
+ responseBody,
108
110
  });
109
111
  }
110
112
  if (response.status >= 400) {
113
+ const responseBody = yield this.safelyReadResponseBody(response);
111
114
  if (response.status === 401 || response.status === 403) {
112
115
  throw new AuthenticationError({
113
116
  failureStatus: response.status,
114
117
  failureReason: response.statusText,
115
118
  url,
116
119
  method,
117
- body
120
+ body,
121
+ responseBody,
118
122
  });
119
123
  }
120
124
  throw new ClientError({
@@ -122,7 +126,8 @@ export class Client {
122
126
  failureReason: response.statusText,
123
127
  url,
124
128
  method,
125
- body
129
+ body,
130
+ responseBody,
126
131
  });
127
132
  }
128
133
  /* node-fetch types json() as Promise<unknown> to ensure the consumer makes a decision about the
@@ -133,16 +138,32 @@ export class Client {
133
138
  return json;
134
139
  });
135
140
  }
141
+ /**
142
+ * Safely attempts to read the response body as text.
143
+ * Returns an error message if reading fails.
144
+ */
145
+ safelyReadResponseBody(response) {
146
+ return __awaiter(this, void 0, void 0, function* () {
147
+ try {
148
+ const text = yield response.text();
149
+ return text || "[Empty response body]";
150
+ }
151
+ catch (error) {
152
+ return `[Unable to read response body: ${error instanceof Error ? error.message : String(error)}]`;
153
+ }
154
+ });
155
+ }
136
156
  }
137
157
  /** The generic error class used to represent error status codes such as 400 Bad Request.
138
158
  */
139
159
  export class ApiError extends Error {
140
- constructor({ failureStatus, failureReason, url, method, body }) {
160
+ constructor({ failureStatus, failureReason, url, method, body, responseBody = "", }) {
141
161
  super(failureReason);
142
162
  this.failureStatus = failureStatus;
143
163
  this.url = url;
144
164
  this.method = method;
145
165
  this.body = body;
166
+ this.responseBody = responseBody;
146
167
  }
147
168
  }
148
169
  /**
@@ -1,8 +1,18 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
1
10
  import { describe, expect, test, beforeAll, afterEach, afterAll, } from "@jest/globals";
2
11
  import { Client, AuthenticationError, ClientError, ServerError, TimeoutError, } from "./client";
3
12
  import { setupServer } from "msw/node";
4
13
  import { http, HttpResponse } from "msw";
5
14
  const successBody = { response: "Okay" };
15
+ const errorResponseBody = { error: "Something went wrong", code: "ERR_001" };
6
16
  const handlers = [
7
17
  http.get("https://example.com/auth_error", () => {
8
18
  return new HttpResponse(null, { status: 401 });
@@ -10,9 +20,15 @@ const handlers = [
10
20
  http.post("https://example.com/bad_request", () => {
11
21
  return new HttpResponse(null, { status: 400 });
12
22
  }),
23
+ http.post("https://example.com/bad_request_with_body", () => {
24
+ return HttpResponse.json(errorResponseBody, { status: 400 });
25
+ }),
13
26
  http.get("https://example.com/server_error", () => {
14
27
  return new HttpResponse(null, { status: 500 });
15
28
  }),
29
+ http.get("https://example.com/server_error_with_body", () => {
30
+ return HttpResponse.json(errorResponseBody, { status: 500 });
31
+ }),
16
32
  http.get("https://example.com/network_error", () => {
17
33
  return HttpResponse.error();
18
34
  }),
@@ -25,6 +41,13 @@ const handlers = [
25
41
  http.patch("https://example.com/success", () => {
26
42
  return HttpResponse.json(successBody);
27
43
  }),
44
+ http.get("https://example.com/check_headers", ({ request }) => {
45
+ const headers = Object.fromEntries(request.headers.entries());
46
+ return HttpResponse.json({ headers });
47
+ }),
48
+ http.get("https://example.com/empty_error_body", () => {
49
+ return new HttpResponse("", { status: 400 });
50
+ }),
28
51
  ];
29
52
  const server = setupServer(...handlers);
30
53
  describe("Client", () => {
@@ -83,4 +106,78 @@ describe("Client", () => {
83
106
  const response = client.request("timeout_error", "GET");
84
107
  return expect(response).rejects.toThrow(TimeoutError);
85
108
  });
109
+ test("Additional headers are included in requests", () => __awaiter(void 0, void 0, void 0, function* () {
110
+ const client = new Client(testEndpoint, "good_token", 15000, fetch, {
111
+ "x-custom-header": "test-value",
112
+ "x-another-header": "another-value",
113
+ });
114
+ const response = yield client.get("check_headers");
115
+ const headers = response.headers;
116
+ expect(headers).toMatchObject({
117
+ "x-another-header": "another-value",
118
+ "x-custom-header": "test-value",
119
+ });
120
+ }));
121
+ test("Response body is captured in ClientError", () => __awaiter(void 0, void 0, void 0, function* () {
122
+ const client = new Client(testEndpoint, "good_token");
123
+ try {
124
+ yield client.post("bad_request_with_body", { test: "body" });
125
+ }
126
+ catch (error) {
127
+ expect(error).toBeInstanceOf(ClientError);
128
+ if (error instanceof ClientError) {
129
+ expect(error.responseBody).toBe(JSON.stringify(errorResponseBody));
130
+ expect(error.failureStatus).toBe(400);
131
+ }
132
+ }
133
+ }));
134
+ test("Response body is captured in ServerError", () => __awaiter(void 0, void 0, void 0, function* () {
135
+ const client = new Client(testEndpoint, "good_token");
136
+ try {
137
+ yield client.get("server_error_with_body");
138
+ }
139
+ catch (error) {
140
+ expect(error).toBeInstanceOf(ServerError);
141
+ if (error instanceof ServerError) {
142
+ expect(error.responseBody).toBe(JSON.stringify(errorResponseBody));
143
+ expect(error.failureStatus).toBe(500);
144
+ }
145
+ }
146
+ }));
147
+ test("Empty response body returns placeholder message", () => __awaiter(void 0, void 0, void 0, function* () {
148
+ const client = new Client(testEndpoint, "good_token");
149
+ try {
150
+ yield client.get("empty_error_body");
151
+ }
152
+ catch (error) {
153
+ expect(error).toBeInstanceOf(ClientError);
154
+ if (error instanceof ClientError) {
155
+ expect(error.responseBody).toBe("[Empty response body]");
156
+ expect(error.failureStatus).toBe(400);
157
+ }
158
+ }
159
+ }));
160
+ test("Unreadable response body returns error message", () => __awaiter(void 0, void 0, void 0, function* () {
161
+ // Mock fetch that returns a response where .text() throws an error
162
+ const fetch_impl = () => __awaiter(void 0, void 0, void 0, function* () {
163
+ return {
164
+ status: 500,
165
+ statusText: "Internal Server Error",
166
+ text: () => __awaiter(void 0, void 0, void 0, function* () {
167
+ throw new Error("Sample error");
168
+ }),
169
+ };
170
+ });
171
+ const client = new Client(testEndpoint, "good_token", 15000, fetch_impl);
172
+ try {
173
+ yield client.get("unreadable_error_body");
174
+ }
175
+ catch (error) {
176
+ expect(error).toBeInstanceOf(ServerError);
177
+ if (error instanceof ServerError) {
178
+ expect(error.responseBody).toBe("[Unable to read response body: Sample error]");
179
+ expect(error.failureStatus).toBe(500);
180
+ }
181
+ }
182
+ }));
86
183
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moneylion/engine-api",
3
- "version": "1.3.6",
3
+ "version": "1.3.7",
4
4
  "description": "Interface to engine.tech API",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",