@pnp/sp
Version:
pnp - provides a fluent api for working with SharePoint REST
216 lines • 8.15 kB
JavaScript
var _Search_1;
import { __decorate } from "tslib";
import { _SPInstance, spInvokableFactory } from "../spqueryable.js";
import { getHashCode, hOP, isArray } from "@pnp/core";
import { body, CacheAlways, CacheKey, invokable } from "@pnp/queryable";
import { spPost } from "../operations.js";
import { defaultPath } from "../decorators.js";
const funcs = new Map([
["text", "Querytext"],
["template", "QueryTemplate"],
["sourceId", "SourceId"],
["trimDuplicatesIncludeId", ""],
["startRow", ""],
["rowLimit", ""],
["rankingModelId", ""],
["rowsPerPage", ""],
["selectProperties", ""],
["culture", ""],
["timeZoneId", ""],
["refinementFilters", ""],
["refiners", ""],
["hiddenConstraints", ""],
["sortList", ""],
["timeout", ""],
["hithighlightedProperties", ""],
["clientType", ""],
["personalizationData", ""],
["resultsURL", ""],
["queryTag", ""],
["properties", ""],
["queryTemplatePropertiesUrl", ""],
["reorderingRules", ""],
["hitHighlightedMultivaluePropertyLimit", ""],
["collapseSpecification", ""],
["uiLanguage", ""],
["desiredSnippetLength", ""],
["maxSnippetLength", ""],
["summaryLength", ""],
]);
const props = new Map([]);
function toPropCase(str) {
return str.replace(/^(.)/, ($1) => $1.toUpperCase());
}
/**
* Creates a new instance of the SearchQueryBuilder
*
* @param queryText Initial query text
* @param _query Any initial query configuration
*/
export function SearchQueryBuilder(queryText = "", _query = {}) {
return new Proxy({
query: Object.assign({
Querytext: queryText,
}, _query),
}, {
get(self, propertyKey, proxy) {
const pk = propertyKey.toString();
if (pk === "toSearchQuery") {
return () => self.query;
}
if (funcs.has(pk)) {
return (...value) => {
const mappedPk = funcs.get(pk);
self.query[mappedPk.length > 0 ? mappedPk : toPropCase(pk)] = value.length > 1 ? value : value[0];
return proxy;
};
}
const propKey = props.has(pk) ? props.get(pk) : toPropCase(pk);
self.query[propKey] = true;
return proxy;
},
});
}
/**
* Describes the search API
*
*/
let _Search = _Search_1 = class _Search extends _SPInstance {
/**
* @returns Promise
*/
async run(queryInit) {
const query = this.parseQuery(queryInit);
const postBody = body({
request: {
...query,
HitHighlightedProperties: this.fixArrProp(query.HitHighlightedProperties),
Properties: this.fixArrProp(query.Properties),
RefinementFilters: this.fixArrProp(query.RefinementFilters),
ReorderingRules: this.fixArrProp(query.ReorderingRules),
SelectProperties: this.fixArrProp(query.SelectProperties),
SortList: this.fixArrProp(query.SortList),
},
});
const poster = new _Search_1([this, this.parentUrl]);
poster.using(CacheAlways(), CacheKey(getHashCode(JSON.stringify(postBody)).toString()));
const data = await spPost(poster, postBody);
// Create search instance copy for SearchResult's getPage request.
return new SearchResults(data, new _Search_1([this, this.parentUrl]), query);
}
/**
* Fix array property
*
* @param prop property to fix for container struct
*/
fixArrProp(prop) {
return typeof prop === "undefined" ? [] : isArray(prop) ? prop : [prop];
}
/**
* Translates one of the query initializers into a SearchQuery instance
*
* @param query
*/
parseQuery(query) {
let finalQuery;
if (typeof query === "string") {
finalQuery = { Querytext: query };
}
else if (query.toSearchQuery) {
finalQuery = query.toSearchQuery();
}
else {
finalQuery = query;
}
return finalQuery;
}
};
_Search = _Search_1 = __decorate([
defaultPath("_api/search/postquery"),
invokable(function (init) {
return this.run(init);
})
], _Search);
export { _Search };
export const Search = spInvokableFactory(_Search);
export class SearchResults {
constructor(rawResponse, _search, _query, _raw = null, _primary = null) {
this._search = _search;
this._query = _query;
this._raw = _raw;
this._primary = _primary;
this._raw = rawResponse.postquery ? rawResponse.postquery : rawResponse;
}
get ElapsedTime() {
var _a;
return ((_a = this === null || this === void 0 ? void 0 : this.RawSearchResults) === null || _a === void 0 ? void 0 : _a.ElapsedTime) || 0;
}
get RowCount() {
var _a, _b, _c;
return ((_c = (_b = (_a = this === null || this === void 0 ? void 0 : this.RawSearchResults) === null || _a === void 0 ? void 0 : _a.PrimaryQueryResult) === null || _b === void 0 ? void 0 : _b.RelevantResults) === null || _c === void 0 ? void 0 : _c.RowCount) || 0;
}
get TotalRows() {
var _a, _b, _c;
return ((_c = (_b = (_a = this === null || this === void 0 ? void 0 : this.RawSearchResults) === null || _a === void 0 ? void 0 : _a.PrimaryQueryResult) === null || _b === void 0 ? void 0 : _b.RelevantResults) === null || _c === void 0 ? void 0 : _c.TotalRows) || 0;
}
get TotalRowsIncludingDuplicates() {
var _a, _b, _c;
return ((_c = (_b = (_a = this === null || this === void 0 ? void 0 : this.RawSearchResults) === null || _a === void 0 ? void 0 : _a.PrimaryQueryResult) === null || _b === void 0 ? void 0 : _b.RelevantResults) === null || _c === void 0 ? void 0 : _c.TotalRowsIncludingDuplicates) || 0;
}
get RawSearchResults() {
return this._raw;
}
get PrimarySearchResults() {
var _a, _b, _c, _d;
if (this._primary === null) {
this._primary = this.formatSearchResults(((_d = (_c = (_b = (_a = this._raw) === null || _a === void 0 ? void 0 : _a.PrimaryQueryResult) === null || _b === void 0 ? void 0 : _b.RelevantResults) === null || _c === void 0 ? void 0 : _c.Table) === null || _d === void 0 ? void 0 : _d.Rows) || null);
}
return this._primary;
}
/**
* Gets a page of results
*
* @param pageNumber Index of the page to return. Used to determine StartRow
* @param pageSize Optional, items per page (default = 10)
*/
getPage(pageNumber, pageSize) {
// if we got all the available rows we don't have another page
if (this.TotalRows < this.RowCount) {
return Promise.resolve(null);
}
// if pageSize is supplied, then we use that regardless of any previous values
// otherwise get the previous RowLimit or default to 10
const rows = pageSize !== undefined ? pageSize : hOP(this._query, "RowLimit") ? this._query.RowLimit : 10;
const query = {
...this._query,
RowLimit: rows,
StartRow: rows * (pageNumber - 1),
};
// we have reached the end
if (query.StartRow > this.TotalRows) {
return Promise.resolve(null);
}
return this._search.run(query);
}
/**
* Formats a search results array
*
* @param rawResults The array to process
*/
formatSearchResults(rawResults) {
const results = new Array();
if (typeof (rawResults) === "undefined" || rawResults == null) {
return [];
}
const tempResults = rawResults.results ? rawResults.results : rawResults;
for (const tempResult of tempResults) {
const cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells;
results.push(cells.reduce((res, cell) => {
res[cell.Key] = cell.Value;
return res;
}, {}));
}
return results;
}
}
//# sourceMappingURL=query.js.map