Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 | 79x 79x 79x 79x 79x 107x 107x 107x 107x 4x 2x 9x 5x 6x 3x 2x 2x 2x 2x 9x 5x 4x 2x 2x 2x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 4x 4x 4x 4x 8x 2x 2x 2x 6x 6x 6x 1x 1x 1x 6x 6x 6x 2x 2x 2x 2x 1x 1x 1x 1x 1x 7x 7x 7x 7x 8x 10x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 1x 2x 1x 2x 1x 2x 2x 2x 2x 2x 1x 3x 1x 7x 7x 7x 1x 6x 1x 1x 5x 1x 4x 1x 3x 1x 2x 2x 2x 7x 7x 11x 7x 7x 9x 7x 14x 7x 79x | "use strict";
const _ = require("lodash");
const Resource = require("./Resource");
const responseType = require("./responseType");
const parsers = require("../agent/parsers");
const requestPut = require("./request/put");
/**
* Envelope GET/POST/PUT/DELETE methods for particular QueryableResource
*
* @class QueryableResource
* @extends {Resource}
*/
class QueryableResource extends Resource {
/**
* Creates an instance of <code>QueryableResource</code>.
* @param {Agent} agent instance of the Agent class @see Agent.js
* @param {Metadata} metadata instance of the metadata object that keeps service metadata
* @param {Object} entitySetModel information about EntitySet parsed from Metadata
* @param {Object} entityTypeModel information about EntityType parsed from Metadata
* @memberof QueryableResource
*/
constructor(agent, metadata, entitySetModel, entityTypeModel) {
super(agent, {
_query: {},
});
Object.defineProperty(this, "metadata", {
value: metadata,
});
Object.defineProperty(this, "entitySetModel", {
value: entitySetModel,
});
Object.defineProperty(this, "entityTypeModel", {
value: entityTypeModel,
});
}
// see RequestDefinition.top
top(top) {
this.defaultRequest.top(top);
return this;
}
// see RequestDefinition.select
select(...args) {
this.defaultRequest.select(...args);
return this;
}
// see RequestDefinition.skip
skip(skip) {
this.defaultRequest.skip(skip);
return this;
}
// see RequestDefinition.filter
filter(filter) {
this.defaultRequest.filter(filter);
return this;
}
// see RequestDefinition.orderby
orderby(...args) {
this.defaultRequest.orderby(...args);
return this;
}
// see RequestDefinition.expand
expand(...args) {
this.defaultRequest.expand(...args);
return this;
}
// see RequestDefinition.search
search(pattern) {
this.defaultRequest.search(pattern);
return this;
}
// see RequestDefinition.key
key(entityKey) {
return this.defaultRequest.key(entityKey);
}
/**
* Send request to count of the EntitySet
*
* @param {RequestDefinition} [request] optional request definition (default entity set request is used as default)
*
* @return {Promise} returned promise is resolved when request is finished
*
* @memberof QueryableResource
*/
count(request = this.defaultRequest) {
return request.count();
}
/**
* Sends GET request to the entity set.
*
* @param {*} args some arguments
* supported argument variants
* 1. one number argument -> list top query
* 2. no arguments and key defined -> get entity entity
* 3. one plain object argument -> get entity with key from this object
* 4. no arguments and key not defined -> list query
*
* @return {Promise} returned promise is resolved when request is finished
* @memberof QueryableResource
*/
get(...args) {
return this.defaultRequest.get(...args);
}
/**
* Send request to create new entity by HTTP POST method
*
* @param {String} body map of the new entity which is end to the new repository
*
* @return {Promise} returned promise is resolved when request is finished
* Promise is resolved with response object which contains res.body and body
* contains newly created object.
*
* @memberof QueryableResource
*/
post(body) {
let defaultBatch = this.agent.batchManager.defaultBatch;
let defaultChangeSet = this.agent.batchManager.defaultChangeSet;
let urlQuery = this.urlQuery();
let path = urlQuery
? `/${this.getListResourcePath()}?${urlQuery}`
: `/${this.getListResourcePath()}`;
this.defaultRequest.payload(this.bodyProperties(body));
return defaultBatch
? this._handleBatchCall(() => {
this.defaultRequest.header("Accept", "application/json");
return defaultBatch.post(
path,
this.defaultRequest._headers,
this.defaultRequest._payload,
defaultChangeSet
);
}, defaultBatch)
: this._handleAgentCall((request) => {
request.header("Content-Type", "application/json");
return this.agent.post(
path,
request._headers,
JSON.stringify(request._payload)
);
});
}
/**
* Send request to update an entity by HTTP PUT method
*
* @param {String} body map of new data for the entity
*
* @return {Promise} returned promise is resolved when request is finished
* Promise is resolved with response object which doesn't contain body
*
* @memberof QueryableResource
*/
put(body) {
return requestPut.call(body, this);
}
/**
* Send request to update an entity by HTTP MERGE method (update for
* OData protocol version 1.0-2.0)
*
* @param {Object} body map of key properties and new data for the entity
* @param {Object} [propertiesToChange] map of new data for the entity
*
* @return {Promise} returned promise is resolved when request is finished
* Promise is resolved with response object which doesn't contain body
*
* @memberof QueryableResource
*/
merge(...args) {
return this.processUpdateCall("merge", ...args);
}
/**
* Send request to update an entity by HTTP MERGE method
*
* @param {Object} body map of key properties and new data for the entity
* @param {Object} [propertiesToChange] map of new data for the entity
*
* @return {Promise} returned promise is resolved when request is finished
* Promise is resolved with response object which doesn't contain body
*
* @memberof QueryableResource
*/
patch(...args) {
return this.processUpdateCall("patch", ...args);
}
/**
* Send request to update entity via MERGE or PATCH method. The method
* unify code for patch and merge methods.
*
* @param {String} methodName name of method from agent "merge" or "patch"
* @param {Object} body map of key properties and new data for the entity
* @param {Object} [propertiesToChange] map of new data for the entity
*
* @return {Promise} returned promise is resolved when request is finished
* Promise is resolved with response object which doesn't contain body
*
* @private
* @memberof QueryableResource
*/
processUpdateCall(methodName, ...args) {
let keyProperties;
let keyPredicate;
let propertiesToChange;
let entity;
let path;
let defaultBatch = this.agent.batchManager.defaultBatch;
let defaultChangeSet = this.agent.batchManager.defaultChangeSet;
Iif (args.length === 0 || args.length > 2) {
throw new Error(`Invalid body parameter for ${methodName}.`);
} else if (args.length === 1) {
entity = _.assign({}, args[0], this.defaultRequest._keyValue);
keyProperties = this.keyProperties(entity);
keyPredicate = this.keyPredicate(keyProperties);
propertiesToChange = _.pickBy(
entity,
(value, key) => !_.has(keyProperties, key)
);
} else {
keyProperties = this.keyProperties(args[0]);
keyPredicate = this.keyPredicate(keyProperties);
// note: following assignment allows to change also properties which are part of the key
propertiesToChange = args[1];
}
path = `/${this.entitySetModel.name}(${keyPredicate})`;
this.defaultRequest.payload(this.bodyProperties(propertiesToChange));
return defaultBatch
? this._handleBatchCall(() => {
this.defaultRequest.header("Accept", "application/json");
this.defaultRequest.header("If-Match", "*");
return defaultBatch[methodName](
path,
this.defaultRequest._headers,
this.defaultRequest._payload,
defaultChangeSet
);
}, defaultBatch)
: this._handleAgentCall((request) => {
request.header("Content-Type", "application/json");
request.header("If-Match", "*");
return this.agent[methodName](
path,
request._headers,
JSON.stringify(request._payload)
);
});
}
/**
* Send request to delete an entity by HTTP DELETE method
*
* @param {String} properties map of key properties of the entity which is to be deleted
*
* @return {Promise} returned promise is resolved when request is finished
* Promise is resolved with response object which doesn't contain body
*
* @memberof QueryableResource
*/
delete(properties) {
let defaultBatch = this.agent.batchManager.defaultBatch;
let defaultChangeSet = this.agent.batchManager.defaultChangeSet;
let path;
if (arguments.length > 0) {
this.key(properties);
}
path = `/${this.getSingleResourcePath()}`;
return defaultBatch
? this._handleBatchCall(() => {
this.defaultRequest.header("If-Match", "*");
return defaultBatch.delete(
path,
this.defaultRequest._headers,
defaultChangeSet
);
}, defaultBatch)
: this._handleAgentCall((request) => {
request.header("If-Match", "*");
return this.agent.delete(path, request._headers);
});
}
/**
* Send GET request to fetch entities requested by clauses like filter, top, count ...
*
* @private
* @param {RequestDefinition} request request definition
* @return {Promise} returned promise is resolved when request is finished
* @memberof QueryableResource
*/
executeGet(request) {
const defaultBatch = this.agent.batchManager.defaultBatch;
const defaultChangeSet = this.agent.batchManager.defaultChangeSet;
const foundResponseType = responseType.determine(this.defaultRequest, this);
return defaultBatch
? this._handleBatchCall(() => {
request.calculatePath();
Eif (
foundResponseType !== responseType.ENTITY_VALUE &&
foundResponseType !== responseType.PROPERTY_VALUE
) {
request.header("Accept", "application/json");
}
return defaultBatch.get(
request._path,
request._headers,
defaultChangeSet,
responseType.determine(request, this)
);
}, defaultBatch)
: this._handleAgentCall(
() => this.agent.get(request._path, request._headers),
request
);
}
/**
* Filter entity object to key properties for the EntitySet
*
* @private
* @param {Object} entity whole entity as Object
*
* @return {Object} the part of the entity with the key properties only
*
* @memberof QueryableResource
*/
keyProperties(entity) {
return this.entityTypeModel.key.reduce((acc, keyProperty) => {
let key = keyProperty.name;
acc[key] = keyProperty.type.format(entity[key]);
return acc;
}, {});
}
/**
* Convert object with the entity key properties to URI component
*
* @protected
* @param {Object} entityKey part of the entity with key properties
*
* @return {String} the part of URI which is used as key
*
* @memberof QueryableResource
*/
keyPredicate(entityKey) {
return _.chain(entityKey)
.map((value, key) => `${key}=${value}`)
.join(",")
.value();
}
/**
* Gets path to the single entity (with key defined)
* @returns {string} path to the single entity
* @memberof QueryableResource
*/
getSingleResourcePath() {
let keyProperties = this.keyProperties(this.defaultRequest._keyValue);
let keyPredicate = this.keyPredicate(keyProperties);
return `${this.getListResourcePath()}(${keyPredicate})`;
}
/**
* Gets path to the list of entities
* @returns {string} path to the list of entities
* @memberof QueryableResource
*/
getListResourcePath() {
return this.entitySetModel.name;
}
/**
* Convert Object with values to Object with values converted to the
* OData primitives
*
* @param {Object} body map of key properties and new data for the entity
*
* @return {Object} Object with converted values
*
* @private
* @memberof QueryableResource
*/
bodyProperties(body) {
return _.assign(
this.processProperties(body, this.entityTypeModel.properties),
this.processNavigationProperties(body, this.entityTypeModel)
);
}
/**
* Convert Object with values to Object with values converted to the
* OData primitives
*
* @param {Object} entityTypeProperties map of key properties and new data for the entity
* @param {Object} entityTypeModelProperties contains definitions of the properties from EntityType
* which is used to format and check body properties
*
* @return {Object} Object with converted values
*
* @private
* @memberof QueryableResource
*/
processProperties(entityTypeProperties, entityTypeModelProperties) {
return entityTypeModelProperties
.filter((entityTypeProperty) =>
_.has(entityTypeProperties, entityTypeProperty.name)
)
.reduce((acc, entityTypeProperty) => {
acc[entityTypeProperty.name] = entityTypeProperty.type.formatBody(
entityTypeProperties[entityTypeProperty.name]
);
return acc;
}, {});
}
/**
* Format and check navigation properties objects
*
* @param {Object} entityTypeProperties is object which contains navigation properties represented
* by nested objects
* @param {Object} entityTypeModel model of the entity type which is used to generate navigation properties
* payload
*
* @return {Object} Object with formatted and checked navigation properties objects
*
* @private
* @memberof QueryableResource
*/
processNavigationProperties(entityTypeProperties, entityTypeModel) {
let navigationProperties = _.get(
entityTypeModel,
"navigationProperties",
[]
);
Iif (!_.isObject(entityTypeModel)) {
throw new Error(
"entityTypeModel is mandatory parameter for navigation property preocessing."
);
}
return _.chain(navigationProperties)
.filter((navigationProperty) =>
_.has(entityTypeProperties, navigationProperty.name)
)
.map((navigationProperty) =>
this.processNavigationPropertyItems(
navigationProperty,
entityTypeProperties
)
)
.reduce(
(acc, processedNavigationProperties) =>
_.assign(acc, processedNavigationProperties),
{}
)
.value();
}
/**
* Go thru navigation propert items for active operations
* (post, merge, put)
*
* @param {NavigationProperty} navigationProperty object which represents
* navigation property definition for v2 or v4
* @param {Object} entityTypeProperties data for navigation properties
*
* @returns {Object} checked navigation properties items
*/
processNavigationPropertyItems(navigationProperty, entityTypeProperties) {
const entityTypeModelEnd = _.get(navigationProperty, "type.elementType");
const navigationPropertyItems =
entityTypeProperties[navigationProperty.name];
let navigationPropertyItemsProcessed;
if (!_.isObject(entityTypeModelEnd)) {
throw new Error(
`End EntityType for navigation property ${navigationProperty.name} from EntityType ${this.entityTypeModel.name} does not exists.`
);
}
if (navigationProperty.isCollection && _.isArray(navigationPropertyItems)) {
navigationPropertyItemsProcessed = _.map(
navigationPropertyItems,
(navigationPropertyItemsToProcess) => {
return _.assign(
this.processProperties(
navigationPropertyItemsToProcess,
_.get(entityTypeModelEnd, "properties", [])
),
this.processNavigationProperties(
navigationPropertyItemsToProcess,
entityTypeModelEnd
)
);
}
);
} else {
navigationPropertyItemsProcessed = _.assign(
this.processProperties(
navigationPropertyItems,
_.get(entityTypeModelEnd, "properties", [])
),
this.processNavigationProperties(
navigationPropertyItems,
entityTypeModelEnd
)
);
}
return {
[navigationProperty.name]: navigationPropertyItemsProcessed,
};
}
/**
* Creates a new association
*
* virtual method that has to be implemented in each inherited class
* due to circular dependency
*
* @protected
* @memberof QueryableResource
*/
createNavigationProperty() {}
/**
* Wraps agent call (preparation, result parsing, error handling).
*
* @param {function} call main call to agent (async)
* @param {RequestDefinition} requestDefinition optional request definition
* @returns {object} value parsed from response
*
* @private
* @memberof QueryableResource
*/
_handleAgentCall(call, requestDefinition) {
let request = requestDefinition || this.defaultRequest;
this.reset();
this.determineRequestHeaders(request);
return call(request).then((rawRes) => {
return this.determineResponseResult(request, rawRes);
});
}
/**
* Set up headers for particular request
*
* @param {RequestDefinition} request definition of request
*
* @private
* @memberof QueryableResource
*/
determineRequestHeaders(request) {
if (!request._isValue && !request._isCount) {
request.header("Accept", "application/json");
}
}
/**
* Returns value from response objects which is
*
* @param {RequestDefinition} request definition of request
* @param {IncommingMessage} response object from OData server
*
* @return {*} Buffer (for stream) or IncommingMessage (for raw response) or Object for JSON response
*
* @private
* @memberof QueryableResource
*/
determineResponseResult(request, response) {
let resultPath;
let promise;
let hasStream = request._resource.entityTypeModel.hasStream;
let foundResponseType = responseType.determine(request, this);
if (request._isRaw) {
promise = Promise.resolve(response);
} else if (hasStream && foundResponseType === responseType.ENTITY_VALUE) {
promise = response.arrayBuffer().then((bodyAsArrayBuffer) => {
return Buffer.from(bodyAsArrayBuffer);
});
} else if (foundResponseType === responseType.PROPERTY_VALUE) {
promise = response.text();
} else if (response.status === 204) {
promise = Promise.resolve(null);
} else if (request._isCount === true) {
promise = response.text().then((text) => parsers.count(text));
} else {
promise = response.json().then((json) => {
resultPath = this.agent.getResultPath(request._isList, json);
return this._unwrapNestedProperties(
resultPath ? _.get(json, resultPath, response.ok) : json
);
});
}
return promise;
}
/**
* Unwrap expanded navigation properties
*
* @param {Object} response Recieved response
* @returns {Object} Response with unwrapped expanded navigation properties
*
* @private
* @memberof QueryableResource
*/
_unwrapNestedProperties(response) {
let splitResponse;
let skipResultsProperty = (value) =>
_.has(value, "results")
? splitResponse(splitResponse, value.results)
: value;
let mapObjectProperties = (item) => _.mapValues(item, skipResultsProperty);
let unwrapObject = (item) =>
item && _.isObject(item) ? mapObjectProperties(item) : item;
splitResponse = (fn, item) =>
_.isArray(item) ? item.map(fn.bind(null, fn)) : unwrapObject(item);
return splitResponse(splitResponse, response);
}
}
module.exports = QueryableResource;
|