theauthapi 1.0.6 → 1.0.9

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
@@ -1,5 +1,332 @@
1
- # The Auth API node library
2
- ## Scalable API Key Management and Auth Control
3
- ## Secure your API with best in class API Key management, user access, all with great analytics.
1
+ # Client library for [TheAuthAPI](https://theauthapi.com/)
4
2
 
5
- Client library for [TheAuthAPI.com](https://theauthapi.com)
3
+ **Contents**
4
+
5
+ - [Client library for TheAuthAPI](#client-library-for-theauthapi)
6
+ - [Installation](#installation)
7
+ - [Configuration](#configuration)
8
+ - [Usage](#usage)
9
+ - [Example: Validating an API-Key](#example-validating-an-api-key)
10
+ - [Example: Listing API-Keys](#example-listing-api-keys)
11
+ - [Example: Listing the projects of an account](#example-listing-the-projects-of-an-account)
12
+ - [Example: Listing projects and associated API-Keys](#example-listing-projects-and-associated-api-keys)
13
+ - [Example: Creating an API-Key](#example-creating-an-api-key)
14
+ - [Handling Errors](#handling-errors)
15
+ - [Typescript](#typescript)
16
+ - [📙 Further Reading](#-further-reading)
17
+
18
+ **Scalable API Key Management and Auth Control**
19
+ Secure your API with best in class API Key management, user access, all with great analytics.
20
+
21
+ ## Installation
22
+
23
+ This library is published on [npm](https://www.npmjs.com/package/theauthapi), you can add it as a dependency using the following
24
+ command
25
+
26
+ ```bash
27
+ npm install theauthapi
28
+ # or
29
+ yarn add theauthapi
30
+ ```
31
+
32
+ ## Configuration
33
+
34
+ You'll need to configure the library with your `access key` and `account id`, you can grab these from [TheAuthAPI](https://app.theauthapi.com/dashboard) dashboard.
35
+
36
+ For further instructions on creating an account, check out our [how to guides](https://thatapicompany.notion.site/The-Auth-API-Knowledge-Base-21660cee84e640729714fad43d9ce546).
37
+
38
+ ### Imports
39
+
40
+ #### CommonJS
41
+
42
+ ```javascript
43
+ const TheAuthAPI = require("theauthapi").default;
44
+ ```
45
+
46
+ #### ES Modules
47
+
48
+ ```typescript
49
+ import TheAuthAPI from "theauthapi";
50
+ ```
51
+
52
+ initialize the client using your access key:
53
+
54
+ ```javascript
55
+ const theAuthAPI = new TheAuthAPI("YOUR_ACCESS_KEY");
56
+ ```
57
+
58
+ You can also provide custom options:
59
+
60
+ ```javascript
61
+ const theAuthAPI = new TheAuthAPI("YOUR_ACCESS_KEY", {
62
+ timeout: 3600,
63
+ retryCount: 2,
64
+ });
65
+ ```
66
+
67
+ **Full option types:**
68
+
69
+ ```typescript
70
+ type Options = {
71
+ // server url
72
+ host?: string;
73
+ // request timeout in ms
74
+ timeout?: string | number;
75
+ // number of retries before failing
76
+ retryCount?: number;
77
+ };
78
+ ```
79
+
80
+ ## Usage
81
+
82
+ After initiating the client, you can access endpoint methods using the following pattern:
83
+ `[object instance].[endpoint].[method]`
84
+
85
+ For example, getting the projects for an account would be: `theAuthApiClient.projects.getProjects("ACCOUNT_ID")`,
86
+
87
+ Similarly, getting the api keys would be:
88
+ `theAuthApiClient.apiKeys.getKeys("PROJECT_ID")`
89
+
90
+ | endpoint | attribute | example |
91
+ | --------- | --------- | --------------------------------------------- |
92
+ | /api-keys | apiKeys | `client.apiKeys.createKey("MY_KEY")` |
93
+ | /projects | projects | `client.projects.createProject("MY_PROJECT")` |
94
+ | /accounts | accounts | `client.accounts.createAccount("MY_ACCOUNT")` |
95
+
96
+ For details on each endpoint accepted values, please reference these docs: [docs.theauthapi.com](https://docs.theauthapi.com/)
97
+
98
+ All methods return a promise containing the returned JSON as a javascript object. Each method of an endpoint maps HTTP methods to
99
+
100
+ | HTTP Method | method name | example |
101
+ | ----------- | ----------- | ------------------------------------------------------------------------- |
102
+ | POST | create\* | `client.apiKeys.createKey({ name: "KEY_NAME", projectId: "PROJECT_ID" })` |
103
+ | GET | get\* | `client.apiKeys.getKeys()` |
104
+ | DELETE | delete\* | `client.apiKeys.deleteKey("MY_KEY")` |
105
+ | PATCH | update\* | `client.apiKeys.updateKey("MY_KEY", { name: "UPDATED_KEY_NAME" })` |
106
+
107
+ #### Example: Validating an API-Key
108
+
109
+ You can easily validate an API key using `apiKeys.isValidKey` which returns `true` if the key is valid, `false` otherwise.
110
+ `isValidKey` throws an `ApiRequestError` if there's a network issue, it's advised to wrap it in a `try/catch` to handle the potential error
111
+
112
+ ```javascript
113
+ theAuthAPI.apiKeys
114
+ .isValidKey("API_KEY")
115
+ .then((isValidKey) => {
116
+ if (isValidKey) {
117
+ console.log("The API is valid!");
118
+ } else {
119
+ console.log("Invalid API key!");
120
+ }
121
+ })
122
+ .catch((error) => {
123
+ // handle network error
124
+ });
125
+ ```
126
+
127
+ **Using async/await**
128
+
129
+ ```javascript
130
+ try {
131
+ const isValidKey = await theAuthAPI.apiKeys.isValidKey("API_KEY");
132
+ if (isValidKey) {
133
+ console.log("The API is valid!");
134
+ } else {
135
+ console.log("Invalid API key!");
136
+ }
137
+ } catch (error) {
138
+ // handle network error
139
+ }
140
+ ```
141
+
142
+ #### Example: Listing API-keys
143
+
144
+ ```javascript
145
+ theAuthAPI.apiKeys
146
+ .getKeys()
147
+ .then((keys) => console.log(keys))
148
+ .catch((error) => console.log(error));
149
+ ```
150
+
151
+ **Using async/await**
152
+
153
+ ```javascript
154
+ try {
155
+ const keys = await theAuthAPI.apiKeys.getKeys();
156
+ } catch (error) {
157
+ console.log(error);
158
+ }
159
+ ```
160
+
161
+ **Filtering API Keys**: You can filter the listed API keys by passing an object of type filter as an argument to `getKeys`
162
+
163
+ ```typescript
164
+ type ApiKeyFilter = {
165
+ projectId?: string;
166
+ customAccountId?: string;
167
+ customUserId?: string;
168
+ isActive?: boolean;
169
+ };
170
+ ```
171
+
172
+ **Example**: filtering api-keys with a specific `projectId` where the keys are not active
173
+
174
+ ```javascript
175
+ try {
176
+ const keys = await theAuthAPI.apiKeys.getKeys({
177
+ projectId: "PROJECT_ID",
178
+ isActive: false,
179
+ });
180
+ } catch (error) {
181
+ console.log(error);
182
+ }
183
+ ```
184
+
185
+ **NOTE** that if your access key is at account level, you need to specify `projectId` when listing the API keys:
186
+ `getKeys({ projectId: "PROJECT_ID" })`, otherwise if your access key is created at project level, you don't have to specify `projectId`,
187
+ the access key's `projectId` will be used to get the API-keys (i.e. you'll see only the keys of the project your access key is created against)
188
+
189
+ #### Example: Listing the projects of an account
190
+
191
+ ```javascript
192
+ theAuthAPI.projects
193
+ .getProjects("ACCOUNT_ID")
194
+ .then((projects) => console.log(projects))
195
+ .catch((error) => console.log(error));
196
+ ```
197
+
198
+ **Using async/await**
199
+
200
+ ```javascript
201
+ try {
202
+ const projects = await client.projects.getProjects("ACCOUNT_ID");
203
+ } catch (error) {
204
+ console.log(error);
205
+ }
206
+ ```
207
+
208
+ #### Example: Listing projects and associated API-Keys
209
+
210
+ ```javascript
211
+ async function getProjectsWithKeys(accountId: string) {
212
+ try {
213
+ const projects = await theAuthAPI.projects.getProjects(accountId);
214
+ const projectsKeys = projects.map(async (project) => {
215
+ const keys = await theAuthAPI.apiKeys.getKeys(project.id);
216
+ return { project, keys };
217
+ });
218
+ return await Promise.all(projectsKeys);
219
+ } catch (error) {
220
+ // handle error
221
+ }
222
+ }
223
+ ```
224
+
225
+ #### Example: Creating an API-Key
226
+
227
+ ```javascript
228
+ theAuthAPI.apiKeys
229
+ .createKey({
230
+ projectId: "PROJECT_ID",
231
+ customMetaData: { metadata_val: "value to store" },
232
+ customAccountId: "[any info you want]",
233
+ name: "[any info you want e.g. name of customer or the key]",
234
+ })
235
+ .then((key) => console.log("Key created > ", key))
236
+ .catch((error) => console.log("Couldn't make the key", error));
237
+ ```
238
+
239
+ **Using async/await**
240
+
241
+ ```javascript
242
+ try {
243
+ const key = await theAuthAPI.apiKeys.createKey({
244
+ projectId: "PROJECT_ID",
245
+ customMetaData: { metadata_val: "value to store" },
246
+ customAccountId: "[any info you want]",
247
+ name: "[any info you want e.g. name of customer or the key]",
248
+ });
249
+ console.log("Key created > ", key);
250
+ } catch (error) {
251
+ console.log("Couldn't make the key ", error);
252
+ }
253
+ ```
254
+
255
+ ### Handling Errors
256
+
257
+ [comment]: <> (All methods that return a promise throw 3 types of errors)
258
+
259
+ ##### ApiRequestError
260
+
261
+ Thrown when there's a network or a connectivity issue, for example, if the client didn't establish any network connection with the host
262
+
263
+ ```
264
+ ApiRequestError: getaddrinfo EAI_AGAIN api.theauthapi.com
265
+ ```
266
+
267
+ ##### ApiResponseError
268
+
269
+ Thrown when the server responds with an HTTP status code not in the `2xx` range. `ApiRequestError` provides two properties to distinguish the type of the error
270
+
271
+ - `statusCode` HTTP status code
272
+ - `message` the message the server responded with in the body
273
+
274
+ This is the most common thrown error, you should expect and handle it each time you use any of the library methods
275
+
276
+ ##### Example: Getting a key throws an ApiResponseError if the key is invalid
277
+
278
+ If you try to GET an invalid key using `apiKeys.getKey("invalid-key")`, the server responds with a 404 error and an `ApiResponseError` is thrown
279
+
280
+ ```
281
+ ApiResponseError: (404): Invalid client key
282
+ ```
283
+
284
+ "404" is the `statusCode`, "Invalid client Key" is the `message`, you can access these properties using `error.statusCode` and `error.message` respectively
285
+
286
+ ##### Error
287
+
288
+ Unknown error, just a normal javascript error
289
+
290
+ #### Handling Errors the Right Way
291
+
292
+ Since all the possible thrown errors are instances of classes, we can check the type of the thrown error and handle it accordingly
293
+
294
+ ```javascript
295
+ try {
296
+ const key = await theAuthAPI.apiKeys.getKey("KEY");
297
+ } catch (error) {
298
+ if (error instanceof ApiResponseError) {
299
+ // handle response error
300
+ }
301
+ if (error instanceof ApiRequestError) {
302
+ // handle network error
303
+ }
304
+ // unknown error
305
+ throw error;
306
+ }
307
+ ```
308
+
309
+ ### Typescript
310
+
311
+ This library is written in [Typescript](https://www.typescriptlang.org/), types are provided out of the box.
312
+
313
+ Example of usage with Typescript:
314
+
315
+ ```typescript
316
+ import TheAuthAPI from "theauthapi";
317
+ import { Project } from "theauthapi/types";
318
+
319
+ const client = new TheAuthAPI("ACCESS_KEY");
320
+
321
+ async function getProjectsIds(accountId: string): Promise<string[]> {
322
+ const projects: Project[] = await client.projects.getProjects(accountId);
323
+ return projects.map((project) => project.name);
324
+ }
325
+ ```
326
+
327
+ ### 📙 Further Reading
328
+
329
+ - Create your account [https://theauthapi.com](https://theauthapi.com)
330
+ - View our [Knowledge Base](https://thatapicompany.notion.site/The-Auth-API-Knowledge-Base-21660cee84e640729714fad43d9ce546) help centre
331
+ - Articles on best Auth practice - [https://theauthapi.com/articles](https://theauthapi.com/articles)
332
+ - Meet the team behind The Auth API - [That API Company](https://thatapicompany.com/)
@@ -1,13 +1,19 @@
1
1
  import ApiRequest from "../../services/ApiRequest/ApiRequest";
2
- import { ApiKey, ApiKeyInput, UpdateApiKeyInput } from "../../types";
2
+ import { ApiKey, ApiKeyFilter, ApiKeyInput, UpdateApiKeyInput } from "../../types";
3
3
  import { ApiKeysInterface } from "./ApiKeysInterface";
4
4
  declare class ApiKeys implements ApiKeysInterface {
5
5
  api: ApiRequest;
6
+ private readonly endpoint;
6
7
  constructor(apiService: ApiRequest);
7
- authenticateKey(apikey: string): Promise<ApiKey>;
8
- getKeys(projectId: string): Promise<ApiKey[]>;
8
+ isValidKey(apikey: string): Promise<boolean>;
9
+ getKeys(filter?: ApiKeyFilter): Promise<ApiKey[]>;
10
+ getKey(apikey: string): Promise<ApiKey>;
9
11
  createKey(apiKey: ApiKeyInput): Promise<ApiKey>;
10
- updateKey(apiKey: string, updateTo: UpdateApiKeyInput): Promise<ApiKey>;
12
+ updateKey(apiKey: string, updatedKey: UpdateApiKeyInput): Promise<ApiKey>;
11
13
  deleteKey(apiKey: string): Promise<boolean>;
14
+ private validateCreateKeyInput;
15
+ private validateUpdateKeyInput;
16
+ private validateFiltersInput;
17
+ private getKeysFilterEndpoint;
12
18
  }
13
19
  export default ApiKeys;
@@ -15,38 +15,49 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  const HttpMethod_1 = require("../../services/ApiRequest/HttpMethod");
16
16
  const lodash_omit_1 = __importDefault(require("lodash.omit"));
17
17
  const util_1 = require("../../util");
18
+ const ApiResponseError_1 = __importDefault(require("../../services/ApiRequest/ApiResponseError"));
18
19
  class ApiKeys {
19
20
  constructor(apiService) {
20
21
  this.api = apiService;
22
+ this.endpoint = "/api-keys/";
21
23
  }
22
- authenticateKey(apikey) {
24
+ isValidKey(apikey) {
23
25
  return __awaiter(this, void 0, void 0, function* () {
24
26
  (0, util_1.validateString)("apikey", apikey);
25
- return yield this.api.request(HttpMethod_1.HttpMethod.GET, `/api-keys/${apikey}`);
27
+ try {
28
+ const key = yield this.api.request(HttpMethod_1.HttpMethod.GET, `/api-keys/${apikey}`);
29
+ return key.key !== undefined;
30
+ }
31
+ catch (error) {
32
+ if (error instanceof ApiResponseError_1.default && error.statusCode === 404) {
33
+ return false;
34
+ }
35
+ throw error;
36
+ }
37
+ });
38
+ }
39
+ getKeys(filter) {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ const endpoint = this.getKeysFilterEndpoint(filter);
42
+ return yield this.api.request(HttpMethod_1.HttpMethod.GET, endpoint);
26
43
  });
27
44
  }
28
- getKeys(projectId) {
45
+ getKey(apikey) {
29
46
  return __awaiter(this, void 0, void 0, function* () {
30
- (0, util_1.validateString)("projectId", projectId);
31
- return yield this.api.request(HttpMethod_1.HttpMethod.GET, `/api-keys/?projectId=${projectId}`);
47
+ (0, util_1.validateString)("apikey", apikey);
48
+ return yield this.api.request(HttpMethod_1.HttpMethod.GET, `/api-keys/${apikey}`);
32
49
  });
33
50
  }
34
51
  createKey(apiKey) {
35
52
  return __awaiter(this, void 0, void 0, function* () {
36
- // validate string properties only
37
- for (const [key, value] of Object.entries((0, lodash_omit_1.default)(apiKey, ["customMetaData", "rateLimitConfigs"]))) {
38
- (0, util_1.validateString)(key, value);
39
- }
53
+ this.validateCreateKeyInput(apiKey);
40
54
  return yield this.api.request(HttpMethod_1.HttpMethod.POST, "/api-keys", apiKey);
41
55
  });
42
56
  }
43
- updateKey(apiKey, updateTo) {
57
+ updateKey(apiKey, updatedKey) {
44
58
  return __awaiter(this, void 0, void 0, function* () {
45
- (0, util_1.validateString)("apiKey", apiKey);
46
- for (const [key, value] of Object.entries((0, lodash_omit_1.default)(updateTo, "customMetaData"))) {
47
- (0, util_1.validateString)(key, value);
48
- }
49
- return yield this.api.request(HttpMethod_1.HttpMethod.PATCH, `/api-keys/${apiKey}`, updateTo);
59
+ this.validateUpdateKeyInput(apiKey, updatedKey);
60
+ return yield this.api.request(HttpMethod_1.HttpMethod.PATCH, `/api-keys/${apiKey}`, updatedKey);
50
61
  });
51
62
  }
52
63
  deleteKey(apiKey) {
@@ -55,5 +66,45 @@ class ApiKeys {
55
66
  return yield this.api.request(HttpMethod_1.HttpMethod.DELETE, `/api-keys/${apiKey}`);
56
67
  });
57
68
  }
69
+ validateCreateKeyInput(apiKey) {
70
+ if (!apiKey) {
71
+ throw new TypeError("apiKey must be an object");
72
+ }
73
+ if (!apiKey.name) {
74
+ throw TypeError("apiKey object must contain the property name");
75
+ }
76
+ // validate string properties only
77
+ for (const [key, value] of Object.entries((0, lodash_omit_1.default)(apiKey, ["customMetaData", "rateLimitConfigs"]))) {
78
+ (0, util_1.validateString)(key, value);
79
+ }
80
+ }
81
+ validateUpdateKeyInput(apiKey, updatedKey) {
82
+ if (!updatedKey) {
83
+ throw new TypeError("updatedKey must be an object");
84
+ }
85
+ if (!updatedKey.name) {
86
+ throw TypeError("updatedKey object must contain the property [name]");
87
+ }
88
+ (0, util_1.validateString)("apiKey", apiKey);
89
+ (0, util_1.validateString)("name", updatedKey.name);
90
+ }
91
+ validateFiltersInput(filter) {
92
+ if (filter) {
93
+ if (filter.isActive && typeof filter.isActive !== "boolean") {
94
+ throw TypeError("isActive must be a boolean");
95
+ }
96
+ Object.entries((0, lodash_omit_1.default)(filter, "isActive")).forEach(([key, value]) => {
97
+ (0, util_1.validateString)(key, value);
98
+ });
99
+ }
100
+ }
101
+ getKeysFilterEndpoint(filter) {
102
+ this.validateFiltersInput(filter);
103
+ let filters = [];
104
+ if (filter) {
105
+ filters = Object.entries(filter).map(([key, value]) => `${key}=${value}`);
106
+ }
107
+ return `${this.endpoint}${filter ? "?" : ""}${filters.join("&")}`;
108
+ }
58
109
  }
59
110
  exports.default = ApiKeys;
@@ -1,7 +1,8 @@
1
- import { ApiKey, ApiKeyInput, UpdateApiKeyInput } from "../../types";
1
+ import { ApiKey, ApiKeyFilter, ApiKeyInput, UpdateApiKeyInput } from "../../types";
2
2
  export interface ApiKeysInterface {
3
- authenticateKey(apiKey: string): Promise<ApiKey>;
4
- getKeys(projectId: string): Promise<ApiKey[]>;
3
+ isValidKey(apiKey: string): Promise<boolean>;
4
+ getKey(apiKey: string): Promise<ApiKey>;
5
+ getKeys(filter?: ApiKeyFilter): Promise<ApiKey[]>;
5
6
  createKey(apiKey: ApiKeyInput): Promise<ApiKey>;
6
7
  updateKey(apiKey: string, updateTo: UpdateApiKeyInput): Promise<ApiKey>;
7
8
  deleteKey(apiKey: string): Promise<boolean>;
@@ -1,5 +1,5 @@
1
1
  import ApiRequest from "../../services/ApiRequest/ApiRequest";
2
- import { Project, UpdateProjectInput } from "../../types";
2
+ import { CreateProjectInput, Project, UpdateProjectInput } from "../../types";
3
3
  import { ProjectsInterface } from "./ProjectsInterface";
4
4
  declare class Projects implements ProjectsInterface {
5
5
  api: ApiRequest;
@@ -8,7 +8,9 @@ declare class Projects implements ProjectsInterface {
8
8
  getProjects(accountId: string): Promise<Project[]>;
9
9
  getProject(projectId: string): Promise<Project>;
10
10
  deleteProject(projectId: string): Promise<boolean>;
11
- createProject(name: string, accountId: string): Promise<Project>;
12
- updateProject(projectId: string, updateTo: UpdateProjectInput): Promise<Project>;
11
+ createProject(project: CreateProjectInput): Promise<Project>;
12
+ updateProject(projectId: string, project: UpdateProjectInput): Promise<Project>;
13
+ private validateCreateProjectInput;
14
+ private validateUpdateProjectInput;
13
15
  }
14
16
  export default Projects;
@@ -9,6 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ const types_1 = require("../../types");
12
13
  const HttpMethod_1 = require("../../services/ApiRequest/HttpMethod");
13
14
  const util_1 = require("../../util");
14
15
  class Projects {
@@ -34,21 +35,34 @@ class Projects {
34
35
  return yield this.api.request(HttpMethod_1.HttpMethod.DELETE, `${this.endpoint}/${projectId}`);
35
36
  });
36
37
  }
37
- createProject(name, accountId) {
38
+ createProject(project) {
38
39
  return __awaiter(this, void 0, void 0, function* () {
39
- (0, util_1.validateString)("name", name);
40
- (0, util_1.validateString)("accountId", accountId);
41
- return yield this.api.request(HttpMethod_1.HttpMethod.POST, this.endpoint, {
42
- name,
43
- accountId,
44
- });
40
+ this.validateCreateProjectInput(project);
41
+ return yield this.api.request(HttpMethod_1.HttpMethod.POST, this.endpoint, project);
45
42
  });
46
43
  }
47
- updateProject(projectId, updateTo) {
44
+ updateProject(projectId, project) {
48
45
  return __awaiter(this, void 0, void 0, function* () {
49
- (0, util_1.validateString)("projectId", projectId);
50
- return this.api.request(HttpMethod_1.HttpMethod.PATCH, `${this.endpoint}/${projectId}`, updateTo);
46
+ this.validateUpdateProjectInput(projectId, project);
47
+ return this.api.request(HttpMethod_1.HttpMethod.PATCH, `${this.endpoint}/${projectId}`, project);
51
48
  });
52
49
  }
50
+ validateCreateProjectInput(project) {
51
+ if (!project) {
52
+ throw new TypeError("project must be an object");
53
+ }
54
+ (0, util_1.validateString)("name", project.name);
55
+ (0, util_1.validateString)("accountId", project.accountId);
56
+ if (!Object.values(types_1.Environment).includes(project.env)) {
57
+ throw TypeError(`expected env to be one of [${Object.values(types_1.Environment).map((v) => `"${v}"`)}], got: ${project.env}`);
58
+ }
59
+ }
60
+ validateUpdateProjectInput(projectId, project) {
61
+ if (!project) {
62
+ throw new TypeError("project must be an object");
63
+ }
64
+ (0, util_1.validateString)("projectId", projectId);
65
+ (0, util_1.validateString)("name", project.name);
66
+ }
53
67
  }
54
68
  exports.default = Projects;
@@ -1,8 +1,8 @@
1
- import { Project, UpdateProjectInput } from "../../types";
1
+ import { CreateProjectInput, Project, UpdateProjectInput } from "../../types";
2
2
  export interface ProjectsInterface {
3
3
  getProjects(accountId: string): Promise<Project[]>;
4
4
  getProject(projectId: string): Promise<Project>;
5
5
  deleteProject(projectId: string): Promise<boolean>;
6
- createProject(name: string, accountId: string): Promise<Project>;
6
+ createProject(project: CreateProjectInput): Promise<Project>;
7
7
  updateProject(name: string, updateTo: UpdateProjectInput): Promise<Project>;
8
8
  }
@@ -1 +1 @@
1
- export declare const version = "1.0.6";
1
+ export declare const version = "1.0.9";
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.version = void 0;
4
- exports.version = "1.0.6";
4
+ exports.version = "1.0.9";
@@ -17,6 +17,7 @@ const libraryMeta_1 = require("../../libraryMeta");
17
17
  const ApiRequestError_1 = __importDefault(require("./ApiRequestError"));
18
18
  const axios_retry_1 = __importDefault(require("axios-retry"));
19
19
  const ms_1 = __importDefault(require("ms"));
20
+ const ApiResponseError_1 = __importDefault(require("./ApiResponseError"));
20
21
  class ApiRequest {
21
22
  constructor(config) {
22
23
  const { host, accessKey, headers, retryCount, timeout } = config;
@@ -76,10 +77,10 @@ class ApiRequest {
76
77
  catch (error) {
77
78
  if (axios_1.default.isAxiosError(error)) {
78
79
  if (error.response) {
79
- throw new ApiRequestError_1.default(error.response.status, (_a = error.response.data.message) !== null && _a !== void 0 ? _a : error.response.statusText);
80
+ throw new ApiResponseError_1.default(error.response.status, (_a = error.response.data.message) !== null && _a !== void 0 ? _a : error.response.statusText);
80
81
  }
81
82
  else if (error.request) {
82
- throw new Error(error.request);
83
+ throw new ApiRequestError_1.default(error.message);
83
84
  }
84
85
  }
85
86
  throw error;
@@ -1,4 +1,10 @@
1
+ /**
2
+ *
3
+ * Throws when no response was received from the server
4
+ * @param message - error message
5
+ *
6
+ * */
1
7
  declare class ApiRequestError extends Error {
2
- constructor(statusCode: number, message: string);
8
+ constructor(message: string);
3
9
  }
4
10
  export default ApiRequestError;
@@ -1,8 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ *
5
+ * Throws when no response was received from the server
6
+ * @param message - error message
7
+ *
8
+ * */
3
9
  class ApiRequestError extends Error {
4
- constructor(statusCode, message) {
5
- super(`(${statusCode}): ${message}`);
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = 'ApiRequestError';
6
13
  }
7
14
  }
8
15
  exports.default = ApiRequestError;
@@ -0,0 +1,12 @@
1
+ /**
2
+ *
3
+ * Throws when the server responds with a status code that falls out of the range 2xx
4
+ * @param statusCode - HTTP status code the server responded with
5
+ * @param message - error message
6
+ *
7
+ * */
8
+ declare class ApiResponseError extends Error {
9
+ statusCode: number;
10
+ constructor(statusCode: number, message: string);
11
+ }
12
+ export default ApiResponseError;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ *
5
+ * Throws when the server responds with a status code that falls out of the range 2xx
6
+ * @param statusCode - HTTP status code the server responded with
7
+ * @param message - error message
8
+ *
9
+ * */
10
+ class ApiResponseError extends Error {
11
+ constructor(statusCode, message) {
12
+ super(`(${statusCode}): ${message}`);
13
+ this.statusCode = statusCode;
14
+ this.name = "ApiResponseError";
15
+ }
16
+ }
17
+ exports.default = ApiResponseError;
@@ -1,26 +1,34 @@
1
1
  export declare type ApiKey = {
2
2
  key: string;
3
3
  name: string;
4
- customMetaData: string;
4
+ customMetaData: object;
5
5
  customAccountId: string;
6
- env: string;
6
+ customUserId: string;
7
+ env: Environment;
7
8
  createdAt: Date;
8
9
  updatedAt: Date;
10
+ isActive: boolean;
9
11
  };
10
12
  export declare type RateLimitConfiguration = {
11
13
  rateLimitedEntity?: string;
12
- ratelimitedEnitityId?: any;
14
+ ratelimitedEnitityId?: string;
13
15
  rateLimit: number;
14
16
  rateLimitTtl: number;
15
17
  };
16
18
  export declare type ApiKeyInput = {
17
19
  name: string;
18
- projectId: string;
20
+ projectId?: string;
19
21
  key?: string;
20
22
  customMetaData?: object;
21
23
  customAccountId?: string;
24
+ customUserId?: string;
22
25
  rateLimitConfigs?: RateLimitConfiguration;
26
+ };
27
+ export declare type ApiKeyFilter = {
28
+ projectId?: string;
29
+ customAccountId?: string;
23
30
  customUserId?: string;
31
+ isActive?: boolean;
24
32
  };
25
33
  export declare type UpdateApiKeyInput = {
26
34
  name: string;
@@ -45,7 +53,16 @@ export declare type Project = AuthBaseEntity & {
45
53
  id: string;
46
54
  name: string;
47
55
  accountId: string;
48
- env: string;
56
+ env: Environment;
57
+ };
58
+ export declare enum Environment {
59
+ LIVE = "live",
60
+ TEST = "test"
61
+ }
62
+ export declare type CreateProjectInput = {
63
+ name: string;
64
+ accountId: string;
65
+ env: Environment;
49
66
  };
50
67
  export declare type UpdateProjectInput = {
51
68
  name: string;
@@ -1,8 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AuthedEntityType = void 0;
3
+ exports.Environment = exports.AuthedEntityType = void 0;
4
4
  var AuthedEntityType;
5
5
  (function (AuthedEntityType) {
6
6
  AuthedEntityType["USER"] = "USER";
7
7
  AuthedEntityType["ACCESS_KEY"] = "ACCESS_KEY";
8
8
  })(AuthedEntityType = exports.AuthedEntityType || (exports.AuthedEntityType = {}));
9
+ var Environment;
10
+ (function (Environment) {
11
+ Environment["LIVE"] = "live";
12
+ Environment["TEST"] = "test";
13
+ })(Environment = exports.Environment || (exports.Environment = {}));
@@ -7,7 +7,7 @@ exports.validateString = void 0;
7
7
  const lodash_isstring_1 = __importDefault(require("lodash.isstring"));
8
8
  function validateString(variableName, value) {
9
9
  if (!value || !(0, lodash_isstring_1.default)(value)) {
10
- throw new Error(`${variableName} must be a string`);
10
+ throw new TypeError(`${variableName} must be a string, got: ${value}`);
11
11
  }
12
12
  }
13
13
  exports.validateString = validateString;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "theauthapi",
3
- "version": "1.0.6",
3
+ "version": "1.0.9",
4
4
  "description": "Client library for TheAuthAPI.com",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",