theauthapi 1.0.3 → 1.0.6

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.
Files changed (32) hide show
  1. package/README.md +5 -2
  2. package/dist/endpoints/Accounts/Accounts.d.ts +10 -0
  3. package/dist/endpoints/Accounts/Accounts.js +26 -0
  4. package/dist/endpoints/Accounts/AccountsInterface.d.ts +4 -0
  5. package/dist/endpoints/Accounts/AccountsInterface.js +2 -0
  6. package/dist/endpoints/ApiKeys/ApiKeys.d.ts +13 -0
  7. package/dist/endpoints/ApiKeys/ApiKeys.js +59 -0
  8. package/dist/endpoints/ApiKeys/ApiKeysInterface.d.ts +8 -0
  9. package/dist/endpoints/ApiKeys/ApiKeysInterface.js +2 -0
  10. package/dist/endpoints/Projects/Projects.d.ts +14 -0
  11. package/dist/endpoints/Projects/Projects.js +54 -0
  12. package/dist/endpoints/Projects/ProjectsInterface.d.ts +8 -0
  13. package/dist/endpoints/Projects/ProjectsInterface.js +2 -0
  14. package/dist/index.d.ts +36 -0
  15. package/dist/index.js +89 -0
  16. package/dist/libraryMeta.d.ts +1 -0
  17. package/dist/libraryMeta.js +4 -0
  18. package/dist/services/ApiRequest/ApiCall.d.ts +5 -0
  19. package/dist/services/ApiRequest/ApiCall.js +2 -0
  20. package/dist/services/ApiRequest/ApiRequest.d.ts +26 -0
  21. package/dist/services/ApiRequest/ApiRequest.js +116 -0
  22. package/dist/services/ApiRequest/ApiRequestError.d.ts +4 -0
  23. package/dist/services/ApiRequest/ApiRequestError.js +8 -0
  24. package/dist/services/ApiRequest/HttpMethod.d.ts +7 -0
  25. package/dist/services/ApiRequest/HttpMethod.js +11 -0
  26. package/dist/types/index.d.ts +56 -0
  27. package/dist/types/index.js +8 -0
  28. package/dist/util/index.d.ts +1 -0
  29. package/dist/util/index.js +13 -0
  30. package/package.json +29 -29
  31. package/index.js +0 -182
  32. package/test.js +0 -139
