@moneylion/engine-api 1.0.0

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 ADDED
@@ -0,0 +1,8 @@
1
+ # Engine API
2
+
3
+ This is a Javascript interface to the [Engine](https://engine.tech/docs/api-reference/) API service.
4
+
5
+ ## Getting Started
6
+
7
+ 1. `npm install`
8
+ 2. `npm build`
@@ -0,0 +1,206 @@
1
+ import { components } from "./generated/schema";
2
+ export type LeadCreateData = components["schemas"]["LeadCreateData"];
3
+ export declare class LeadCreateBuilder {
4
+ private leadData;
5
+ constructor(startingData?: LeadCreateData);
6
+ build(): {
7
+ productTypes?: ("credit_card" | "insurance" | "life_insurance" | "loan" | "mortgage" | "savings" | "other")[] | undefined;
8
+ uuid?: string | undefined;
9
+ sessionUuid?: string | undefined;
10
+ loanInformation?: {
11
+ purpose?: "other" | "unknown" | "auto" | "auto_purchase" | "auto_refinance" | "baby" | "boat" | "business" | "car_repair" | "cosmetic" | "credit_card_refi" | "debt_consolidation" | "emergency" | "engagement" | "green" | "home_improvement" | "home_purchase" | "home_refi" | "household_expenses" | "large_purchases" | "life_event" | "medical_dental" | "motorcycle" | "moving_relocation" | "rv" | "special_occasion" | "student_loan" | "student_loan_refi" | "taxes" | "vacation" | "wedding" | undefined;
12
+ loanAmount?: number | undefined;
13
+ } | undefined;
14
+ personalInformation?: {
15
+ firstName?: string | undefined;
16
+ lastName?: string | undefined;
17
+ aliasFirstName?: string | undefined;
18
+ aliasLastName?: string | undefined;
19
+ email?: string | undefined;
20
+ city?: string | undefined;
21
+ state?: "AK" | "AL" | "AR" | "AZ" | "CA" | "CO" | "CT" | "DC" | "DE" | "FL" | "GA" | "HI" | "IA" | "ID" | "IL" | "IN" | "KS" | "KY" | "LA" | "MA" | "MD" | "ME" | "MI" | "MN" | "MO" | "MS" | "MT" | "NC" | "ND" | "NE" | "NH" | "NJ" | "NM" | "NV" | "NY" | "OH" | "OK" | "OR" | "PA" | "PR" | "RI" | "SC" | "SD" | "TN" | "TX" | "UT" | "VA" | "VI" | "VT" | "WA" | "WI" | "WV" | "WY" | undefined;
22
+ workPhone?: string | undefined;
23
+ primaryPhone?: string | undefined;
24
+ bestTimeToCall?: "morning" | "afternoon" | "evening" | "night" | undefined;
25
+ address1?: string | undefined;
26
+ address2?: string | undefined;
27
+ addressMoveInDate?: string | undefined;
28
+ zipcode?: string | undefined;
29
+ monthsAtAddress?: number | undefined;
30
+ driversLicenseNumber?: string | undefined;
31
+ driversLicenseState?: string | undefined;
32
+ ipAddress?: string | undefined;
33
+ activeMilitary?: boolean | undefined;
34
+ militaryVeteran?: boolean | undefined;
35
+ dateOfBirth?: string | undefined;
36
+ educationLevel?: "other" | "high_school" | "associate" | "bachelors" | "masters" | "doctorate" | "other_grad_degree" | "certificate" | "did_not_graduate" | "still_enrolled" | undefined;
37
+ ssn?: string | undefined;
38
+ citizenshipStatus?: "other" | "citizen" | "permanent_resident" | undefined;
39
+ } | undefined;
40
+ personalReferenceInformation?: {
41
+ firstName?: string | undefined;
42
+ lastName?: string | undefined;
43
+ primaryPhone?: string | undefined;
44
+ relationType?: "other" | "parent" | "employer" | "spouse" | "guardian" | "sibling" | "relative" | "friend" | undefined;
45
+ } | undefined;
46
+ mortgageInformation?: {
47
+ propertyType?: "rent" | "condo" | "multi_unit" | "single_family" | "townhouse" | undefined;
48
+ propertyValue?: number | undefined;
49
+ mortgageBalance?: number | undefined;
50
+ lenderName?: string | undefined;
51
+ hasFHALoan?: boolean | undefined;
52
+ currentWithLoan?: boolean | undefined;
53
+ propertyStatus?: "own_outright" | "own_with_mortgage" | "rent" | undefined;
54
+ mortgageType?: "purchase" | "refinance" | undefined;
55
+ mortgageAmount?: number | undefined;
56
+ downPaymentAmount?: number | undefined;
57
+ propertyState?: string | undefined;
58
+ propertyCounty?: string | undefined;
59
+ propertyAddress1?: string | undefined;
60
+ propertyAddress2?: string | undefined;
61
+ propertyZipcode?: string | undefined;
62
+ propertyCity?: string | undefined;
63
+ refinanceAmount?: number | undefined;
64
+ cashOutAmount?: number | undefined;
65
+ occupancyType?: "primary" | "secondary" | "investment" | undefined;
66
+ refinanceType?: "cash_out" | "rate_term" | undefined;
67
+ propertySearchStatus?: "found" | "not_found" | undefined;
68
+ numUnits?: number | undefined;
69
+ closingDate?: string | undefined;
70
+ purchaseStatus?: "no_offer" | "offer_accepted" | "offer_pending" | "under_contract" | undefined;
71
+ purchaseDate?: string | undefined;
72
+ monthlyHoaFee?: number | undefined;
73
+ mortgageCompany?: string | undefined;
74
+ mortgageEscrowAmount?: number | undefined;
75
+ } | undefined;
76
+ creditCardInformation?: {
77
+ allowAnnualFee?: boolean | undefined;
78
+ cardPurposes?: ("balance_transfer" | "cash_back" | "earning_rewards" | "improve_credit" | "low_interest" | "new_to_credit" | "student" | "travel_incentives")[] | undefined;
79
+ } | undefined;
80
+ savingsInformation?: {
81
+ minDepositAmount?: number | undefined;
82
+ maxDepositAmount?: number | undefined;
83
+ } | undefined;
84
+ creditInformation?: {
85
+ providedCreditRating?: "excellent" | "good" | "fair" | "poor" | "limited" | "unknown" | undefined;
86
+ providedNumericCreditScore?: number | undefined;
87
+ } | undefined;
88
+ financialInformation?: {
89
+ employmentStatus?: "other" | "employed" | "employed_full_time" | "employed_part_time" | "military" | "not_employed" | "self_employed" | "retired" | undefined;
90
+ employmentPayFrequency?: "monthly" | "weekly" | "biweekly" | "twice_monthly" | undefined;
91
+ annualIncome?: number | undefined;
92
+ monthlyNetIncome?: number | undefined;
93
+ bankName?: string | undefined;
94
+ bankRoutingNumber?: string | undefined;
95
+ bankAccountType?: "savings" | "other" | "checking" | undefined;
96
+ creditCardDebt?: number | undefined;
97
+ monthsAtBank?: number | undefined;
98
+ bankAccountNumber?: string | undefined;
99
+ monthlyDebt?: number | undefined;
100
+ totalAssets?: number | undefined;
101
+ monthlyHousingPayment?: number | undefined;
102
+ availableAssets?: number | undefined;
103
+ additionalIncome?: number | undefined;
104
+ additionalIncomeFrequency?: "monthly" | "weekly" | "biweekly" | "twice_monthly" | undefined;
105
+ hasDirectDeposit?: boolean | undefined;
106
+ totalUnsecuredDebt?: number | undefined;
107
+ } | undefined;
108
+ employmentInformation?: {
109
+ employerName?: string | undefined;
110
+ employerAddress?: string | undefined;
111
+ employerAddress2?: string | undefined;
112
+ employerCity?: string | undefined;
113
+ employerPhone?: string | undefined;
114
+ employerState?: string | undefined;
115
+ employerZip?: string | undefined;
116
+ jobTitle?: string | undefined;
117
+ monthsEmployed?: number | undefined;
118
+ directDeposit?: boolean | undefined;
119
+ payDate1?: string | undefined;
120
+ payDate2?: string | undefined;
121
+ startDate?: string | undefined;
122
+ } | undefined;
123
+ legalInformation?: {
124
+ consentsToFcra?: boolean | undefined;
125
+ consentsToSms?: boolean | undefined;
126
+ consentsToTcpa?: boolean | undefined;
127
+ fcraLanguage?: string | undefined;
128
+ tcpaLanguage?: string | undefined;
129
+ } | undefined;
130
+ educationInformation?: {
131
+ educationLevel?: "other" | "high_school" | "associate" | "bachelors" | "masters" | "doctorate" | "other_grad_degree" | "certificate" | "did_not_graduate" | "still_enrolled" | undefined;
132
+ graduateDegreeType?: "other" | "doctor_of_medicine" | "doctor_of_osteopathic_medicine" | "doctor_of_optometry" | "doctor_of_dental_medicine" | "dentariae_medicinae_doctoris" | "doctor_of_dental_surgery" | "doctor_of_veterinary_medicine" | "doctor_of_pharmacy" | "veterinariae_medicinae_doctoris" | "master_of_arts" | "master_of_science" | "master_of_research" | "master_of_research_project" | "master_of_studies" | "master_of_business_administration" | "master_of_library_science" | "master_of_public_administration" | "master_of_public_health" | "master_of_laws" | "master_of_arts_liberal_studies" | "master_of_fine_arts" | "master_of_music" | "master_of_education" | "master_of_engineering" | "master_of_architecture" | "juris_doctor" | undefined;
133
+ universityAttended?: string | undefined;
134
+ universityOpeId?: string | undefined;
135
+ graduationDate?: string | undefined;
136
+ graduateGraduationDate?: string | undefined;
137
+ graduateLastAttendedDate?: string | undefined;
138
+ graduateUniversityAttended?: string | undefined;
139
+ graduateUniversityOpeId?: string | undefined;
140
+ undergraduateGraduationDate?: string | undefined;
141
+ undergraduateLastAttendedDate?: string | undefined;
142
+ undergraduateUniversityAttended?: string | undefined;
143
+ undergraduateUniversityOpeId?: string | undefined;
144
+ } | undefined;
145
+ coApplicantInformation?: {
146
+ firstName?: string | undefined;
147
+ lastName?: string | undefined;
148
+ dateOfBirth?: string | undefined;
149
+ annualIncome?: number | undefined;
150
+ streetAddress1?: string | undefined;
151
+ streetAddress2?: string | undefined;
152
+ city?: string | undefined;
153
+ state?: "AK" | "AL" | "AR" | "AZ" | "CA" | "CO" | "CT" | "DC" | "DE" | "FL" | "GA" | "HI" | "IA" | "ID" | "IL" | "IN" | "KS" | "KY" | "LA" | "MA" | "MD" | "ME" | "MI" | "MN" | "MO" | "MS" | "MT" | "NC" | "ND" | "NE" | "NH" | "NJ" | "NM" | "NV" | "NY" | "OH" | "OK" | "OR" | "PA" | "PR" | "RI" | "SC" | "SD" | "TN" | "TX" | "UT" | "VA" | "VI" | "VT" | "WA" | "WI" | "WV" | "WY" | undefined;
154
+ zipcode?: string | undefined;
155
+ } | undefined;
156
+ healthInformation?: {
157
+ gender?: "male" | "female" | undefined;
158
+ heightInInches?: number | undefined;
159
+ weightInPounds?: number | undefined;
160
+ tobaccoSmoker?: boolean | undefined;
161
+ } | undefined;
162
+ refinanceLoans?: {
163
+ accountNumber?: string | undefined;
164
+ incomeBasedRepayment?: boolean | undefined;
165
+ interestRate?: number | undefined;
166
+ loanAmount?: number | undefined;
167
+ loanServicer?: string | undefined;
168
+ loanType?: "federal_student_loan" | "private_student_loan" | undefined;
169
+ nextPaymentAmount?: number | undefined;
170
+ nextPaymentDate?: string | undefined;
171
+ }[] | undefined;
172
+ identificationInformation?: {
173
+ idNumber?: string | undefined;
174
+ idState?: string | undefined;
175
+ idType?: "driver_license" | "state_id" | "passport" | undefined;
176
+ } | undefined;
177
+ clientTags?: {
178
+ [key: string]: string[];
179
+ } | undefined;
180
+ sessionInformation?: {
181
+ ipAddress?: string | undefined;
182
+ userAgent?: string | undefined;
183
+ } | undefined;
184
+ formCompleted?: boolean | undefined;
185
+ referralCompanyUuid?: string | undefined;
186
+ trackingUuid?: string | undefined;
187
+ };
188
+ productTypes(types: components["schemas"]["ProductType"][]): this;
189
+ loanInformation(loanInfo: components["schemas"]["LeadLoanInformation"]): this;
190
+ personalInformation(personalInfo: components["schemas"]["LeadPersonalInformation"]): this;
191
+ personalReferenceInformation(pRefInfo: components["schemas"]["PersonalReferenceInformation"]): this;
192
+ mortgageInformation(mortgageInfo: components["schemas"]["LeadMortgageInformation"]): this;
193
+ creditCardInformation(creditCardInformation: components["schemas"]["LeadCreditCardInformation"]): this;
194
+ savingsInformation(savingsInformation: components["schemas"]["LeadSavingsInformation"]): this;
195
+ creditInformation(creditInformation: components["schemas"]["LeadCreditInformation"]): this;
196
+ financialInformation(financialInformation: components["schemas"]["LeadFinancialInformation"]): this;
197
+ employmentInformation(employmentInformation: components["schemas"]["LeadEmploymentInformation"]): this;
198
+ legalInformation(legalInformation: components["schemas"]["LeadLegalInformation"]): this;
199
+ educationInformation(educationInformation: components["schemas"]["LeadEducationInformation"]): this;
200
+ coApplicantInformation(coApplicantInformation: components["schemas"]["LeadCoApplicantInformation"]): this;
201
+ healthInformation(healthInformation: components["schemas"]["LeadHealthInformation"]): this;
202
+ refinanceLoans(refinanceLoans: components["schemas"]["RefinanceLoanInformation"][]): this;
203
+ identificationInformation(identificationInformation: components["schemas"]["LeadIdentificationInformation"]): this;
204
+ clientTags(clientTags: components["schemas"]["ClientTags"]): this;
205
+ sessionInformation(sessionInformation: components["schemas"]["LeadSessionInformation"]): this;
206
+ }
@@ -0,0 +1,80 @@
1
+ export class LeadCreateBuilder {
2
+ constructor(startingData = {}) {
3
+ this.leadData = startingData;
4
+ }
5
+ build() {
6
+ return this.leadData;
7
+ }
8
+ productTypes(types) {
9
+ this.leadData.productTypes = types;
10
+ return this;
11
+ }
12
+ loanInformation(loanInfo) {
13
+ this.leadData.loanInformation = loanInfo;
14
+ return this;
15
+ }
16
+ personalInformation(personalInfo) {
17
+ this.leadData.personalInformation = personalInfo;
18
+ return this;
19
+ }
20
+ personalReferenceInformation(pRefInfo) {
21
+ this.leadData.personalReferenceInformation = pRefInfo;
22
+ return this;
23
+ }
24
+ mortgageInformation(mortgageInfo) {
25
+ this.leadData.mortgageInformation = mortgageInfo;
26
+ return this;
27
+ }
28
+ creditCardInformation(creditCardInformation) {
29
+ this.leadData.creditCardInformation = creditCardInformation;
30
+ return this;
31
+ }
32
+ savingsInformation(savingsInformation) {
33
+ this.leadData.savingsInformation = savingsInformation;
34
+ return this;
35
+ }
36
+ creditInformation(creditInformation) {
37
+ this.leadData.creditInformation = creditInformation;
38
+ return this;
39
+ }
40
+ financialInformation(financialInformation) {
41
+ this.leadData.financialInformation = financialInformation;
42
+ return this;
43
+ }
44
+ employmentInformation(employmentInformation) {
45
+ this.leadData.employmentInformation = employmentInformation;
46
+ return this;
47
+ }
48
+ legalInformation(legalInformation) {
49
+ this.leadData.legalInformation = legalInformation;
50
+ return this;
51
+ }
52
+ educationInformation(educationInformation) {
53
+ this.leadData.educationInformation = educationInformation;
54
+ return this;
55
+ }
56
+ coApplicantInformation(coApplicantInformation) {
57
+ this.leadData.coApplicantInformation = coApplicantInformation;
58
+ return this;
59
+ }
60
+ healthInformation(healthInformation) {
61
+ this.leadData.healthInformation = healthInformation;
62
+ return this;
63
+ }
64
+ refinanceLoans(refinanceLoans) {
65
+ this.leadData.refinanceLoans = refinanceLoans;
66
+ return this;
67
+ }
68
+ identificationInformation(identificationInformation) {
69
+ this.leadData.identificationInformation = identificationInformation;
70
+ return this;
71
+ }
72
+ clientTags(clientTags) {
73
+ this.leadData.clientTags = clientTags;
74
+ return this;
75
+ }
76
+ sessionInformation(sessionInformation) {
77
+ this.leadData.sessionInformation = sessionInformation;
78
+ return this;
79
+ }
80
+ }
@@ -0,0 +1,91 @@
1
+ type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE";
2
+ /**
3
+ * The base HTTP client that the API clients depend on.
4
+ * It handles setting the appropriate headers and also handles serialization and deserialization.
5
+ * Error status codes will be raised as an exception.
6
+ *
7
+ * You should not need to use this in regular usage.
8
+ * It is provided as an escape hatch in case something isn't covered by the more specific APIs.
9
+ */
10
+ export declare class Client {
11
+ private host;
12
+ private auth_token;
13
+ /**
14
+ * Construct a new client instance.
15
+ * @param host - The API host URL. Example: https://www.example.com. Should not include a trailing slash.
16
+ * @param auth_token - The auth token used for authenticating with the API.
17
+ */
18
+ constructor(host: string | undefined, auth_token: string);
19
+ /**
20
+ * Make a GET request.
21
+ *
22
+ * @param endpoint - The endpoint to make the request against. Should not include a leading slash.
23
+ *
24
+ * @returns A deserialized Javascript object wrapped in a Promise
25
+ */
26
+ get(endpoint: string): Promise<object>;
27
+ /**
28
+ * Make a POST request.
29
+ *
30
+ * @param endpoint - The endpoint to make the request against. Should not include a leading slash.
31
+ * @param body - A javascript object to be serialized and sent with the request.
32
+ *
33
+ * @returns A deserialized Javascript object wrapped in a Promise.
34
+ */
35
+ post(endpoint: string, body?: object): Promise<object>;
36
+ /**
37
+ * Make a PATCH request.
38
+ *
39
+ * @param endpoint - The endpoint to make the request against. Should not include a leading slash.
40
+ * @param body - A javascript object to be serialized and sent with the request.
41
+ *
42
+ * @returns A deserialized Javascript object wrapped in a Promise.
43
+ */
44
+ patch(endpoint: string, body?: object): Promise<object>;
45
+ /**
46
+ * Make a request with an arbitrary method.
47
+ *
48
+ * @remarks
49
+ * You should not need to use this during regular usage of the client.
50
+ * It's provided as an escape hatch in case you need something that isn't provided.
51
+ *
52
+ * @param endpoint - The endpoint to make the request against. Should not include a leading slash.
53
+ * @param method - An HTTP method name as a string. One of "GET", "PUT", "PATCH", or "DELETE".
54
+ * @param body - A string representing the serialized body of the request.
55
+ *
56
+ * @returns A deserialized Javascript object wrapped in a Promise.
57
+ */
58
+ request(endpoint: string, method: HttpMethod, body?: string): Promise<object>;
59
+ }
60
+ /** The generic error class used to represent error status codes such as 400 Bad Request.
61
+ */
62
+ export declare class ApiError extends Error {
63
+ /** The HTTP status code.
64
+ */
65
+ failureStatus: number;
66
+ /** The url that was requested.
67
+ */
68
+ url: string;
69
+ /** The HTTP method that was used for the request.
70
+ */
71
+ method: HttpMethod;
72
+ /** The serialized body.
73
+ */
74
+ body?: string;
75
+ constructor(failureStatus: number, failureReason: string, url: string, method: HttpMethod, body?: string);
76
+ }
77
+ /**
78
+ * An error that the caller has made in the request.
79
+ * You should fix the error and then repeat the request.
80
+ */
81
+ export declare class ClientError extends ApiError {
82
+ }
83
+ /** An error that occurred on the server.
84
+ */
85
+ export declare class ServerError extends ApiError {
86
+ }
87
+ /** An error that occurred during authentication.
88
+ */
89
+ export declare class AuthenticationError extends ApiError {
90
+ }
91
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,127 @@
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
+ };
10
+ /**
11
+ * The base HTTP client that the API clients depend on.
12
+ * It handles setting the appropriate headers and also handles serialization and deserialization.
13
+ * Error status codes will be raised as an exception.
14
+ *
15
+ * You should not need to use this in regular usage.
16
+ * It is provided as an escape hatch in case something isn't covered by the more specific APIs.
17
+ */
18
+ export class Client {
19
+ /**
20
+ * Construct a new client instance.
21
+ * @param host - The API host URL. Example: https://www.example.com. Should not include a trailing slash.
22
+ * @param auth_token - The auth token used for authenticating with the API.
23
+ */
24
+ constructor(host = "https://api.evenfinancial.com", auth_token) {
25
+ this.host = host;
26
+ this.auth_token = auth_token;
27
+ }
28
+ /**
29
+ * Make a GET request.
30
+ *
31
+ * @param endpoint - The endpoint to make the request against. Should not include a leading slash.
32
+ *
33
+ * @returns A deserialized Javascript object wrapped in a Promise
34
+ */
35
+ get(endpoint) {
36
+ return this.request(endpoint, "GET");
37
+ }
38
+ /**
39
+ * Make a POST request.
40
+ *
41
+ * @param endpoint - The endpoint to make the request against. Should not include a leading slash.
42
+ * @param body - A javascript object to be serialized and sent with the request.
43
+ *
44
+ * @returns A deserialized Javascript object wrapped in a Promise.
45
+ */
46
+ post(endpoint, body) {
47
+ return this.request(endpoint, "POST", body ? JSON.stringify(body) : body);
48
+ }
49
+ /**
50
+ * Make a PATCH request.
51
+ *
52
+ * @param endpoint - The endpoint to make the request against. Should not include a leading slash.
53
+ * @param body - A javascript object to be serialized and sent with the request.
54
+ *
55
+ * @returns A deserialized Javascript object wrapped in a Promise.
56
+ */
57
+ patch(endpoint, body) {
58
+ return this.request(endpoint, "PATCH", body ? JSON.stringify(body) : body);
59
+ }
60
+ /**
61
+ * Make a request with an arbitrary method.
62
+ *
63
+ * @remarks
64
+ * You should not need to use this during regular usage of the client.
65
+ * It's provided as an escape hatch in case you need something that isn't provided.
66
+ *
67
+ * @param endpoint - The endpoint to make the request against. Should not include a leading slash.
68
+ * @param method - An HTTP method name as a string. One of "GET", "PUT", "PATCH", or "DELETE".
69
+ * @param body - A string representing the serialized body of the request.
70
+ *
71
+ * @returns A deserialized Javascript object wrapped in a Promise.
72
+ */
73
+ request(endpoint, method, body) {
74
+ return __awaiter(this, void 0, void 0, function* () {
75
+ const url = `${this.host}/${endpoint}`;
76
+ const response = yield fetch(url, {
77
+ method: method,
78
+ headers: {
79
+ "Content-Type": "application/json",
80
+ "Accept": "application/json",
81
+ "Authorization": `Bearer ${this.auth_token}`,
82
+ },
83
+ body: body,
84
+ });
85
+ if (response.status >= 500) {
86
+ throw new ServerError(response.status, response.statusText, url, method, body);
87
+ }
88
+ if (response.status >= 400) {
89
+ if (response.status === 401 || response.status === 403) {
90
+ throw new AuthenticationError(response.status, response.statusText, url, method, body);
91
+ }
92
+ throw new ClientError(response.status, response.statusText, url, method, body);
93
+ }
94
+ /* node-fetch types json() as Promise<unknown> to ensure the consumer makes a decision about the
95
+ * type. We are deciding here to treat it as an object so that consumers of this method can introspect
96
+ * it further more easily.
97
+ */
98
+ const json = (yield response.json());
99
+ return json;
100
+ });
101
+ }
102
+ }
103
+ /** The generic error class used to represent error status codes such as 400 Bad Request.
104
+ */
105
+ export class ApiError extends Error {
106
+ constructor(failureStatus, failureReason, url, method, body) {
107
+ super(failureReason);
108
+ this.failureStatus = failureStatus;
109
+ this.url = url;
110
+ this.method = method;
111
+ this.body = body;
112
+ }
113
+ }
114
+ /**
115
+ * An error that the caller has made in the request.
116
+ * You should fix the error and then repeat the request.
117
+ */
118
+ export class ClientError extends ApiError {
119
+ }
120
+ /** An error that occurred on the server.
121
+ */
122
+ export class ServerError extends ApiError {
123
+ }
124
+ /** An error that occurred during authentication.
125
+ */
126
+ export class AuthenticationError extends ApiError {
127
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,78 @@
1
+ import { describe, expect, test, beforeAll, afterEach, afterAll, } from "@jest/globals";
2
+ import { Client, AuthenticationError, ClientError, ServerError, } from "./client";
3
+ import { setupServer } from "msw/node";
4
+ import { http, HttpResponse } from "msw";
5
+ const successBody = { response: "Okay" };
6
+ const handlers = [
7
+ http.get("https://example.com/auth_error", () => {
8
+ return new HttpResponse(null, { status: 401 });
9
+ }),
10
+ http.post("https://example.com/bad_request", () => {
11
+ return new HttpResponse(null, { status: 400 });
12
+ }),
13
+ http.get("https://example.com/server_error", () => {
14
+ return new HttpResponse(null, { status: 500 });
15
+ }),
16
+ http.get("https://example.com/network_error", () => {
17
+ return HttpResponse.error();
18
+ }),
19
+ http.get("https://example.com/success", () => {
20
+ return HttpResponse.json(successBody);
21
+ }),
22
+ http.post("https://example.com/success", () => {
23
+ return HttpResponse.json(successBody);
24
+ }),
25
+ http.patch("https://example.com/success", () => {
26
+ return HttpResponse.json(successBody);
27
+ }),
28
+ ];
29
+ const server = setupServer(...handlers);
30
+ describe("Client", () => {
31
+ beforeAll(() => server.listen({
32
+ onUnhandledRequest: "error",
33
+ }));
34
+ afterEach(() => server.resetHandlers());
35
+ afterAll(() => server.close());
36
+ const testEndpoint = "https://example.com";
37
+ test("Authentication error is raised when auth token is incorrect", () => {
38
+ const bad_token = "bad_token";
39
+ const client = new Client(testEndpoint, bad_token);
40
+ const response = client.request("auth_error", "GET");
41
+ return expect(response).rejects.toThrow(AuthenticationError);
42
+ });
43
+ test("Client error is raised when request is incorrect", () => {
44
+ const client = new Client(testEndpoint, "good_token");
45
+ const response = client.request("bad_request", "POST", JSON.stringify({ test: "body" }));
46
+ return expect(response).rejects.toThrow(ClientError);
47
+ });
48
+ test("Server error is raised when the server encounters a problem", () => {
49
+ const client = new Client(testEndpoint, "good_token");
50
+ const response = client.request("server_error", "GET");
51
+ return expect(response).rejects.toThrow(ServerError);
52
+ });
53
+ test("Successful response returns decoded JSON object", () => {
54
+ const client = new Client(testEndpoint, "good_token");
55
+ const response = client.request("success", "GET");
56
+ return expect(response).resolves.toEqual(successBody);
57
+ });
58
+ test("Can make GET requests", () => {
59
+ const client = new Client(testEndpoint, "good_token");
60
+ const response = client.get("success");
61
+ return expect(response).resolves.toEqual(successBody);
62
+ });
63
+ test("Can make POST requests", () => {
64
+ const client = new Client(testEndpoint, "good_token");
65
+ const response = client.post("success", { test: "body" });
66
+ return expect(response).resolves.toEqual(successBody);
67
+ });
68
+ test("Can make PATCH requests", () => {
69
+ const client = new Client(testEndpoint, "good_token");
70
+ const response = client.patch("success", { test: "body" });
71
+ return expect(response).resolves.toEqual(successBody);
72
+ });
73
+ test("Network error is raised when there is a network error", () => {
74
+ const client = new Client(testEndpoint, "good_token");
75
+ const response = client.request("network_error", "GET");
76
+ return expect(response).rejects.toThrow(TypeError);
77
+ });
78
+ });
@@ -0,0 +1,40 @@
1
+ import { Decoder } from "@mojotech/json-type-validation";
2
+ import { components } from "./generated/schema";
3
+ type FixNull<T> = T extends object ? {
4
+ [P in keyof T]: undefined extends T[P] ? FixNull<T[P] | null> : FixNull<T[P]>;
5
+ } : T extends Array<infer X> ? FixNull<X>[] : T;
6
+ export declare const cardPurposeDecoder: Decoder<components["schemas"]["CardPurpose"]>;
7
+ export declare const termUnitDecoder: Decoder<components["schemas"]["TermUnit"]>;
8
+ export declare const introOfferTypeDecoder: Decoder<components["schemas"]["IntroOfferType"]>;
9
+ export declare const cardTypeDecoder: Decoder<components["schemas"]["CardType"]>;
10
+ export declare const providedCreditRatingDecoder: Decoder<components["schemas"]["ProvidedCreditRating"]>;
11
+ type CardBenefit = components["schemas"]["CardBenefit"];
12
+ export declare const cardBenefitDecoder: Decoder<CardBenefit>;
13
+ export declare const creditCardOfferDetailsDecoder: Decoder<FixNull<components["schemas"]["CreditCardOfferDetails"]>>;
14
+ export declare const partnerDecoder: Decoder<FixNull<components["schemas"]["Partner"]>>;
15
+ export declare const productTypeDecoder: Decoder<components["schemas"]["ProductType"]>;
16
+ type ProductSubType = components["schemas"]["ProductSubType"];
17
+ export declare const productSubTypeDecoder: Decoder<ProductSubType>;
18
+ export declare const offerDecoder: Decoder<FixNull<components["schemas"]["Offer"]>>;
19
+ export declare const creditCardOfferDecoder: Decoder<FixNull<components["schemas"]["CreditCardOffer"]>>;
20
+ export declare const originatorImageDecoder: Decoder<components["schemas"]["OriginatorImage"]>;
21
+ export declare const originatorDecoder: Decoder<FixNull<components["schemas"]["Originator"]>>;
22
+ export declare const aprTypeDecoder: Decoder<components["schemas"]["AprType"]>;
23
+ type OldLoanOffer = components["schemas"]["LoanOffer"];
24
+ type LoanOffer = FixNull<OldLoanOffer>;
25
+ export declare const loanOfferDecoder: Decoder<LoanOffer>;
26
+ export declare const mortgageLoanTypeDecoder: Decoder<components["schemas"]["MortgageLoanType"]>;
27
+ export declare const mortgageAdjustmentTypeDecoder: Decoder<components["schemas"]["MortgageAdjustmentType"]>;
28
+ export declare const mortageOfferDetailsDecoder: Decoder<components["schemas"]["MortgageOfferDetails"]>;
29
+ export declare const mortgageOfferDecoder: Decoder<FixNull<components["schemas"]["MortgageOffer"]>>;
30
+ export declare const compoundingMethodDecoder: Decoder<components["schemas"]["CompoundingMethod"]>;
31
+ export declare const federalInsuranceTypeDecoder: Decoder<components["schemas"]["FederalInsuranceType"]>;
32
+ export declare const savingsOfferDetailsDecoder: Decoder<FixNull<components["schemas"]["SavingsOfferDetails"]>>;
33
+ export declare const savingsOfferDecoder: Decoder<FixNull<components["schemas"]["SavingsOffer"]>>;
34
+ export declare const specialOfferDecoder: Decoder<FixNull<components["schemas"]["SpecialOffer"]>>;
35
+ export declare const pendingResponseDecoder: Decoder<FixNull<components["schemas"]["PendingResponse"]>>;
36
+ type OldRateTable = components["schemas"]["RateTable"];
37
+ export type FixedRateTable = FixNull<OldRateTable>;
38
+ export declare const rateTableDecoder: Decoder<FixedRateTable>;
39
+ export declare const leadUuidDecoder: Decoder<components["schemas"]["LeadUuid"]>;
40
+ export {};