@microsoft/kiota-abstractions
Version:
Core abstractions for kiota generated libraries in TypeScript and JavaScript
298 lines • 12.7 kB
JavaScript
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { trace } from "@opentelemetry/api";
import { StdUriTemplate } from "@std-uritemplate/std-uritemplate";
import { DateOnly } from "./dateOnly.js";
import { Duration } from "./duration.js";
import { Headers } from "./headers.js";
import { MultipartBody } from "./multipartBody.js";
import { createRecordWithCaseInsensitiveKeys } from "./recordWithCaseInsensitiveKeys.js";
import { TimeOnly } from "./timeOnly.js";
/** This class represents an abstract HTTP request. */
export class RequestInformation {
/**
* Initializes a request information instance with the provided values.
* @param httpMethod The HTTP method for the request.
* @param urlTemplate The URL template for the request.
* @param pathParameters The path parameters for the request.
*/
constructor(httpMethod, urlTemplate, pathParameters) {
/** The path parameters for the request. */
this.pathParameters = createRecordWithCaseInsensitiveKeys();
/** The Query Parameters of the request. */
this.queryParameters = createRecordWithCaseInsensitiveKeys();
/** The Request Headers. */
this.headers = new Headers();
this._requestOptions = createRecordWithCaseInsensitiveKeys();
/**
* Sets the request body from a model with the specified content type.
* @param requestAdapter The adapter service to get the serialization writer from.
* @param contentType the content type.
* @param value the models.
* @param modelSerializerFunction the serialization function for the model type.
*/
this.setContentFromParsable = (requestAdapter, contentType, value, modelSerializerFunction) => {
trace.getTracer(RequestInformation.tracerKey).startActiveSpan("setContentFromParsable", (span) => {
try {
const writer = this.getSerializationWriter(requestAdapter, contentType, value);
if (value instanceof MultipartBody) {
contentType += "; boundary=" + value.getBoundary();
}
if (!this.headers) {
this.headers = new Headers();
}
if (Array.isArray(value)) {
span.setAttribute(RequestInformation.requestTypeKey, "object[]");
writer.writeCollectionOfObjectValues(undefined, value, modelSerializerFunction);
}
else {
span.setAttribute(RequestInformation.requestTypeKey, "object");
writer.writeObjectValue(undefined, value, modelSerializerFunction);
}
this.setContentAndContentType(writer, contentType);
}
finally {
span.end();
}
});
};
this.setContentAndContentType = (writer, contentType) => {
if (contentType) {
this.headers.tryAdd(RequestInformation.contentTypeHeader, contentType);
}
this.content = writer.getSerializedContent();
};
this.getSerializationWriter = (requestAdapter, contentType, ...values) => {
if (!requestAdapter)
throw new Error("httpCore cannot be undefined");
if (!contentType)
throw new Error("contentType cannot be undefined");
if (!values || values.length === 0) {
throw new Error("values cannot be undefined or empty");
}
return requestAdapter.getSerializationWriterFactory().getSerializationWriter(contentType);
};
/**
* Sets the request body from a model with the specified content type.
* @param requestAdapter The adapter service to get the serialization writer from.
* @param contentType the content type.
* @param value the scalar values to serialize.
*/
this.setContentFromScalar = (requestAdapter, contentType, value) => {
trace.getTracer(RequestInformation.tracerKey).startActiveSpan("setContentFromScalar", (span) => {
try {
const writer = this.getSerializationWriter(requestAdapter, contentType, value);
if (!this.headers) {
this.headers = new Headers();
}
if (Array.isArray(value)) {
span.setAttribute(RequestInformation.requestTypeKey, "[]");
writer.writeCollectionOfPrimitiveValues(undefined, value);
}
else {
const valueType = typeof value;
span.setAttribute(RequestInformation.requestTypeKey, valueType);
if (!value) {
writer.writeNullValue(undefined);
}
else if (valueType === "boolean") {
writer.writeBooleanValue(undefined, value);
}
else if (valueType === "string") {
writer.writeStringValue(undefined, value);
}
else if (value instanceof Date) {
writer.writeDateValue(undefined, value);
}
else if (value instanceof DateOnly) {
writer.writeDateOnlyValue(undefined, value);
}
else if (value instanceof TimeOnly) {
writer.writeTimeOnlyValue(undefined, value);
}
else if (value instanceof Duration) {
writer.writeDurationValue(undefined, value);
}
else if (valueType === "number") {
writer.writeNumberValue(undefined, value);
}
else if (Array.isArray(value)) {
writer.writeCollectionOfPrimitiveValues(undefined, value);
}
else {
throw new Error(`encountered unknown value type during serialization ${valueType}`);
}
}
this.setContentAndContentType(writer, contentType);
}
finally {
span.end();
}
});
};
/**
* Sets the request body to be a binary stream.
* @param value the binary stream
* @param contentType the content type.
*/
this.setStreamContent = (value, contentType) => {
if (!contentType) {
contentType = RequestInformation.binaryContentType;
}
this.headers.tryAdd(RequestInformation.contentTypeHeader, contentType);
this.content = value;
};
if (httpMethod) {
this.httpMethod = httpMethod;
}
if (urlTemplate) {
this.urlTemplate = urlTemplate;
}
if (pathParameters) {
this.pathParameters = pathParameters;
}
}
/**
* Gets the URL of the request
* @returns the url string
*/
get URL() {
const rawUrl = this.pathParameters[RequestInformation.raw_url_key];
if (this.uri) {
return this.uri;
}
else if (rawUrl) {
this.URL = rawUrl;
return rawUrl;
}
else if (!this.queryParameters) {
throw new Error("queryParameters cannot be undefined");
}
else if (!this.pathParameters) {
throw new Error("pathParameters cannot be undefined");
}
else if (!this.urlTemplate) {
throw new Error("urlTemplate cannot be undefined");
}
else {
const data = {};
for (const key in this.queryParameters) {
if (this.queryParameters[key] !== null && this.queryParameters[key] !== undefined) {
data[key] = this.normalizeValue(this.queryParameters[key]);
}
}
for (const key in this.pathParameters) {
if (this.pathParameters[key] !== null && this.pathParameters[key] !== undefined) {
data[key] = this.normalizeValue(this.pathParameters[key]);
}
}
return StdUriTemplate.expand(this.urlTemplate, data);
}
}
/** Sets the URL of the request */
set URL(url) {
if (!url)
throw new Error("URL cannot be undefined");
this.uri = url;
this.queryParameters = {};
this.pathParameters = {};
}
/**
* Gets the request options for the request.
* @returns the request options.
*/
getRequestOptions() {
return this._requestOptions;
}
/**
* Adds the headers for the request.
* @param source The source collection to add the headers to
*/
addRequestHeaders(source) {
if (source) {
this.headers.addAllRaw(source);
}
}
/**
* Adds the request options for the request.
* @param options the options to add.
*/
addRequestOptions(options) {
if (!options || options.length === 0)
return;
options.forEach((option) => {
this._requestOptions[option.getKey()] = option;
});
}
/**
* Removes the request options for the request.
* @param options the options to remove.
*/
removeRequestOptions(...options) {
if (!options || options.length === 0)
return;
options.forEach((option) => {
delete this._requestOptions[option.getKey()];
});
}
normalizeValue(value) {
if (value instanceof DateOnly || value instanceof TimeOnly || value instanceof Duration) {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
if (Array.isArray(value)) {
return value.map((val) => this.normalizeValue(val));
}
return value;
}
/**
* Sets the query string parameters from a raw object.
* @param q parameters the parameters.
* @param p the mapping from code symbol to URI template parameter name.
*/
setQueryStringParametersFromRawObject(q, p) {
if (q === null || q === undefined)
return;
Object.entries(q).forEach(([k, v]) => {
let key = k;
if (p) {
const keyCandidate = p[key];
if (keyCandidate) {
key = keyCandidate;
}
}
if (typeof v === "boolean" || typeof v === "number" || typeof v === "string" || Array.isArray(v))
this.queryParameters[key] = v;
else if (v instanceof DateOnly || v instanceof TimeOnly || v instanceof Duration)
this.queryParameters[key] = v.toString();
else if (v instanceof Date)
this.queryParameters[key] = v.toISOString();
else if (v === undefined)
this.queryParameters[key] = undefined;
});
}
/**
* Configure the current request with headers, query parameters and options.
* @param config the configuration object to use.
* @param queryParametersMapper mapping between code symbols and URI template parameter names.
*/
configure(config, queryParametersMapper) {
if (!config)
return;
this.addRequestHeaders(config.headers);
this.setQueryStringParametersFromRawObject(config.queryParameters, queryParametersMapper);
this.addRequestOptions(config.options);
}
}
RequestInformation.raw_url_key = "request-raw-url";
RequestInformation.binaryContentType = "application/octet-stream";
RequestInformation.contentTypeHeader = "Content-Type";
RequestInformation.tracerKey = "@microsoft/kiota-abstractions";
RequestInformation.requestTypeKey = "com.microsoft.kiota.request.type";
//# sourceMappingURL=requestInformation.js.map