odata-batch
Version:
a simple lib for send and recieve calls odata batch
91 lines • 3.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchResponse = exports.createBatchResponse = void 0;
const utils_1 = require("./utils");
function createBatchResponse(ctor, OResponse, accept) {
return new ctor(OResponse, accept);
}
exports.createBatchResponse = createBatchResponse;
class BatchResponse {
constructor({ data, headers }, accept) {
this.accept = accept;
this.ensureHasAccept();
this.boundary = this.getBoundary(headers);
this.response = this.parseBatch(data);
}
ensureHasAccept() {
if (!this.accept) {
throw new Error('Need accept to know how parse.');
}
}
parseResponse(part) {
const responseParts = part.split("\r\n\r\n");
const httpResponseWithHeaders = responseParts[1].split("\r\n");
const regCodeAndStatus = RegExp("HTTP/1.1 ([0-9]{3}) (.+)");
const headers = httpResponseWithHeaders
.filter((header) => !regCodeAndStatus.test(header))
.map((header) => {
const headerKeyAndValue = header.match("(.+): (.+)");
if (!headerKeyAndValue) {
return {
key: '',
value: '',
};
}
return {
key: headerKeyAndValue[1],
value: headerKeyAndValue[2]
};
});
const httpCodeAndDesc = httpResponseWithHeaders[0]
.match(regCodeAndStatus);
const code = httpCodeAndDesc && httpCodeAndDesc[1] || '';
const success = code.substring(0, 1) != "4" && code.substring(0, 1) != "5";
const data = this.parseData(responseParts[2]);
return {
code,
status: httpCodeAndDesc && httpCodeAndDesc[2] || '',
headers,
data,
success,
};
}
parseData(sData) {
if (this.accept === 'application/json') {
return JSON.parse(sData);
}
const parts = sData.match(/.*/) || [''];
return parts[0];
}
parseBatch(body) {
const batchParts = body.split(RegExp("--" + this.boundary + "(?:\r\n)?(?:--\r\n)?"));
const parseResponses = batchParts
.filter((batchPart) => RegExp("^content-type", "i").test(batchPart))
.map((batchPart) => {
const boundary = batchPart.match(RegExp("boundary=(.+)", "m"));
if (!boundary) {
return batchPart;
}
const changeSetBoundary = boundary[1];
const changeSetBody = batchPart
.match(RegExp("(--" + changeSetBoundary + "\r\n[^]+--" + changeSetBoundary + ")", "i"));
const changeSetParts = changeSetBody && changeSetBody[1]
.split(RegExp("--" + changeSetBoundary + "(?:\r\n)?(?:--\r\n)?")) || [];
return changeSetParts.filter((p) => p);
});
return utils_1.flatten(parseResponses).map(p => this.parseResponse(p));
}
getBoundary(headers) {
const contentType = headers['content-type'];
const boundaryMatch = contentType.match(/boundary=([^;]+)/);
this.ensureHasBoundary(boundaryMatch);
return boundaryMatch[1];
}
ensureHasBoundary(boundaryMatch) {
if (!boundaryMatch) {
throw new Error('Bad content-type header, no multipart boundary');
}
}
}
exports.BatchResponse = BatchResponse;
//# sourceMappingURL=response.js.map