UNPKG

jobsuche-api-js

Version:

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

60 lines (59 loc) 1.98 kB
import axios from 'axios'; import querystring from 'querystring'; import { authSuffix, host } from '../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.stringify({ client_id: this.clientId, client_secret: this.clientSecret, grant_type: 'client_credentials', }); try { const response = await axios.post(`https://${host}${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.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(); } } export default AuthManager.getInstance();