@azure/storage-queue
Version:
Microsoft Azure Storage SDK for JavaScript - Queue
549 lines (548 loc) • 22.7 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var QueueServiceClient_exports = {};
__export(QueueServiceClient_exports, {
QueueServiceClient: () => QueueServiceClient
});
module.exports = __toCommonJS(QueueServiceClient_exports);
var import_core_auth = require("@azure/core-auth");
var import_core_util = require("@azure/core-util");
var import_Pipeline = require("./Pipeline.js");
var import_StorageClient = require("./StorageClient.js");
var import_utils_common = require("./utils/utils.common.js");
var import_storage_common = require("@azure/storage-common");
var import_storage_common2 = require("@azure/storage-common");
var import_tracing = require("./utils/tracing.js");
var import_QueueClient = require("./QueueClient.js");
var import_AccountSASPermissions = require("./AccountSASPermissions.js");
var import_AccountSASSignatureValues = require("./AccountSASSignatureValues.js");
var import_AccountSASServices = require("./AccountSASServices.js");
var import_core_rest_pipeline = require("@azure/core-rest-pipeline");
function isQueueGetUserDelegationKeyParameters(parameter) {
if (!parameter || typeof parameter !== "object") {
return false;
}
const castParameter = parameter;
return castParameter.expiresOn instanceof Date;
}
class QueueServiceClient extends import_StorageClient.StorageClient {
/**
* Creates an instance of QueueServiceClient.
*
* @param connectionString - Account connection string or a SAS connection string of an Azure storage account.
* [ Note - Account connection string can only be used in NODE.JS runtime. ]
* Account connection string example -
* `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net`
* SAS connection string example -
* `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString`
* @param options - Options to configure the HTTP pipeline.
* @returns A new QueueServiceClient object from the given connection string.
*/
static fromConnectionString(connectionString, options) {
options = options || {};
const extractedCreds = (0, import_utils_common.extractConnectionStringParts)(connectionString);
if (extractedCreds.kind === "AccountConnString") {
if (import_core_util.isNodeLike) {
const sharedKeyCredential = new import_storage_common.StorageSharedKeyCredential(
extractedCreds.accountName,
extractedCreds.accountKey
);
if (!options.proxyOptions) {
options.proxyOptions = (0, import_core_rest_pipeline.getDefaultProxySettings)(extractedCreds.proxyUri);
}
const pipeline = (0, import_Pipeline.newPipeline)(sharedKeyCredential, options);
return new QueueServiceClient(extractedCreds.url, pipeline);
} else {
throw new Error("Account connection string is only supported in Node.js environment");
}
} else if (extractedCreds.kind === "SASConnString") {
const pipeline = (0, import_Pipeline.newPipeline)(new import_storage_common2.AnonymousCredential(), options);
return new QueueServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline);
} else {
throw new Error(
"Connection string must be either an Account connection string or a SAS connection string"
);
}
}
/**
* serviceContext provided by protocol layer.
*/
serviceContext;
constructor(url, credentialOrPipeline, options) {
let pipeline;
if ((0, import_Pipeline.isPipelineLike)(credentialOrPipeline)) {
pipeline = credentialOrPipeline;
} else if (import_core_util.isNodeLike && credentialOrPipeline instanceof import_storage_common.StorageSharedKeyCredential || credentialOrPipeline instanceof import_storage_common2.AnonymousCredential || (0, import_core_auth.isTokenCredential)(credentialOrPipeline)) {
pipeline = (0, import_Pipeline.newPipeline)(credentialOrPipeline, options);
} else {
pipeline = (0, import_Pipeline.newPipeline)(new import_storage_common2.AnonymousCredential(), options);
}
super(url, pipeline);
this.serviceContext = this.storageClientContext.service;
}
/**
* Creates a {@link QueueClient} object.
*
* @param queueName -
* @returns a new QueueClient
*
* Example usage:
*
* ```ts snippet:ReadmeSampleCreateQueue
* import { QueueServiceClient } from "@azure/storage-queue";
* import { DefaultAzureCredential } from "@azure/identity";
*
* const account = "<account>";
* const queueServiceClient = new QueueServiceClient(
* `https://${account}.queue.core.windows.net`,
* new DefaultAzureCredential(),
* );
*
* const queueName = "<valid queue name>";
* const queueClient = queueServiceClient.getQueueClient(queueName);
* const createQueueResponse = await queueClient.create();
* console.log(
* `Created queue ${queueName} successfully, service assigned request Id: ${createQueueResponse.requestId}`,
* );
* ```
*/
getQueueClient(queueName) {
return new import_QueueClient.QueueClient((0, import_utils_common.appendToURLPath)(this.url, queueName), this.pipeline);
}
/**
* Returns a list of the queues under the specified account.
* @see https://learn.microsoft.com/rest/api/storageservices/list-queues1
*
* @param marker - A string value that identifies the portion of
* the list of queues to be returned with the next listing operation. The
* operation returns the continuationToken value within the response body if the
* listing operation did not return all queues remaining to be listed
* with the current page. The continuationToken value can be used as the value for
* the marker parameter in a subsequent call to request the next page of list
* items. The marker value is opaque to the client.
* @param options - Options to list queues operation.
* @returns Response data for the list queues segment operation.
*/
async listQueuesSegment(marker, options = {}) {
if (options.prefix === "") {
options.prefix = void 0;
}
return import_tracing.tracingClient.withSpan(
"QueueServiceClient-listQueuesSegment",
options,
async (updatedOptions) => {
return (0, import_utils_common.assertResponse)(
await this.serviceContext.listQueuesSegment({
...updatedOptions,
marker,
include: options.include === void 0 ? void 0 : [options.include]
})
);
}
);
}
/**
* Returns an AsyncIterableIterator for {@link ServiceListQueuesSegmentResponse} objects
*
* @param marker - A string value that identifies the portion of
* the list of queues to be returned with the next listing operation. The
* operation returns the continuationToken value within the response body if the
* listing operation did not return all queues remaining to be listed
* with the current page. The continuationToken value can be used as the value for
* the marker parameter in a subsequent call to request the next page of list
* items. The marker value is opaque to the client.
* @param options - Options to list queues operation.
*/
async *listSegments(marker, options = {}) {
if (options.prefix === "") {
options.prefix = void 0;
}
let listQueuesResponse;
do {
listQueuesResponse = await this.listQueuesSegment(marker, options);
marker = listQueuesResponse.continuationToken;
yield await listQueuesResponse;
} while (marker);
}
/**
* Returns an AsyncIterableIterator for {@link QueueItem} objects
*
* @param options - Options to list queues operation.
*/
async *listItems(options = {}) {
if (options.prefix === "") {
options.prefix = void 0;
}
let marker;
for await (const segment of this.listSegments(marker, options)) {
if (segment.queueItems) {
yield* segment.queueItems;
}
}
}
/**
* Returns an async iterable iterator to list all the queues
* under the specified account.
*
* .byPage() returns an async iterable iterator to list the queues in pages.
*
* Example using `for await` syntax:
*
* ```ts snippet:ReadmeSampleListQueues
* import { QueueServiceClient } from "@azure/storage-queue";
* import { DefaultAzureCredential } from "@azure/identity";
*
* const account = "<account>";
* const queueServiceClient = new QueueServiceClient(
* `https://${account}.queue.core.windows.net`,
* new DefaultAzureCredential(),
* );
*
* let i = 1;
* for await (const item of queueServiceClient.listQueues()) {
* console.log(`Queue${i++}: ${item.name}`);
* }
* ```
*
* Example using `iter.next()`:
*
* ```ts snippet:ReadmeSampleListQueues_Iterator
* import { QueueServiceClient } from "@azure/storage-queue";
* import { DefaultAzureCredential } from "@azure/identity";
*
* const account = "<account>";
* const queueServiceClient = new QueueServiceClient(
* `https://${account}.queue.core.windows.net`,
* new DefaultAzureCredential(),
* );
*
* let i = 1;
* const iterator = queueServiceClient.listQueues();
* let { done, value } = await iterator.next();
* while (!done) {
* console.log(`Queue${i++}: ${value.name}`);
* ({ done, value } = await iterator.next());
* }
* ```
*
* Example using `byPage()`:
*
* ```ts snippet:ReadmeSampleListQueues_ByPage
* import { QueueServiceClient } from "@azure/storage-queue";
* import { DefaultAzureCredential } from "@azure/identity";
*
* const account = "<account>";
* const queueServiceClient = new QueueServiceClient(
* `https://${account}.queue.core.windows.net`,
* new DefaultAzureCredential(),
* );
*
* let i = 1;
* for await (const page of queueServiceClient.listQueues().byPage({ maxPageSize: 20 })) {
* for (const item of page.queueItems || []) {
* console.log(`Queue${i++}: ${item.name}`);
* }
* }
* ```
*
* Example using paging with a marker:
*
* ```ts snippet:ReadmeSampleListQueues_Continuation
* import { QueueServiceClient } from "@azure/storage-queue";
* import { DefaultAzureCredential } from "@azure/identity";
*
* const account = "<account>";
* const queueServiceClient = new QueueServiceClient(
* `https://${account}.queue.core.windows.net`,
* new DefaultAzureCredential(),
* );
*
* let i = 1;
* let iterator = queueServiceClient.listQueues().byPage({ maxPageSize: 2 });
* let response = (await iterator.next()).value;
* // Prints 2 queues
* if (response.queueItems) {
* for (const item of response.queueItems) {
* console.log(`Queue${i++}: ${item.name}`);
* }
* }
* // Gets next marker
* let marker = response.continuationToken;
* // Passing next marker as continuationToken
* iterator = queueServiceClient.listQueues().byPage({ continuationToken: marker, maxPageSize: 10 });
* response = (await iterator.next()).value;
* // Prints 10 queues
* if (response.queueItems) {
* for (const item of response.queueItems) {
* console.log(`Queue${i++}: ${item.name}`);
* }
* }
* ```
*
* @param options - Options to list queues operation.
* @returns An asyncIterableIterator that supports paging.
*/
listQueues(options = {}) {
if (options.prefix === "") {
options.prefix = void 0;
}
const updatedOptions = {
...options,
...options.includeMetadata ? { include: "metadata" } : {}
};
const iter = this.listItems(updatedOptions);
return {
/**
* The next method, part of the iteration protocol
*/
next() {
return iter.next();
},
/**
* The connection to the async iterator, part of the iteration protocol
*/
[Symbol.asyncIterator]() {
return this;
},
/**
* Return an AsyncIterableIterator that works a page at a time
*/
byPage: (settings = {}) => {
return this.listSegments(settings.continuationToken, {
maxPageSize: settings.maxPageSize,
...updatedOptions
});
}
};
}
/**
* Gets the properties of a storage account’s Queue service, including properties
* for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules.
* @see https://learn.microsoft.com/rest/api/storageservices/get-queue-service-properties
*
* @param options - Options to get properties operation.
* @returns Response data including the queue service properties.
*/
async getProperties(options = {}) {
return import_tracing.tracingClient.withSpan(
"QueueServiceClient-getProperties",
options,
async (updatedOptions) => {
return (0, import_utils_common.assertResponse)(await this.serviceContext.getProperties(updatedOptions));
}
);
}
/**
* Sets properties for a storage account’s Queue service endpoint, including properties
* for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings.
* @see https://learn.microsoft.com/rest/api/storageservices/set-queue-service-properties
*
* @param properties -
* @param options - Options to set properties operation.
* @returns Response data for the Set Properties operation.
*/
async setProperties(properties, options = {}) {
return import_tracing.tracingClient.withSpan(
"QueueServiceClient-setProperties",
options,
async (updatedOptions) => {
return (0, import_utils_common.assertResponse)(
await this.serviceContext.setProperties(properties, updatedOptions)
);
}
);
}
/**
* Retrieves statistics related to replication for the Queue service. It is only
* available on the secondary location endpoint when read-access geo-redundant
* replication is enabled for the storage account.
* @see https://learn.microsoft.com/rest/api/storageservices/get-queue-service-stats
*
* @param options - Options to get statistics operation.
* @returns Response data for get statistics the operation.
*/
async getStatistics(options = {}) {
return import_tracing.tracingClient.withSpan(
"QueueServiceClient-getStatistics",
options,
async (updatedOptions) => {
return (0, import_utils_common.assertResponse)(await this.serviceContext.getStatistics(updatedOptions));
}
);
}
/**
* Creates a new queue under the specified account.
* @see https://learn.microsoft.com/rest/api/storageservices/create-queue4
*
* @param queueName - name of the queue to create
* @param options - Options to Queue create operation.
* @returns Response data for the Queue create operation.
*/
async createQueue(queueName, options = {}) {
return import_tracing.tracingClient.withSpan(
"QueueServiceClient-createQueue",
options,
async (updatedOptions) => {
return this.getQueueClient(queueName).create(updatedOptions);
}
);
}
/**
* Deletes the specified queue permanently.
* @see https://learn.microsoft.com/rest/api/storageservices/delete-queue3
*
* @param queueName - name of the queue to delete.
* @param options - Options to Queue delete operation.
* @returns Response data for the Queue delete operation.
*/
async deleteQueue(queueName, options = {}) {
return import_tracing.tracingClient.withSpan(
"QueueServiceClient-deleteQueue",
options,
async (updatedOptions) => {
return this.getQueueClient(queueName).delete(updatedOptions);
}
);
}
/**
* Only available for QueueServiceClient constructed with a shared key credential.
*
* Generates an account Shared Access Signature (SAS) URI based on the client properties
* and parameters passed in. The SAS is signed by the shared key credential of the client.
*
* @see https://learn.microsoft.com/rest/api/storageservices/create-account-sas
*
* @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not specified.
* @param permissions - Specifies the list of permissions to be associated with the SAS.
* @param resourceTypes - Specifies the resource types associated with the shared access signature.
* @param options - Optional parameters.
* @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token.
*/
generateAccountSasUrl(expiresOn, permissions = import_AccountSASPermissions.AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) {
if (!(this.credential instanceof import_storage_common.StorageSharedKeyCredential)) {
throw RangeError(
"Can only generate the account SAS when the client is initialized with a shared key credential"
);
}
if (expiresOn === void 0) {
const now = /* @__PURE__ */ new Date();
expiresOn = new Date(now.getTime() + 3600 * 1e3);
}
const sas = (0, import_AccountSASSignatureValues.generateAccountSASQueryParameters)(
{
permissions,
expiresOn,
resourceTypes,
services: import_AccountSASServices.AccountSASServices.parse("q").toString(),
...options
},
this.credential
).toString();
return (0, import_utils_common.appendToURLQuery)(this.url, sas);
}
/**
* Only available for QueueServiceClient constructed with a shared key credential.
*
* Generates string to sign for an account Shared Access Signature (SAS) URI based on the client properties
* and parameters passed in. The SAS is signed by the shared key credential of the client.
*
* @see https://learn.microsoft.com/rest/api/storageservices/create-account-sas
*
* @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not specified.
* @param permissions - Specifies the list of permissions to be associated with the SAS.
* @param resourceTypes - Specifies the resource types associated with the shared access signature.
* @param options - Optional parameters.
* @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token.
*/
generateSasStringToSign(expiresOn, permissions = import_AccountSASPermissions.AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) {
if (!(this.credential instanceof import_storage_common.StorageSharedKeyCredential)) {
throw RangeError(
"Can only generate the account SAS when the client is initialized with a shared key credential"
);
}
if (expiresOn === void 0) {
const now = /* @__PURE__ */ new Date();
expiresOn = new Date(now.getTime() + 3600 * 1e3);
}
return (0, import_AccountSASSignatureValues.generateAccountSASQueryParametersInternal)(
{
permissions,
expiresOn,
resourceTypes,
services: import_AccountSASServices.AccountSASServices.parse("q").toString(),
...options
},
this.credential
).stringToSign;
}
async getUserDelegationKey(startsOnOrParam, expiresOnOrOption, options = {}) {
let startsOn = startsOnOrParam;
let expiresOn = expiresOnOrOption;
let userDelegationTid = void 0;
let getUserDelegationKeyOptions = options;
if (isQueueGetUserDelegationKeyParameters(startsOnOrParam)) {
startsOn = startsOnOrParam.startsOn;
expiresOn = startsOnOrParam.expiresOn;
userDelegationTid = startsOnOrParam.delegatedUserTenantId;
getUserDelegationKeyOptions = expiresOnOrOption;
}
return import_tracing.tracingClient.withSpan(
"QueueServiceClient-getUserDelegationKey",
getUserDelegationKeyOptions,
async (updatedOptions) => {
const response = (0, import_utils_common.assertResponse)(
await this.serviceContext.getUserDelegationKey(
{
start: (0, import_utils_common.truncatedISO8061Date)(startsOn, false),
expiry: (0, import_utils_common.truncatedISO8061Date)(expiresOn, false),
delegatedUserTid: userDelegationTid
},
{
abortSignal: options.abortSignal,
tracingOptions: updatedOptions.tracingOptions
}
)
);
const userDelegationKey = {
signedObjectId: response.signedObjectId,
signedTenantId: response.signedTenantId,
signedStartsOn: new Date(response.signedStartsOn),
signedExpiresOn: new Date(response.signedExpiresOn),
signedService: response.signedService,
signedVersion: response.signedVersion,
signedDelegatedUserTenantId: response.signedDelegatedUserTenantId,
value: response.value
};
const res = {
_response: response._response,
requestId: response.requestId,
clientRequestId: response.clientRequestId,
version: response.version,
date: response.date,
...userDelegationKey
};
return res;
}
);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueueServiceClient
});
//# sourceMappingURL=QueueServiceClient.js.map