UNPKG

@sp-api-sdk/auth

Version:
77 lines (76 loc) 2.74 kB
import process from 'node:process'; import { AxiosError } from 'axios'; import { SellingPartnerApiAuthError } from './error'; import { axios } from './utils/axios'; /** * Class for simplify auth with Selling Partner API */ export class SellingPartnerApiAuth { clientId; clientSecret; refreshToken; scopes; #accessToken; #accessTokenExpiration; constructor(parameters) { const clientId = parameters.clientId ?? process.env.LWA_CLIENT_ID; const clientSecret = parameters.clientSecret ?? process.env.LWA_CLIENT_SECRET; const refreshToken = parameters.refreshToken ?? process.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.post('/o2/token', body); expiration.setSeconds(expiration.getSeconds() + data.expires_in); this.#accessToken = data.access_token; this.#accessTokenExpiration = expiration; } catch (error) { if (error instanceof AxiosError) { throw new SellingPartnerApiAuthError(error); } throw error; } } return this.#accessToken; } /** * Access token expiration date */ get accessTokenExpiration() { return this.#accessTokenExpiration; } } export { SellingPartnerApiAuthError } from './error'; export { AuthorizationScope } from './types/scope';