Source: services/api_key_service.js

  1. import util from 'util';
  2. import Constants from '../constants';
  3. import FilteringError from '../errors/general/filtering_error';
  4. import baseService from './base_service';
  5. export default (easypostClient) =>
  6. /**
  7. * The ApiKeyService class provides methods for interacting with EasyPost {@link ApiKey} objects.
  8. * @param {EasyPostClient} easypostClient - The pre-configured EasyPostClient instance to use for API requests with this service.
  9. */
  10. class ApiKeyService extends baseService(easypostClient) {
  11. /**
  12. * Retrieve all {@link ApiKey API keys} associated with the current authenticated user.
  13. * See {@link https://docs.easypost.com/docs/api-keys#retrieve-an-api-key EasyPost API Documentation} for more information.
  14. * @returns {Object} - An object containing the API keys associated with the current authenticated user and its child users.
  15. */
  16. static async all(params = {}) {
  17. const url = 'api_keys';
  18. return this._all(url, params);
  19. }
  20. /**
  21. * Retrieve API Keys for a specified {@link User user}.
  22. * See {@link https://docs.easypost.com/docs/api-keys#retrieve-an-api-key EasyPost API Documentation} for more information.
  23. * @param {string} id - The ID of the user to retrieve keys for.
  24. * @returns {Array} - List of associated API Keys.
  25. * @throws {FilteringError} If user or API Keys are not found.
  26. */
  27. static async retrieveApiKeysForUser(id) {
  28. const url = `api_keys`;
  29. try {
  30. const response = await easypostClient._get(url);
  31. const user = this._convertToEasyPostObject(response.body);
  32. if (user.id == id) {
  33. return user.keys;
  34. }
  35. user.children.forEach((child) => {
  36. if (child.id == id) {
  37. return child.keys;
  38. }
  39. });
  40. } catch (e) {
  41. return Promise.reject(e);
  42. }
  43. throw new FilteringError({ message: util.format(Constants.NO_OBJECT_FOUND, 'child') });
  44. }
  45. };