navidev-abap-gw-api
Version:
API para la extracción de datos de servicios SAP GW
269 lines (268 loc) • 13.7 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const Result_1 = require("navidev-adt-api/dist/shared/core/Result");
const crudOperationsApp_1 = __importDefault(require("./crudOperationsApp"));
const crudOperationsTypes_1 = require("./crudOperationsTypes");
const queryUtils_1 = __importDefault(require("./queryUtils"));
const postUtils_1 = __importDefault(require("./postUtils"));
const draftConstants_1 = require("../shared/constants/draftConstants");
class CrudOperationsV4App extends crudOperationsApp_1.default {
query(entity, parameters) {
return __awaiter(this, void 0, void 0, function* () {
this.readEntityInfo(entity);
if (!this.entityInfo)
return Result_1.Result.fail(this.adtExceptionController.fromText("Entity no valid."));
const queryUtils = new queryUtils_1.default(this.entityInfo, this.serviceBindingInfo.versionOdata);
let parametersAux = Object.assign(Object.assign({}, parameters), { filterComplex: Object.assign(Object.assign({}, parameters === null || parameters === void 0 ? void 0 : parameters.filterComplex), { or: [
{ IsActiveEntity: false },
{ "SiblingEntity/IsActiveEntity": null },
] }) });
const query = queryUtils.buildQuery(parametersAux);
const response = yield this.connectionController.request(`${this.serviceBindingInfo.serviceUrl}/${entity}${query}`, {
method: "GET",
});
if (response.isSuccess) {
let httpResponse = response.getValue();
let json = JSON.parse(httpResponse.body);
let mappedValues = queryUtils.mappingSAPJSON2Array(json.value);
return Result_1.Result.ok(mappedValues);
}
else {
return Result_1.Result.fail(response.getErrorValue());
}
});
}
read(entity, keys) {
return __awaiter(this, void 0, void 0, function* () {
this.readEntityInfo(entity);
if (!this.entityInfo)
return Result_1.Result.fail(this.adtExceptionController.fromText("Entity no valid."));
const queryUtils = new queryUtils_1.default(this.entityInfo, this.serviceBindingInfo.versionOdata);
let query = queryUtils.buildReadQuery(keys);
const response = yield this.connectionController.request(`${this.serviceBindingInfo.serviceUrl}/${entity}${query}`, {
method: "GET",
});
if (response.isSuccess) {
let httpResponse = response.getValue();
let json = JSON.parse(httpResponse.body);
return Result_1.Result.ok(json);
}
else {
return Result_1.Result.fail(response.getErrorValue());
}
});
}
post(entity, values, parameters) {
return __awaiter(this, void 0, void 0, function* () {
this.readEntityInfo(entity);
if (!this.entityInfo)
return Result_1.Result.fail(this.adtExceptionController.fromText("Entity no valid."));
let responseDraft;
const postUtils = new postUtils_1.default(this.entityInfo, this.serviceBindingInfo.versionOdata);
const entryStatus = yield this.checkEntryStatus(entity, postUtils.buildFieldKeysFromValues(values));
// Info del ETAG necesario para poder actualizar
let odataEtag = entryStatus.odataEtag;
// Si tiene registro activo y no tiene borrador hay que activarlo para que no de error
// que la entrada ya existe.
if (entryStatus.haveActiveEntity) {
if (!entryStatus.haveDraftEntity) {
const responseCreateDraft = yield this.createDraft(entity, postUtils.buildFieldKeysFromValues(values), odataEtag);
if (responseCreateDraft.isFailure)
return Result_1.Result.fail(responseCreateDraft.getErrorValue());
odataEtag = responseCreateDraft.getValue();
}
responseDraft = yield this.saveDraft(entity, values, odataEtag);
}
else {
responseDraft = yield this.createEntry(entity, values);
}
if (responseDraft.isFailure)
return Result_1.Result.fail(responseDraft.getErrorValue());
if (parameters === null || parameters === void 0 ? void 0 : parameters.v4.activateDraft)
yield this.activateDraft(entity, postUtils.buildFieldKeysFromValues(values), responseDraft.getValue()[draftConstants_1.DRAFT_INFO_TYPE_FIELDS.ODATA_ETAG]);
return Result_1.Result.ok(responseDraft.getValue());
});
}
/**
* Crea una nueva entrada cuando no hay registros previos. La crea como borrador.
* @param entity
* @param values
* @returns
*/
createEntry(entity, values) {
return __awaiter(this, void 0, void 0, function* () {
const postUtils = new postUtils_1.default(this.entityInfo, this.serviceBindingInfo.versionOdata);
const body = postUtils.mappingObject2SAPJSON(values);
const responsePost = yield this.connectionController.request(`${this.serviceBindingInfo.serviceUrl}/${entity}`, {
method: "POST",
headers: {
"content-type": "application/json",
Accept: "application/json",
},
body: body,
});
if (responsePost.isFailure)
return Result_1.Result.fail(responsePost.getErrorValue());
const response = responsePost.getValue();
const valuesParsed = JSON.parse(response.body);
const valuesOutput = postUtils.mappingSAPJSON2Object(valuesParsed);
return Result_1.Result.ok(valuesOutput);
});
}
/**
* Graba los datos del borrador
* @param entity
* @param values
* @param odataEtag
* @returns
*/
saveDraft(entity, values, odataEtag) {
return __awaiter(this, void 0, void 0, function* () {
const postUtils = new postUtils_1.default(this.entityInfo, this.serviceBindingInfo.versionOdata);
const keyFields = postUtils.buildFieldKeysFromValues(values);
const query = postUtils.buildPatchQuery(Object.assign(Object.assign({}, keyFields), { [draftConstants_1.KEYS_FIELDS.DRAFT_ACTIVE]: false }));
const body = postUtils.mappingObject2SAPJSON(values, Object.keys(keyFields));
// Si no hay campos no se realiza ningun acción. Esto puede ocurrir cuando se activa un borrador y solo se han pasado
// los campos clave.
if (body == "{}")
return Result_1.Result.ok();
const responseSave = yield this.connectionController.request(`${this.serviceBindingInfo.serviceUrl}/${entity}${query}`, {
method: "PATCH",
headers: {
"content-type": "application/json",
Accept: "application/json",
"If-Match": odataEtag,
},
body: body,
});
if (responseSave.isFailure)
return Result_1.Result.fail(responseSave.getErrorValue());
const response = responseSave.getValue();
const valuesParsed = JSON.parse(response.body);
const valuesOutput = postUtils.mappingSAPJSON2Object(valuesParsed);
return Result_1.Result.ok(valuesOutput);
});
}
/**
* Pasos los datos del borrador a la tabla activa
* @param entity
* @param keys
* @param odataEtag
* @returns
*/
activateDraft(entity, keys, odataEtag) {
return __awaiter(this, void 0, void 0, function* () {
const query = new postUtils_1.default(this.entityInfo, this.serviceBindingInfo.versionOdata).buildPatchQuery(Object.assign(Object.assign({}, keys), { [draftConstants_1.KEYS_FIELDS.DRAFT_ACTIVE]: false }));
const actionPrepare = `${query}/${this.metadataInfo.namespace}.${draftConstants_1.DRAFT_ACTIONS.PREPARE}`;
const responsePrepare = yield this.connectionController.request(`${this.serviceBindingInfo.serviceUrl}/${entity}${actionPrepare}`, {
method: "POST",
headers: {
"content-type": "application/json",
Accept: "application/json",
"If-Match": odataEtag,
},
});
if (responsePrepare.isFailure) {
let error = responsePrepare.getErrorValue();
return Result_1.Result.fail(responsePrepare.getErrorValue());
}
const actionActivate = `${query}/${this.metadataInfo.namespace}.${draftConstants_1.DRAFT_ACTIONS.ACTIVATE}`;
const responseActivate = yield this.connectionController.request(`${this.serviceBindingInfo.serviceUrl}/${entity}${actionActivate}`, {
method: "POST",
headers: {
"content-type": "application/json",
Accept: "application/json",
"If-Match": "*",
},
});
if (responseActivate.isFailure)
return Result_1.Result.fail(responseActivate.getErrorValue());
return Result_1.Result.ok();
});
}
/**
* Pasos los datos del borrador a la tabla activa
* @param entity
* @param keys
* @returns
*/
createDraft(entity, keys, odataEtag) {
return __awaiter(this, void 0, void 0, function* () {
const postUtils = new postUtils_1.default(this.entityInfo, this.serviceBindingInfo.versionOdata).buildPatchQuery(Object.assign(Object.assign({}, keys), { [draftConstants_1.KEYS_FIELDS.DRAFT_ACTIVE]: true }));
const actionEdit = `${postUtils}/${this.metadataInfo.namespace}.${draftConstants_1.DRAFT_ACTIONS.EDIT}`;
const responseEdit = yield this.connectionController.request(`${this.serviceBindingInfo.serviceUrl}/${entity}${actionEdit}`, {
method: "POST",
headers: {
"content-type": "application/json",
Accept: "application/json",
"If-Match": odataEtag,
},
body: JSON.stringify({ PreserveChanges: true }),
});
if (responseEdit.isFailure)
return Result_1.Result.fail(responseEdit.getErrorValue());
let httpResponse = responseEdit.getValue();
return Result_1.Result.ok(httpResponse.headers[draftConstants_1.DRAFT_FIELDS.HTTP_HEADER.ETAG]);
});
}
/**
* Verifica el estado de la entrada para ver si tiene borrador, o no. etc.
* @param entity
* @param keys
* @returns
*/
checkEntryStatus(entity, keys) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
let entryStatus = {
haveActiveEntity: false,
haveDraftEntity: false,
odataEtag: "",
};
let parametersQuery = {
filters: [],
expand: "DraftAdministrativeData",
};
Object.keys(keys).forEach((rowKey) => {
var _a;
(_a = parametersQuery.filters) === null || _a === void 0 ? void 0 : _a.push({
field: rowKey,
option: crudOperationsTypes_1.FilterOptions.equal,
value1: keys[rowKey],
});
});
const responseQuery = yield this.query(entity, parametersQuery);
if (responseQuery.isSuccess) {
let values = responseQuery.getValue();
if (values.length > 0) {
entryStatus.haveActiveEntity =
values[0][draftConstants_1.DRAFT_FIELDS.HAS_ACTIVATE_ENTITY] ||
values[0][draftConstants_1.DRAFT_FIELDS.IS_ACTIVATE_ENTITY]
? true
: false;
entryStatus.haveDraftEntity =
values[0][draftConstants_1.DRAFT_FIELDS.HAS_ACTIVATE_ENTITY] &&
!values[0][draftConstants_1.DRAFT_FIELDS.IS_ACTIVATE_ENTITY]
? true
: false;
entryStatus.odataEtag =
(_a = values[0][draftConstants_1.DRAFT_INFO_TYPE_FIELDS.ODATA_ETAG]) !== null && _a !== void 0 ? _a : "";
}
}
return entryStatus;
});
}
}
exports.default = CrudOperationsV4App;