package/README.md CHANGED
@@ -1,2 +1,5 @@
1
- # theauthapi
2
- Client library for TheAuthAPI.com
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.
4
+
5
+ Client library for [TheAuthAPI.com](https://theauthapi.com)
@@ -0,0 +1,10 @@
1
+ import { AccountsInterface } from "./AccountsInterface";
2
+ import ApiRequest from "../../services/ApiRequest/ApiRequest";
3
+ import { Account } from "../../types";
4
+ declare class Accounts implements AccountsInterface {
5
+ api: ApiRequest;
6
+ endpoint: string;
7
+ constructor(apiService: ApiRequest);
8
+ getAccount(accountId: string): Promise<Account>;
9
+ }
10
+ export default Accounts;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const HttpMethod_1 = require("../../services/ApiRequest/HttpMethod");
13
+ const util_1 = require("../../util");
14
+ class Accounts {
15
+ constructor(apiService) {
16
+ this.api = apiService;
17
+ this.endpoint = "/accounts";
18
+ }
19
+ getAccount(accountId) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ (0, util_1.validateString)("accountId", accountId);
22
+ return yield this.api.request(HttpMethod_1.HttpMethod.GET, `${this.endpoint}/${accountId}`);
23
+ });
24
+ }
25
+ }
26
+ exports.default = Accounts;
@@ -0,0 +1,4 @@
1
+ import { Account } from "../../types";
2
+ export interface AccountsInterface {
3
+ getAccount(accountId: string): Promise<Account>;
4
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,13 @@
1
+ import ApiRequest from "../../services/ApiRequest/ApiRequest";
2
+ import { ApiKey, ApiKeyInput, UpdateApiKeyInput } from "../../types";
3
+ import { ApiKeysInterface } from "./ApiKeysInterface";
4
+ declare class ApiKeys implements ApiKeysInterface {
5
+ api: ApiRequest;
6
+ constructor(apiService: ApiRequest);
7
+ authenticateKey(apikey: string): Promise<ApiKey>;
8
+ getKeys(projectId: string): Promise<ApiKey[]>;
9
+ createKey(apiKey: ApiKeyInput): Promise<ApiKey>;
10
+ updateKey(apiKey: string, updateTo: UpdateApiKeyInput): Promise<ApiKey>;
11
+ deleteKey(apiKey: string): Promise<boolean>;
12
+ }
13
+ export default ApiKeys;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const HttpMethod_1 = require("../../services/ApiRequest/HttpMethod");
16
+ const lodash_omit_1 = __importDefault(require("lodash.omit"));
17
+ const util_1 = require("../../util");
18
+ class ApiKeys {
19
+ constructor(apiService) {
20
+ this.api = apiService;
21
+ }
22
+ authenticateKey(apikey) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ (0, util_1.validateString)("apikey", apikey);
25
+ return yield this.api.request(HttpMethod_1.HttpMethod.GET, `/api-keys/${apikey}`);
26
+ });
27
+ }
28
+ getKeys(projectId) {
29
+ 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}`);
32
+ });
33
+ }
34
+ createKey(apiKey) {
35
+ 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
+ }
40
+ return yield this.api.request(HttpMethod_1.HttpMethod.POST, "/api-keys", apiKey);
41
+ });
42
+ }
43
+ updateKey(apiKey, updateTo) {
44
+ 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);
50
+ });
51
+ }
52
+ deleteKey(apiKey) {
53
+ return __awaiter(this, void 0, void 0, function* () {
54
+ (0, util_1.validateString)("apiKey", apiKey);
55
+ return yield this.api.request(HttpMethod_1.HttpMethod.DELETE, `/api-keys/${apiKey}`);
56
+ });
57
+ }
58
+ }
59
+ exports.default = ApiKeys;
@@ -0,0 +1,8 @@
1
+ import { ApiKey, ApiKeyInput, UpdateApiKeyInput } from "../../types";
2
+ export interface ApiKeysInterface {
3
+ authenticateKey(apiKey: string): Promise<ApiKey>;
4
+ getKeys(projectId: string): Promise<ApiKey[]>;
5
+ createKey(apiKey: ApiKeyInput): Promise<ApiKey>;
6
+ updateKey(apiKey: string, updateTo: UpdateApiKeyInput): Promise<ApiKey>;
7
+ deleteKey(apiKey: string): Promise<boolean>;
8
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,14 @@
1
+ import ApiRequest from "../../services/ApiRequest/ApiRequest";
2
+ import { Project, UpdateProjectInput } from "../../types";
3
+ import { ProjectsInterface } from "./ProjectsInterface";
4
+ declare class Projects implements ProjectsInterface {
5
+ api: ApiRequest;
6
+ endpoint: string;
7
+ constructor(apiService: ApiRequest);
8
+ getProjects(accountId: string): Promise<Project[]>;
9
+ getProject(projectId: string): Promise<Project>;
10
+ deleteProject(projectId: string): Promise<boolean>;
11
+ createProject(name: string, accountId: string): Promise<Project>;
12
+ updateProject(projectId: string, updateTo: UpdateProjectInput): Promise<Project>;
13
+ }
14
+ export default Projects;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const HttpMethod_1 = require("../../services/ApiRequest/HttpMethod");
13
+ const util_1 = require("../../util");
14
+ class Projects {
15
+ constructor(apiService) {
16
+ this.api = apiService;
17
+ this.endpoint = "/projects";
18
+ }
19
+ getProjects(accountId) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ (0, util_1.validateString)("accountId", accountId);
22
+ return yield this.api.request(HttpMethod_1.HttpMethod.GET, `${this.endpoint}?accountId=${accountId}`);
23
+ });
24
+ }
25
+ getProject(projectId) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ (0, util_1.validateString)("projectId", projectId);
28
+ return yield this.api.request(HttpMethod_1.HttpMethod.GET, `${this.endpoint}/${projectId}`);
29
+ });
30
+ }
31
+ deleteProject(projectId) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ (0, util_1.validateString)("projectId", projectId);
34
+ return yield this.api.request(HttpMethod_1.HttpMethod.DELETE, `${this.endpoint}/${projectId}`);
35
+ });
36
+ }
37
+ createProject(name, accountId) {
38
+ 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
+ });
45
+ });
46
+ }
47
+ updateProject(projectId, updateTo) {
48
+ 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);
51
+ });
52
+ }
53
+ }
54
+ exports.default = Projects;
@@ -0,0 +1,8 @@
1
+ import { Project, UpdateProjectInput } from "../../types";
2
+ export interface ProjectsInterface {
3
+ getProjects(accountId: string): Promise<Project[]>;
4
+ getProject(projectId: string): Promise<Project>;
5
+ deleteProject(projectId: string): Promise<boolean>;
6
+ createProject(name: string, accountId: string): Promise<Project>;
7
+ updateProject(name: string, updateTo: UpdateProjectInput): Promise<Project>;
8
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,36 @@
1
+ import ApiRequest from "./services/ApiRequest/ApiRequest";
2
+ import ApiKeys from "./endpoints/ApiKeys/ApiKeys";
3
+ import Projects from "./endpoints/Projects/Projects";
4
+ import Accounts from "./endpoints/Accounts/Accounts";
5
+ declare type Options = {
6
+ host?: string;
7
+ timeout?: string | number;
8
+ cacheTTL?: number;
9
+ enable?: boolean;
10
+ retryCount?: number;
11
+ };
12
+ declare class TheAuthAPI {
13
+ queue: [];
14
+ accessKey: string;
15
+ host: string;
16
+ timeout: number | string | undefined;
17
+ cacheTTL: number;
18
+ api: ApiRequest;
19
+ apiKeys: ApiKeys;
20
+ projects: Projects;
21
+ accounts: Accounts;
22
+ /**
23
+ * Initialize a new `Analytics` with your Segment project's `writeKey` and an
24
+ * optional dictionary of `options`.
25
+ *
26
+ * @param {String} accessKey
27
+ * @param {Object} [options] (optional)
28
+ * @property {Number} flushAt (default: 20)
29
+ * @property {Number} flushInterval (default: 10000)
30
+ * @property {String} host (default: 'https://api.segment.io')
31
+ * @property {Boolean} enable (default: true)
32
+ */
33
+ constructor(accessKey: string, options?: Options);
34
+ authenticateAPIKey(key: string, callback?: (err: any, data: any) => any): Promise<unknown>;
35
+ }
36
+ export default TheAuthAPI;
package/dist/index.js ADDED
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const assert_1 = __importDefault(require("assert"));
16
+ const remove_trailing_slash_1 = __importDefault(require("remove-trailing-slash"));
17
+ const ApiRequest_1 = __importDefault(require("./services/ApiRequest/ApiRequest"));
18
+ const util_1 = require("./util");
19
+ const ApiKeys_1 = __importDefault(require("./endpoints/ApiKeys/ApiKeys"));
20
+ const HttpMethod_1 = require("./services/ApiRequest/HttpMethod");
21
+ const Projects_1 = __importDefault(require("./endpoints/Projects/Projects"));
22
+ const Accounts_1 = __importDefault(require("./endpoints/Accounts/Accounts"));
23
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
24
+ const noop = () => { };
25
+ class TheAuthAPI {
26
+ /**
27
+ * Initialize a new `Analytics` with your Segment project's `writeKey` and an
28
+ * optional dictionary of `options`.
29
+ *
30
+ * @param {String} accessKey
31
+ * @param {Object} [options] (optional)
32
+ * @property {Number} flushAt (default: 20)
33
+ * @property {Number} flushInterval (default: 10000)
34
+ * @property {String} host (default: 'https://api.segment.io')
35
+ * @property {Boolean} enable (default: true)
36
+ */
37
+ constructor(accessKey, options) {
38
+ var _a;
39
+ (0, assert_1.default)(accessKey, "You must pass your project's write key.");
40
+ this.queue = [];
41
+ this.accessKey = accessKey;
42
+ this.host = (0, remove_trailing_slash_1.default)((options === null || options === void 0 ? void 0 : options.host) || "https://api.theauthapi.com");
43
+ this.timeout = options === null || options === void 0 ? void 0 : options.timeout;
44
+ this.cacheTTL = (_a = options === null || options === void 0 ? void 0 : options.cacheTTL) !== null && _a !== void 0 ? _a : 60;
45
+ this.api = new ApiRequest_1.default({
46
+ accessKey: this.accessKey,
47
+ host: this.host,
48
+ });
49
+ this.apiKeys = new ApiKeys_1.default(this.api);
50
+ this.projects = new Projects_1.default(this.api);
51
+ this.accounts = new Accounts_1.default(this.api);
52
+ Object.defineProperty(this, "enable", {
53
+ configurable: false,
54
+ writable: false,
55
+ enumerable: true,
56
+ value: typeof (options === null || options === void 0 ? void 0 : options.enable) === "boolean" ? options.enable : true,
57
+ });
58
+ }
59
+ /*
60
+ @deprecated
61
+ */
62
+ authenticateAPIKey(key, callback) {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ (0, util_1.validateString)("key", key);
65
+ const cb = callback || noop;
66
+ const done = (err) => {
67
+ cb(err, data);
68
+ };
69
+ const data = {
70
+ credentials: { api_key: key },
71
+ timestamp: new Date().getTime(),
72
+ sentAt: new Date().getTime(),
73
+ };
74
+ try {
75
+ const key = yield this.api.request(HttpMethod_1.HttpMethod.POST, "/auth/authenticate", data);
76
+ done(key);
77
+ return key;
78
+ }
79
+ catch (err) {
80
+ if (err.response) {
81
+ const error = new Error(err.response.statusText);
82
+ return done(error);
83
+ }
84
+ done(err);
85
+ }
86
+ });
87
+ }
88
+ }
89
+ exports.default = TheAuthAPI;
@@ -0,0 +1 @@
1
+ export declare const version = "1.0.6";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.version = void 0;
4
+ exports.version = "1.0.6";
@@ -0,0 +1,5 @@
1
+ import { HttpMethod } from "./HttpMethod";
2
+ interface ApiCall {
3
+ request<T>(method: HttpMethod, endpoint: string, payload?: any): Promise<T>;
4
+ }
5
+ export default ApiCall;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,26 @@
1
+ import { HttpMethod } from "./HttpMethod";
2
+ import ApiCall from "./ApiCall";
3
+ declare type Config = {
4
+ host: string;
5
+ accessKey: string;
6
+ headers?: object;
7
+ retryCount?: number;
8
+ timeout?: number | string;
9
+ };
10
+ declare class ApiRequest implements ApiCall {
11
+ host: string;
12
+ headers: object;
13
+ accessKey: string;
14
+ timeout: number;
15
+ retryCount: number;
16
+ constructor(config: Config);
17
+ _init(): void;
18
+ request<T>(method: HttpMethod, endpoint: string, payload?: any): Promise<T>;
19
+ _generateDefaultHeaders(): {
20
+ "user-agent": string;
21
+ "x-api-key": string;
22
+ "api-key": string;
23
+ };
24
+ _isErrorRetryable(error: any): boolean;
25
+ }
26
+ export default ApiRequest;
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const axios_1 = __importDefault(require("axios"));
16
+ const libraryMeta_1 = require("../../libraryMeta");
17
+ const ApiRequestError_1 = __importDefault(require("./ApiRequestError"));
18
+ const axios_retry_1 = __importDefault(require("axios-retry"));
19
+ const ms_1 = __importDefault(require("ms"));
20
+ class ApiRequest {
21
+ constructor(config) {
22
+ const { host, accessKey, headers, retryCount, timeout } = config;
23
+ this.host = host;
24
+ this.accessKey = accessKey;
25
+ this.headers = this._generateDefaultHeaders();
26
+ this.timeout = timeout ? (typeof timeout === "string" ? (0, ms_1.default)(timeout) : timeout) : 0;
27
+ this.retryCount = retryCount !== null && retryCount !== void 0 ? retryCount : 3;
28
+ if (headers) {
29
+ this.headers = Object.assign(Object.assign({}, this.headers), { headers });
30
+ }
31
+ this._init();
32
+ }
33
+ _init() {
34
+ var _a;
35
+ const isoDateFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?(?:[-+]\d{2}:?\d{2}|Z)?$/;
36
+ function isIsoDateString(value) {
37
+ return value && typeof value === "string" && isoDateFormat.test(value);
38
+ }
39
+ function handleDates(body) {
40
+ if (body === null || body === undefined || typeof body !== "object") {
41
+ return body;
42
+ }
43
+ for (const key of Object.keys(body)) {
44
+ const value = body[key];
45
+ if (isIsoDateString(value)) {
46
+ body[key] = new Date(value);
47
+ }
48
+ else if (typeof value === "object") {
49
+ handleDates(value);
50
+ }
51
+ }
52
+ }
53
+ axios_1.default.interceptors.response.use((response) => {
54
+ handleDates(response.data);
55
+ return response;
56
+ });
57
+ (0, axios_retry_1.default)(axios_1.default, {
58
+ retries: (_a = this.retryCount) !== null && _a !== void 0 ? _a : 3,
59
+ retryCondition: this._isErrorRetryable,
60
+ retryDelay: axios_retry_1.default.exponentialDelay,
61
+ });
62
+ }
63
+ request(method, endpoint, payload) {
64
+ var _a;
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ try {
67
+ const response = yield axios_1.default.request({
68
+ baseURL: this.host,
69
+ method: method,
70
+ url: endpoint,
71
+ data: payload,
72
+ headers: this.headers,
73
+ });
74
+ return response.data;
75
+ }
76
+ catch (error) {
77
+ if (axios_1.default.isAxiosError(error)) {
78
+ 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
+ }
81
+ else if (error.request) {
82
+ throw new Error(error.request);
83
+ }
84
+ }
85
+ throw error;
86
+ }
87
+ });
88
+ }
89
+ _generateDefaultHeaders() {
90
+ return {
91
+ "user-agent": `theauthapi-client-node/${libraryMeta_1.version}`,
92
+ "x-api-key": this.accessKey,
93
+ "api-key": this.accessKey,
94
+ };
95
+ }
96
+ _isErrorRetryable(error) {
97
+ // Retry Network Errors.
98
+ if (axios_retry_1.default.isNetworkError(error)) {
99
+ return true;
100
+ }
101
+ if (!error.response) {
102
+ // Cannot determine if the request can be retried
103
+ return false;
104
+ }
105
+ // Retry Server Errors (5xx).
106
+ if (error.response.status >= 500 && error.response.status <= 599) {
107
+ return true;
108
+ }
109
+ // Retry if rate limited.
110
+ if (error.response.status === 429) {
111
+ return true;
112
+ }
113
+ return false;
114
+ }
115
+ }
116
+ exports.default = ApiRequest;
@@ -0,0 +1,4 @@
1
+ declare class ApiRequestError extends Error {
2
+ constructor(statusCode: number, message: string);
3
+ }
4
+ export default ApiRequestError;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class ApiRequestError extends Error {
4
+ constructor(statusCode, message) {
5
+ super(`(${statusCode}): ${message}`);
6
+ }
7
+ }
8
+ exports.default = ApiRequestError;
@@ -0,0 +1,7 @@
1
+ export declare enum HttpMethod {
2
+ GET = "GET",
3
+ POST = "POST",
4
+ DELETE = "DELETE",
5
+ PATCH = "PATCH",
6
+ PUT = "PUT"
7
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpMethod = void 0;
4
+ var HttpMethod;
5
+ (function (HttpMethod) {
6
+ HttpMethod["GET"] = "GET";
7
+ HttpMethod["POST"] = "POST";
8
+ HttpMethod["DELETE"] = "DELETE";
9
+ HttpMethod["PATCH"] = "PATCH";
10
+ HttpMethod["PUT"] = "PUT";
11
+ })(HttpMethod = exports.HttpMethod || (exports.HttpMethod = {}));
@@ -0,0 +1,56 @@
1
+ export declare type ApiKey = {
2
+ key: string;
3
+ name: string;
4
+ customMetaData: string;
5
+ customAccountId: string;
6
+ env: string;
7
+ createdAt: Date;
8
+ updatedAt: Date;
9
+ };
10
+ export declare type RateLimitConfiguration = {
11
+ rateLimitedEntity?: string;
12
+ ratelimitedEnitityId?: any;
13
+ rateLimit: number;
14
+ rateLimitTtl: number;
15
+ };
16
+ export declare type ApiKeyInput = {
17
+ name: string;
18
+ projectId: string;
19
+ key?: string;
20
+ customMetaData?: object;
21
+ customAccountId?: string;
22
+ rateLimitConfigs?: RateLimitConfiguration;
23
+ customUserId?: string;
24
+ };
25
+ export declare type UpdateApiKeyInput = {
26
+ name: string;
27
+ customMetaData?: object;
28
+ customAccountId?: string;
29
+ };
30
+ export declare enum AuthedEntityType {
31
+ USER = "USER",
32
+ ACCESS_KEY = "ACCESS_KEY"
33
+ }
34
+ export declare type AuthBaseEntity = {
35
+ isActive: boolean;
36
+ createdBy: string;
37
+ createdByType?: AuthedEntityType;
38
+ createdIn: string;
39
+ lastChangedBy: string;
40
+ lastChangedByType?: AuthedEntityType;
41
+ updatedAt: Date;
42
+ createdAt: Date;
43
+ };
44
+ export declare type Project = AuthBaseEntity & {
45
+ id: string;
46
+ name: string;
47
+ accountId: string;
48
+ env: string;
49
+ };
50
+ export declare type UpdateProjectInput = {
51
+ name: string;
52
+ };
53
+ export declare type Account = AuthBaseEntity & {
54
+ id: string;
55
+ name: string;
56
+ };
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthedEntityType = void 0;
4
+ var AuthedEntityType;
5
+ (function (AuthedEntityType) {
6
+ AuthedEntityType["USER"] = "USER";
7
+ AuthedEntityType["ACCESS_KEY"] = "ACCESS_KEY";
8
+ })(AuthedEntityType = exports.AuthedEntityType || (exports.AuthedEntityType = {}));
@@ -0,0 +1 @@
1
+ export declare function validateString(variableName: string, value: string): void;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateString = void 0;
7
+ const lodash_isstring_1 = __importDefault(require("lodash.isstring"));
8
+ function validateString(variableName, value) {
9
+ if (!value || !(0, lodash_isstring_1.default)(value)) {
10
+ throw new Error(`${variableName} must be a string`);
11
+ }
12
+ }
13
+ exports.validateString = validateString;
package/package.json CHANGED
@@ -1,18 +1,19 @@
1
1
  {
2
2
  "name": "theauthapi",
3
- "version": "1.0.3",
3
+ "version": "1.0.6",
4
4
  "description": "Client library for TheAuthAPI.com",
5
- "main": "index.js",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
6
10
  "scripts": {
7
- "dependencies": "yarn",
8
- "size": "size-limit",
9
- "test": "standard && nyc ava",
10
- "report-coverage": "nyc report --reporter=lcov > coverage.lcov && codecov",
11
+ "test": "jest --runInBand",
12
+ "test:coverage": "jest --coverage --runInBand",
11
13
  "np": "np --no-publish",
12
14
  "release": "yarn run np",
13
- "babel-node": "babel-node --presets='@babel/preset-env'",
14
- "dev": "nodemon --exec npm run babel-node -- src/app.js",
15
- "test-mocha": "ava mocha"
15
+ "build": "tsc",
16
+ "prepublish": "npm run build"
16
17
  },
17
18
  "repository": {
18
19
  "type": "git",
@@ -28,32 +29,31 @@
28
29
  "assert": "^2.0.0",
29
30
  "axios": "^0.21.4",
30
31
  "axios-retry": "^3.1.9",
31
- "core-js": "^3.17.3",
32
32
  "lodash.isstring": "^4.0.1",
33
+ "lodash.omit": "^4.5.0",
33
34
  "ms": "^2.1.3",
34
- "node-cache": "^5.1.2",
35
- "regenerator-runtime": "^0.13.9",
36
35
  "remove-trailing-slash": "^0.1.1"
37
36
  },
38
37
  "devDependencies": {
39
- "ava": "^3.15.0",
40
- "basic-auth": "^2.0.1",
41
- "body-parser": "^1.17.1",
42
- "chai": "^4.3.4",
43
- "codecov": "^3.0.0",
44
- "commander": "^5.1.0",
45
- "delay": "^4.2.0",
46
- "dotenv": "^10.0.0",
38
+ "@size-limit/preset-small-lib": "^7.0.8",
39
+ "@types/basic-auth": "^1.1.3",
40
+ "@types/express": "^4.17.13",
41
+ "@types/jest": "^27.4.1",
42
+ "@types/lodash.isstring": "^4.0.6",
43
+ "@types/lodash.omit": "^4.5.6",
44
+ "@types/ms": "^0.7.31",
45
+ "@types/node": "^17.0.23",
46
+ "@typescript-eslint/eslint-plugin": "^5.17.0",
47
+ "@typescript-eslint/parser": "^5.17.0",
48
+ "body-parser": "^1.20.0",
49
+ "eslint": "^7.14.0",
50
+ "eslint-config-prettier": "^8.5.0",
47
51
  "express": "^4.15.2",
48
- "husky": "^3.0.4",
49
- "mocha": "^9.1.1",
50
- "nyc": "^14.1.1",
51
- "pify": "^4.0.1",
52
- "sinon": "^7.3.2",
53
- "sinon-chai": "^3.7.0",
52
+ "jest": "^27.5.1",
53
+ "prettier": "2.6.2",
54
54
  "size-limit": "^4.11.0",
55
- "snyk": "^1.328.0",
56
- "standard": "^12.0.1",
57
- "supertest": "^6.1.6"
55
+ "ts-jest": "^27.1.4",
56
+ "ts-node": "^10.7.0",
57
+ "typescript": "^4.6.3"
58
58
  }
59
59
  }
package/index.js DELETED
@@ -1,182 +0,0 @@
1
- 'use strict'
2
-
3
- const assert = require('assert')
4
- const removeSlash = require('remove-trailing-slash')
5
- const axios = require('axios')
6
- const axiosRetry = require('axios-retry')
7
- const ms = require('ms')
8
- const version = require('./package.json').version
9
- const isString = require('lodash.isstring')
10
- const NodeCache = require('node-cache')
11
-
12
- const noop = () => {}
13
-
14
- // const axios = require('axios').default;
15
-
16
- class TheAuthAPI {
17
- /**
18
- * Initialize a new `Analytics` with your Segment project's `writeKey` and an
19
- * optional dictionary of `options`.
20
- *
21
- * @param {String} writeKey
22
- * @param {Object} [options] (optional)
23
- * @property {Number} flushAt (default: 20)
24
- * @property {Number} flushInterval (default: 10000)
25
- * @property {String} host (default: 'https://api.segment.io')
26
- * @property {Boolean} enable (default: true)
27
- */
28
-
29
- constructor (writeKey, options) {
30
- options = options || {}
31
-
32
- assert(writeKey, 'You must pass your project\'s write key.')
33
- this.queue = []
34
- this.writeKey = writeKey
35
- this.host = removeSlash(options.host || 'https://api.theauthapi.com')
36
- this.timeout = options.timeout || false
37
- this.cacheTTL = options.cacheTTL || 60
38
-
39
- Object.defineProperty(this, 'enable', {
40
- configurable: false,
41
- writable: false,
42
- enumerable: true,
43
- value: typeof options.enable === 'boolean' ? options.enable : true
44
- })
45
-
46
- axiosRetry(axios, {
47
- retries: options.retryCount || 3,
48
- retryCondition: this._isErrorRetryable,
49
- retryDelay: axiosRetry.exponentialDelay
50
- })
51
-
52
- this.cache = new NodeCache({
53
- stdTTL: this.cacheTTL,
54
- checkperiod: this.cacheTTL * 0.2,
55
- useClones: false
56
- })
57
- }
58
-
59
- _validate (key, type) {
60
- try {
61
- if (!key || !isString(key)) throw new Error('must pass a string')
62
- } catch (e) {
63
- throw e
64
- }
65
- }
66
-
67
- /**
68
- * Send a track `message`.
69
- *
70
- * @param {Object} message
71
- * @param {Function} [callback] (optional)
72
- * @return {TheAnalyticsAPI}
73
- */
74
-
75
- async authenticateAPIKey (key, callback) {
76
- this._validate(key, 'api_key')
77
-
78
- callback = callback || noop
79
-
80
- const data = {
81
- credentials: { api_key: key },
82
- timestamp: new Date().getTime(),
83
- sentAt: new Date().getTime()
84
- }
85
-
86
- const done = err => {
87
- // callbacks.forEach(callback => callback(err))
88
- callback(err, data)
89
- }
90
-
91
- const headers = {}
92
-
93
- headers['user-agent'] = `theauthapi-client-node/${version}`
94
- headers['x-api-key'] = headers['api_key'] = this.writeKey
95
-
96
- const req = {
97
- method: 'POST',
98
- url: `${this.host}/auth/authenticate`,
99
- /* auth: {
100
- username: this.writeKey
101
- }, */
102
- data,
103
- headers
104
- }
105
-
106
- if (this.timeout) {
107
- req.timeout = typeof this.timeout === 'string' ? ms(this.timeout) : this.timeout
108
- }
109
-
110
- try {
111
- const resp = await axios(req)
112
- done(resp.data)
113
- return resp.data
114
- } catch (err) {
115
- if (err.response) {
116
- const error = new Error(err.response.statusText)
117
- return done(error)
118
- }
119
-
120
- done(err)
121
- }
122
- }
123
-
124
- _isErrorRetryable (error) {
125
- // Retry Network Errors.
126
- if (axiosRetry.isNetworkError(error)) {
127
- return true
128
- }
129
-
130
- if (!error.response) {
131
- // Cannot determine if the request can be retried
132
- return false
133
- }
134
-
135
- // Retry Server Errors (5xx).
136
- if (error.response.status >= 500 && error.response.status <= 599) {
137
- return true
138
- }
139
-
140
- // Retry if rate limited.
141
- if (error.response.status === 429) {
142
- return true
143
- }
144
-
145
- return false
146
- }
147
-
148
- getCache (key) {
149
- const value = this.cache.get(key)
150
- if (value) {
151
- return Promise.resolve(value)
152
- } else {
153
-
154
- }
155
- }
156
-
157
- setCache (key, value, ttl = null) {
158
- if (ttl) this.cache.set(key, value, ttl)
159
- else this.cache.set(key, value)
160
- }
161
-
162
- delCache (keys) {
163
- this.cache.del(keys)
164
- }
165
- delCacheStartWith (startStr = '') {
166
- if (!startStr) {
167
- return
168
- }
169
-
170
- const keys = this.cache.keys()
171
- for (const key of keys) {
172
- if (key.indexOf(startStr) === 0) {
173
- this.del(key)
174
- }
175
- }
176
- }
177
- flushCache () {
178
- this.cache.flushAll()
179
- }
180
- }
181
-
182
- module.exports = TheAuthAPI
package/test.js DELETED
@@ -1,139 +0,0 @@
1
- const express = require('express')
2
- // const delay = require('delay')
3
- // const pify = require('pify')
4
- const auth = require('basic-auth').auth
5
- require('dotenv').config()
6
- const test = require('ava')
7
- const version = require('./package.json').version
8
- const TheAuthAPI = require('.')
9
- /* var sinon = require('sinon')
10
- var spy = sinon.spy
11
- var stub = sinon.stub
12
-
13
- const noop = () => {}
14
-
15
- const context = {
16
- library: {
17
- name: 'theanalyticsapi',
18
- version
19
- }
20
- }
21
-
22
- const metadata = { nodeVersion: process.versions.node }
23
- */
24
- const THE_AUTH_API_KEY = process.env.THE_AUTH_API_KEY
25
- const TEST_USERS_API_KEY = process.env.TEST_USERS_API_KEY
26
-
27
- const port = 4063
28
-
29
- const createClient = options => {
30
- options = Object.assign({
31
- host: `http://localhost:${port}`
32
- }, options)
33
-
34
- const client = new TheAuthAPI('key', options)
35
- return client
36
- }
37
-
38
- test.before.cb(t => {
39
- express()
40
- .post('/auth/authenticate', (req, res) => {
41
- const batch = req.body
42
-
43
- const { name: writeKey } = auth(req)
44
- if (!writeKey) {
45
- return res.status(400).json({
46
- error: { message: 'missing write key' }
47
- })
48
- }
49
-
50
- const ua = req.headers['user-agent']
51
- if (ua !== `theauthapi-client-node/${version}`) {
52
- return res.status(400).json({
53
- error: { message: 'invalid user-agent' }
54
- })
55
- }
56
-
57
- if (batch[0] === 'error') {
58
- return res.status(400).json({
59
- error: { message: 'error' }
60
- })
61
- }
62
-
63
- if (batch[0] === 'timeout') {
64
- return setTimeout(() => res.end(), 5000)
65
- }
66
-
67
- res.json({})
68
- })
69
- .listen(port, t.end)
70
- })
71
-
72
- test('expose a constructor', t => {
73
- t.is(typeof TheAuthAPI, 'function')
74
- })
75
- /*
76
- test('require a write key', t => {
77
- t.throws(() => new TheAuthAPI(), 'You must pass your project\'s write key.')
78
- })
79
- */
80
- test('default options', t => {
81
- const client = new TheAuthAPI('key')
82
-
83
- t.is(client.writeKey, 'key')
84
- t.is(client.host, 'https://api.theauthapi.com')
85
- })
86
-
87
- test('remove trailing slashes from `host`', t => {
88
- const client = new TheAuthAPI('key', { host: 'http://google.com///' })
89
-
90
- t.is(client.host, 'http://google.com')
91
- })
92
-
93
- test('overwrite defaults with options', t => {
94
- const client = new TheAuthAPI('key', {
95
- host: 'a'
96
- })
97
-
98
- t.is(client.host, 'a')
99
- })
100
-
101
- test('test real request', async t => {
102
- const client = new TheAuthAPI(THE_AUTH_API_KEY)
103
-
104
- t.is(client.writeKey, THE_AUTH_API_KEY)
105
- t.is(client.host, 'https://api.theauthapi.com')
106
- const response = await client.authenticateAPIKey(TEST_USERS_API_KEY)
107
-
108
- t.is(response.authenticated, true)
109
- t.is(response.customAccountId, '1234-npm')
110
- t.is(response.customMetadata.env, 'dev')
111
- })
112
-
113
- test('test real request bad key', async t => {
114
- const client = new TheAuthAPI('bad key')
115
-
116
- t.is(client.writeKey, 'bad key')
117
- t.is(client.host, 'https://api.theauthapi.com')
118
- const response = await client.authenticateAPIKey(TEST_USERS_API_KEY)
119
-
120
- t.is(response.authenticated, true)
121
- t.is(response.customAccountId, '1234-npm')
122
- t.is(response.customMetadata.env, 'dev')
123
- })
124
- test('isErrorRetryable', t => {
125
- const client = createClient()
126
-
127
- t.false(client._isErrorRetryable({}))
128
-
129
- // ETIMEDOUT is retryable as per `is-retry-allowed` (used by axios-retry in `isNetworkError`).
130
- t.true(client._isErrorRetryable({ code: 'ETIMEDOUT' }))
131
-
132
- // ECONNABORTED is not retryable as per `is-retry-allowed` (used by axios-retry in `isNetworkError`).
133
- t.false(client._isErrorRetryable({ code: 'ECONNABORTED' }))
134
-
135
- t.true(client._isErrorRetryable({ response: { status: 500 } }))
136
- t.true(client._isErrorRetryable({ response: { status: 429 } }))
137
-
138
- t.false(client._isErrorRetryable({ response: { status: 200 } }))
139
- })