UNPKG

atlas-app-services-admin-api

Version:
485 lines (484 loc) 18 kB
"use strict"; // Copyright (c) 2023 Gregory Fay // This software is licensed under the MIT License. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AtlasAppServicesClient = void 0; const API = __importStar(require(".")); const _1 = require("."); /** * No operation logger for default logging. */ class NoOpLogger { log(message, ...optionalParams) { } error(message, ...optionalParams) { } debug(message, ...optionalParams) { } } /** * Custom error for App ID retrieval failures. */ class AppIdRetrievalError extends Error { constructor(message) { super(message); this.name = 'AppIdRetrievalError'; } } /** * Custom error for unauthorized access. */ class UnauthorizedException extends Error { constructor(message) { super(message); this.name = 'UnauthorizedException'; } } /** * AtlasAppServicesClient class for interacting with Atlas App Services. */ class AtlasAppServicesClient { /** * Constructor for AtlasAppServicesClient. * @param config - Configuration object containing publicKey, privateKey, baseUrl, and groupId. * @param logger - Optional logger for custom logging. */ constructor(config, logger) { this.apis = {}; // Cache of instantiated APIs this.logger = logger || new NoOpLogger(); this.configParams = { username: config.publicKey, apiKey: config.privateKey, basePath: config.baseUrl, baseOptions: { headers: { 'Content-Type': 'application/json', }, }, }; this.groupId = config.groupId; } /** * Initialize the client by logging in and setting up the app. */ initialize() { return __awaiter(this, void 0, void 0, function* () { yield this.loginAndAppSetup(); }); } loginAndAppSetup() { return __awaiter(this, void 0, void 0, function* () { try { const loginResponse = yield this.doAdminLogin(); this.appsApi = new API.AppsApi(new _1.Configuration(this.configParams)); const appsResponse = yield this.appsApi.adminListApplications(this.groupId, "atlas"); if (!appsResponse.data || !appsResponse.data[0] || !appsResponse.data[0]._id) { this.logger.error(`Failed to get appID App Services Admin API: ${JSON.stringify(appsResponse.data, null, 2)}`); throw new AppIdRetrievalError('Failed to retrieve appID from App Services Admin API.'); } this.appId = appsResponse.data[0]._id; this.clientAppId = appsResponse.data[0].client_app_id; this.groupId = appsResponse.data[0].group_id; } catch (error) { throw error; } }); } doAdminLogin() { return __awaiter(this, void 0, void 0, function* () { const adminLoginRequest = { username: this.configParams.username, apiKey: this.configParams.apiKey }; this.adminApi = new API.AdminApi(new _1.Configuration(this.configParams)); const loginResponse = yield this.adminApi.adminLogin("mongodb-cloud", adminLoginRequest); if (!loginResponse.data || !loginResponse.data.access_token || !loginResponse.data.refresh_token) { throw new UnauthorizedException('Failed to Login to Atlas App Services Admin API'); } this.setAccessToken(loginResponse.data.access_token); this.refreshToken = loginResponse.data.refresh_token; this.userId = loginResponse.data.user_id; this.logger.log('Successfully completed login to Atlas App Services Admin API'); return loginResponse; }); } setAccessToken(token) { this.tokenExpiration = new Date(Date.now() + 30 * 60 * 1000); // 30 minutes from now this.accessToken = token; this.configParams.accessToken = token; } isAccessTokenValid() { if (!this.tokenExpiration) { return false; } return Date.now() < this.tokenExpiration.getTime() - 30 * 1000; // 30 seconds before expiration } ensureValidAccessToken() { return __awaiter(this, void 0, void 0, function* () { if (this.isAccessTokenValid()) { return; } this.configParams.accessToken = this.refreshToken; this.adminApi = new API.AdminApi(new _1.Configuration(this.configParams)); try { const refreshResponse = yield this.adminApi.adminCreateSession(); if (!refreshResponse || !refreshResponse.data || !refreshResponse.data.access_token) { this.logger.error(`Failed to refresh access token: ${JSON.stringify(refreshResponse.data, null, 2)}`); yield this.loginAndAppSetup(); // Re-login and re-initialize } else { this.logger.log('Successfully refreshed access token'); this.setAccessToken(refreshResponse.data.access_token); } } catch (error) { this.logger.error(`Failed to refresh access token (error): ${JSON.stringify(error.response.data, null, 2)}`); yield this.loginAndAppSetup(); // Re-login and re-initialize } }); } instantiateApi(apiName) { return __awaiter(this, void 0, void 0, function* () { yield this.ensureValidAccessToken(); const ApiClass = API[apiName]; if (typeof ApiClass !== 'function') { throw new Error(`API ${apiName} does not exist`); } const apiInstance = new ApiClass(new API.Configuration(this.configParams)); return new Proxy(apiInstance, this.createApiProxyHandler()); }); } createApiProxyHandler() { return { get: (target, propKey, receiver) => { const origMethod = target[propKey]; if (typeof origMethod === 'function') { return (...args) => { this.logger.log(`Calling method: '${String(propKey)}' with arguments: ${this.stringifyArgs(args)}`); return origMethod.apply(target, args); }; } else { return origMethod; } } }; } stringifyArgs(args, depth = 2) { const cache = []; return JSON.stringify(args, (key, value) => { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // Circular reference found, discard key return; } // Store value in our collection cache.push(value); } return value; }, depth); } /*** Getters for the APIs */ /*** Getters for the APIs */ /** * Get an instance of the Admin API. * @returns {Promise<API.AdminApi>} An instance of the Admin API. */ atlasAdminApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('AdminApi'); }); } /** * Get an instance of the API Keys API. * @returns {Promise<API.ApikeysApi>} An instance of the API Keys API. */ atlasApikeysApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('ApikeysApi'); }); } /** * Get an instance of the Apps API. * @returns {Promise<API.AppsApi>} An instance of the Apps API. */ atlasAppsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('AppsApi'); }); } /** * Get an instance of the Auth Providers API. * @returns {Promise<API.AuthprovidersApi>} An instance of the Auth Providers API. */ atlasAuthprovidersApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('AuthprovidersApi'); }); } /** * Get an instance of the Billing API. * @returns {Promise<API.BillingApi>} An instance of the Billing API. */ atlasBillingApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('BillingApi'); }); } /** * Get an instance of the Custom User Data API. * @returns {Promise<API.CustomUserDataApi>} An instance of the Custom User Data API. */ atlasCustomUserDataApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('CustomUserDataApi'); }); } /** * Get an instance of the Data API. * @returns {Promise<API.DataApiApi>} An instance of the Data API. */ atlasDataApiApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('DataApiApi'); }); } /** * Get an instance of the Dependencies API. * @returns {Promise<API.DependenciesApi>} An instance of the Dependencies API. */ atlasDependenciesApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('DependenciesApi'); }); } /** * Get an instance of the Deploy API. * @returns {Promise<API.DeployApi>} An instance of the Deploy API. */ atlasDeployApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('DeployApi'); }); } /** * Get an instance of the Email API. * @returns {Promise<API.EmailApi>} An instance of the Email API. */ atlasEmailApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('EmailApi'); }); } /** * Get an instance of the Endpoints API. * @returns {Promise<API.EndpointsApi>} An instance of the Endpoints API. */ atlasEndpointsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('EndpointsApi'); }); } /** * Get an instance of the Environments API. * @returns {Promise<API.EnvironmentsApi>} An instance of the Environments API. */ atlasEnvironmentsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('EnvironmentsApi'); }); } /** * Get an instance of the Event Subscriptions API. * @returns {Promise<API.EventSubscriptionsApi>} An instance of the Event Subscriptions API. */ atlasEventSubscriptionsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('EventSubscriptionsApi'); }); } /** * Get an instance of the Functions API. * @returns {Promise<API.FunctionsApi>} An instance of the Functions API. */ atlasFunctionsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('FunctionsApi'); }); } /** * Get an instance of the GraphQL API. * @returns {Promise<API.GraphqlApi>} An instance of the GraphQL API. */ atlasGraphqlApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('GraphqlApi'); }); } /** * Get an instance of the Hosting API. * @returns {Promise<API.HostingApi>} An instance of the Hosting API. */ atlasHostingApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('HostingApi'); }); } /** * Get an instance of the Log Forwarders API. * @returns {Promise<API.LogForwardersApi>} An instance of the Log Forwarders API. */ atlasLogForwardersApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('LogForwardersApi'); }); } /** * Get an instance of the Logs API. * @returns {Promise<API.LogsApi>} An instance of the Logs API. */ atlasLogsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('LogsApi'); }); } /** * Get an instance of the Metrics API. * @returns {Promise<API.MetricsApi>} An instance of the Metrics API. */ atlasMetricsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('MetricsApi'); }); } /** * Get an instance of the Notifications API. * @returns {Promise<API.NotificationsApi>} An instance of the Notifications API. */ atlasNotificationsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('NotificationsApi'); }); } /** * Get an instance of the Rules API. * @returns {Promise<API.RulesApi>} An instance of the Rules API. */ atlasRulesApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('RulesApi'); }); } /** * Get an instance of the Schemas API. * @returns {Promise<API.SchemasApi>} An instance of the Schemas API. */ atlasSchemasApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('SchemasApi'); }); } /** * Get an instance of the Secrets API. * @returns {Promise<API.SecretsApi>} An instance of the Secrets API. */ atlasSecretsApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('SecretsApi'); }); } /** * Get an instance of the Security API. * @returns {Promise<API.SecurityApi>} An instance of the Security API. */ atlasSecurityApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('SecurityApi'); }); } /** * Get an instance of the Services API. * @returns {Promise<API.ServicesApi>} An instance of the Services API. */ atlasServicesApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('ServicesApi'); }); } /** * Get an instance of the Sync API. * @returns {Promise<API.SyncApi>} An instance of the Sync API. */ atlasSyncApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('SyncApi'); }); } /** * Get an instance of the Triggers API. * @returns {Promise<API.TriggersApi>} An instance of the Triggers API. */ atlasTriggersApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('TriggersApi'); }); } /** * Get an instance of the Users API. * @returns {Promise<API.UsersApi>} An instance of the Users API. */ atlasUsersApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('UsersApi'); }); } /** * Get an instance of the Values API. * @returns {Promise<API.ValuesApi>} An instance of the Values API. */ atlasValuesApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('ValuesApi'); }); } /** * Get an instance of the Webhooks API. * @returns {Promise<API.WebhooksApi>} An instance of the Webhooks API. */ atlasWebhooksApi() { return __awaiter(this, void 0, void 0, function* () { return yield this.instantiateApi('WebhooksApi'); }); } } exports.AtlasAppServicesClient = AtlasAppServicesClient;