UNPKG

@sp-api-sdk/auth

Version:
86 lines (85 loc) 3.44 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AuthorizationScope = exports.SellingPartnerApiAuthError = exports.SellingPartnerApiAuth = void 0; const node_process_1 = __importDefault(require("node:process")); const axios_1 = require("axios"); const error_1 = require("./error"); const axios_2 = require("./utils/axios"); /** * Class for simplify auth with Selling Partner API */ class SellingPartnerApiAuth { clientId; clientSecret; refreshToken; scopes; #accessToken; #accessTokenExpiration; constructor(parameters) { const clientId = parameters.clientId ?? node_process_1.default.env.LWA_CLIENT_ID; const clientSecret = parameters.clientSecret ?? node_process_1.default.env.LWA_CLIENT_SECRET; const refreshToken = parameters.refreshToken ?? node_process_1.default.env.LWA_REFRESH_TOKEN; if (!clientId) { throw new Error('Missing required `clientId` configuration value'); } if (!clientSecret) { throw new Error('Missing required `clientSecret` configuration value'); } if (!refreshToken && !parameters.scopes) { throw new TypeError('Either `refreshToken` or `scopes` must be specified'); } this.clientId = clientId; this.clientSecret = clientSecret; this.refreshToken = refreshToken; this.scopes = parameters.scopes; } /** * Get access token */ async getAccessToken() { if (!this.#accessToken || (this.#accessTokenExpiration && Date.now() >= this.#accessTokenExpiration.getTime())) { const body = { client_id: this.clientId, client_secret: this.clientSecret, ...(this.refreshToken ? { grant_type: 'refresh_token', refresh_token: this.refreshToken, } : { grant_type: 'client_credentials', scope: this.scopes.join(' '), }), }; try { const expiration = new Date(); const { data } = await axios_2.axios.post('/o2/token', body); expiration.setSeconds(expiration.getSeconds() + data.expires_in); this.#accessToken = data.access_token; this.#accessTokenExpiration = expiration; } catch (error) { if (error instanceof axios_1.AxiosError) { throw new error_1.SellingPartnerApiAuthError(error); } throw error; } } return this.#accessToken; } /** * Access token expiration date */ get accessTokenExpiration() { return this.#accessTokenExpiration; } } exports.SellingPartnerApiAuth = SellingPartnerApiAuth; var error_2 = require("./error"); Object.defineProperty(exports, "SellingPartnerApiAuthError", { enumerable: true, get: function () { return error_2.SellingPartnerApiAuthError; } }); var scope_1 = require("./types/scope"); Object.defineProperty(exports, "AuthorizationScope", { enumerable: true, get: function () { return scope_1.AuthorizationScope; } });