fsm-sdk
Version:
Node.JS sdk to interface with SAP Field Service Management APIs.
85 lines • 3.93 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const polyfills_1 = require("../polyfills");
const request_options_facory_1 = require("./request-options.facory");
class AuthService {
constructor(_http, _logger = console) {
this._http = _http;
this._logger = _logger;
}
_fetchAndSaveToken(config) {
return __awaiter(this, void 0, void 0, function* () {
const body = new polyfills_1.URLSearchParams(Object.assign({ grant_type: config.authGrantType }, (config.authGrantType === 'password'
? {
username: `${config.authAccountName}/${config.authUserName}`,
password: config.authPassword
}
: {})));
const response = yield this._http.request(`${config.oauthEndpoint}/token`, {
method: 'POST',
headers: Object.assign({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': `Basic ${polyfills_1.toBase64(`${config.clientIdentifier}:${config.clientSecret}`)}` }, request_options_facory_1.RequestOptionsFacory.getRequestXHeaders(config)),
body: body.toString()
});
if (config.debug && config.tokenCacheFilePath) {
try {
const fs = require('fs'); // inline import for isomorphic
fs.writeFileSync(config.tokenCacheFilePath, JSON.stringify(response));
}
catch (error) {
this._logger.error(`ERROR: could not create ${config.tokenCacheFilePath}`, error);
}
}
const token = typeof response === 'string' ? JSON.parse(response) : response;
return token;
});
}
_readToken(config) {
return __awaiter(this, void 0, void 0, function* () {
try {
return yield new Promise((resolve, fail) => {
if (config.debug && config.tokenCacheFilePath) {
const path = require('path');
const token = require(path.resolve(config.tokenCacheFilePath));
return resolve(token);
}
fail({ code: 'MODULE_NOT_FOUND' });
});
}
catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
return yield this._fetchAndSaveToken(config);
}
throw error;
}
});
}
ensureToken(config) {
return __awaiter(this, void 0, void 0, function* () {
return this._token && this._tokenExpiration && (new Date() < this._tokenExpiration)
? Promise.resolve(this._token)
: this._readToken(config)
.then(token => this.setToken(token).getToken());
});
}
getToken() {
return this._token;
}
setToken(token) {
if (!token || !token.account) {
throw new Error('invalid token');
}
this._token = token;
this._tokenExpiration = new Date(new Date().getTime() + token.expires_in * 1000);
return this;
}
}
exports.AuthService = AuthService;
//# sourceMappingURL=auth.service.js.map