UNPKG

jobsuche-api-js

Version:

A JavaScript wrapper for the Arbeitsagentur jobs API, allowing developers to easily integrate job search functionality into their applications.

65 lines (64 loc) 2.28 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const axios_1 = __importDefault(require("axios")); const querystring_1 = __importDefault(require("querystring")); const urls_1 = require("../constants/urls"); class AuthManager { constructor() { this.accessToken = null; this.tokenExpiresAt = null; this.clientId = null; this.clientSecret = null; } static getInstance() { if (!AuthManager.instance) { AuthManager.instance = new AuthManager(); } return AuthManager.instance; } async initialize(clientId, clientSecret) { this.clientId = clientId; this.clientSecret = clientSecret; await this.refreshToken(); // Initialize or refresh token } async fetchToken() { if (!this.clientId || !this.clientSecret) { throw new Error('Client ID or Client Secret not set.'); } const data = querystring_1.default.stringify({ client_id: this.clientId, client_secret: this.clientSecret, grant_type: 'client_credentials', }); try { const response = await axios_1.default.post(`https://${urls_1.host}${urls_1.authSuffix}`, data); this.accessToken = response.data.access_token; this.tokenExpiresAt = Date.now() + response.data.expires_in * 1000; // Convert seconds to milliseconds } catch (error) { if (axios_1.default.isAxiosError(error)) { console.error('Axios error:', error.message); console.error('Error details:', error.toJSON()); } else { console.error('Unexpected error:', error); } throw error; } } async getAccessToken() { if (!this.accessToken || !this.tokenExpiresAt || this.tokenExpiresAt < Date.now()) { await this.refreshToken(); } return this.accessToken; } async refreshToken() { await this.fetchToken(); } } exports.default = AuthManager.getInstance();