@azure/app-configuration
Version:
An isomorphic client library for the Azure App Configuration service.
978 lines (977 loc) • 39.1 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 appConfigurationClient_exports = {};
__export(appConfigurationClient_exports, {
AppConfigurationClient: () => AppConfigurationClient
});
module.exports = __toCommonJS(appConfigurationClient_exports);
var import_core_paging = require("@azure/core-paging");
var import_core_rest_pipeline = require("@azure/core-rest-pipeline");
var import_audienceErrorHandlingPolicy = require("./internal/audienceErrorHandlingPolicy.js");
var import_syncTokenPolicy = require("./internal/syncTokenPolicy.js");
var import_queryParamPolicy = require("./internal/queryParamPolicy.js");
var import_emptyBodyPolicy = require("./internal/emptyBodyPolicy.js");
var import_core_auth = require("@azure/core-auth");
var import_helpers = require("./internal/helpers.js");
var import_appConfigurationClient = require("./generated/appConfigurationClient.js");
var import_operations = require("./generated/api/operations.js");
var import_pollingHelpers = require("./generated/static-helpers/pollingHelpers.js");
var import_appConfigCredential = require("./appConfigCredential.js");
var import_tracing = require("./internal/tracing.js");
var import_logger = require("./logger.js");
var import_lroShim = require("./internal/lroShim.js");
var import_constants = require("./internal/constants.js");
const ConnectionStringRegex = /Endpoint=(.*);Id=(.*);Secret=(.*)/;
class AppConfigurationClient {
client;
_syncTokens;
constructor(connectionStringOrEndpoint, tokenCredentialOrOptions, options) {
let appConfigOptions = {};
let appConfigCredential = void 0;
let appConfigEndpoint;
let authPolicy;
let authPolicyName;
let scope;
if ((0, import_core_auth.isTokenCredential)(tokenCredentialOrOptions)) {
appConfigOptions = options || {};
appConfigCredential = tokenCredentialOrOptions;
appConfigEndpoint = connectionStringOrEndpoint.endsWith("/") ? connectionStringOrEndpoint.slice(0, -1) : connectionStringOrEndpoint;
scope = [(0, import_helpers.getScope)(appConfigEndpoint, appConfigOptions.audience)];
authPolicyName = import_core_rest_pipeline.bearerTokenAuthenticationPolicyName;
} else {
appConfigOptions = tokenCredentialOrOptions || {};
const regexMatch = connectionStringOrEndpoint?.match(ConnectionStringRegex);
if (regexMatch) {
appConfigEndpoint = regexMatch[1];
authPolicy = (0, import_appConfigCredential.appConfigKeyCredentialPolicy)(regexMatch[2], regexMatch[3]);
authPolicyName = authPolicy.name;
} else {
throw new Error(
`Invalid connection string. Valid connection strings should match the regex '${ConnectionStringRegex.source}'. To mitigate the issue, please refer to the troubleshooting guide here at https://aka.ms/azsdk/js/app-configuration/troubleshoot.`
);
}
}
const generatedClientOptions = {
...appConfigOptions,
userAgentOptions: {
...appConfigOptions.userAgentOptions,
userAgentPrefix: `azsdk-js-app-configuration/${import_constants.packageVersion}${appConfigOptions.userAgentOptions?.userAgentPrefix ? ` ${appConfigOptions.userAgentOptions.userAgentPrefix}` : ""}`
},
loggingOptions: {
logger: import_logger.logger.info
},
apiVersion: options?.apiVersion ?? import_constants.appConfigurationApiVersion,
credentials: {}
};
generatedClientOptions.credentials = {
...generatedClientOptions.credentials,
scopes: scope
};
this._syncTokens = appConfigOptions.syncTokens || new import_syncTokenPolicy.SyncTokens();
this.client = new import_appConfigurationClient.AppConfigurationClient(
appConfigEndpoint,
// When a connection string is used, appConfigCredential is undefined here. We pass undefined to avoid @azure-rest/core-client's keyCredentialAuthenticationPolicy setting the apiKeyHeader on the request.
// Connection strings are authenticated by HMAC (appConfigKeyCredentialPolicy) and the secret should never leave the client.
// The `as TokenCredential` cast bridges a gap between the generated client and the core SDK: the generated constructor types `credential` as required (KeyCredential | TokenCredential),
// but @azure-rest/core-client's addCredentialPipelinePolicy no-ops when no credential is passed, so handing it undefined is safe at runtime.
appConfigCredential,
generatedClientOptions
);
this.client.pipeline.addPolicy(
(0, import_audienceErrorHandlingPolicy.audienceErrorHandlingPolicy)(appConfigOptions?.audience !== void 0),
{
phase: "Sign",
beforePolicies: [authPolicyName]
}
);
if (authPolicy) {
this.client.pipeline.addPolicy(authPolicy, { phase: "Sign" });
}
this.client.pipeline.addPolicy((0, import_queryParamPolicy.queryParamPolicy)());
this.client.pipeline.addPolicy((0, import_emptyBodyPolicy.emptyBodyPolicy)());
this.client.pipeline.addPolicy((0, import_syncTokenPolicy.syncTokenPolicy)(this._syncTokens), { afterPhase: "Retry" });
}
/**
* Add a setting into the Azure App Configuration service, failing if it
* already exists.
*
* Example usage:
* ```ts snippet:AddConfigurationSetting
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const result = await client.addConfigurationSetting({
* key: "MyKey",
* label: "MyLabel",
* value: "MyValue",
* });
* ```
* @param configurationSetting - A configuration setting.
* @param options - Optional parameters for the request.
*/
addConfigurationSetting(configurationSetting, options = {}) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.addConfigurationSetting",
options,
async (updatedOptions) => {
const keyValue = (0, import_helpers.serializeAsConfigurationSettingParam)(configurationSetting);
import_logger.logger.info("[addConfigurationSetting] Creating a key value pair");
try {
const originalResponse = await this.client.putKeyValue(
"application/json",
configurationSetting.key,
{
ifNoneMatch: "*",
label: configurationSetting.label,
entity: keyValue,
...updatedOptions,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
}
);
const response = (0, import_helpers.transformKeyValueResponse)(originalResponse);
(0, import_helpers.assertResponse)(response);
return response;
} catch (error) {
const err = error;
if (err.statusCode === 412) {
err.message = `Status 412: Setting was already present`;
}
throw err;
}
throw new Error("Unreachable code");
}
);
}
/**
* Delete a setting from the Azure App Configuration service
*
* Example usage:
* ```ts snippet:DeleteConfigurationSetting
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const deletedSetting = await client.deleteConfigurationSetting({
* key: "MyKey",
* label: "MyLabel",
* });
* ```
* @param id - The id of the configuration setting to delete.
* @param options - Optional parameters for the request (ex: etag, label)
*/
deleteConfigurationSetting(id, options = {}) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.deleteConfigurationSetting",
options,
async (updatedOptions) => {
let status;
import_logger.logger.info("[deleteConfigurationSetting] Deleting key value pair");
const originalResponse = await this.client.deleteKeyValue(id.key, {
label: id.label,
...updatedOptions,
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)(id, options),
onResponse: (response2) => {
status = response2.status;
},
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
});
const response = (0, import_helpers.transformKeyValueResponseWithStatusCode)(originalResponse, status);
(0, import_helpers.assertResponse)(response);
return response;
}
);
}
/**
* Gets a setting from the Azure App Configuration service.
*
* Example code:
* ```ts snippet:GetConfigurationSetting
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const setting = await client.getConfigurationSetting({ key: "MyKey", label: "MyLabel" });
* ```
* @param id - The id of the configuration setting to get.
* @param options - Optional parameters for the request.
*/
async getConfigurationSetting(id, options = {}) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.getConfigurationSetting",
options,
async (updatedOptions) => {
let status;
let rawResponse;
import_logger.logger.info("[getConfigurationSetting] Getting key value pair");
try {
const originalResponse = await this.client.getKeyValue(id.key, {
...updatedOptions,
label: id.label,
select: (0, import_helpers.formatFieldsForSelect)(options.fields),
...(0, import_helpers.formatAcceptDateTime)(options),
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)(id, options),
onResponse: (response2) => {
status = response2.status;
rawResponse = response2;
},
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
});
const response = (0, import_helpers.transformKeyValueResponseWithStatusCode)(originalResponse, status);
(0, import_helpers.assertResponse)(response);
return response;
} catch (error) {
const err = error;
if (err.statusCode === 304) {
const response = (0, import_helpers.transformKeyValueResponseWithStatusCode)(
{ _response: rawResponse },
304
);
response.key = id.key;
(0, import_helpers.makeConfigurationSettingEmpty)(response);
(0, import_helpers.assertResponse)(response);
return response;
}
throw err;
}
}
);
}
/**
* Lists settings from the Azure App Configuration service, optionally
* filtered by key names, labels and accept datetime.
*
* Example code:
* ```ts snippet:ListConfigurationSettings
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const allSettingsWithLabel = client.listConfigurationSettings({ labelFilter: "MyLabel" });
* ```
* @param options - Optional parameters for the request.
*/
listConfigurationSettings(options = {}) {
const pageEtags = options.pageEtags ? [...options.pageEtags] : void 0;
delete options.pageEtags;
const pagedResult = {
firstPageLink: void 0,
getPage: async (pageLink) => {
const etag = pageEtags?.shift();
try {
const response = await this.sendConfigurationSettingsRequest(
{ ...options, etag },
pageLink
);
const currentResponse = {
...response,
items: response.items != null ? response.items?.map(import_helpers.transformKeyValue) : [],
continuationToken: response.nextLink ? (0, import_helpers.extractAfterTokenFromNextLink)(response.nextLink) : void 0,
_response: response._response
};
return {
page: currentResponse,
nextPageLink: currentResponse.continuationToken
};
} catch (error) {
const err = error;
const link = err.response?.headers?.get("link");
const continuationToken = link ? (0, import_helpers.extractAfterTokenFromLinkHeader)(link) : void 0;
if (err.statusCode === 304) {
err.message = `Status 304: No updates for this page`;
import_logger.logger.info(
`[listConfigurationSettings] No updates for this page. The current etag for the page is ${etag}`
);
return {
page: {
items: [],
etag,
_response: { ...err.response, status: 304 }
},
nextPageLink: continuationToken
};
}
throw err;
}
},
toElements: (page) => page.items
};
return (0, import_core_paging.getPagedAsyncIterator)(pagedResult);
}
/**
* Checks settings from the Azure App Configuration service using a HEAD request, returning only headers without the response body.
* This is useful for efficiently checking if settings have changed by comparing ETags.
*
* Example code:
* ```ts snippet:CheckConfigurationSettings
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const pageIterator = client.checkConfigurationSettings({ keyFilter: "MyKey" }).byPage();
* ```
* @param options - Optional parameters for the request.
*/
checkConfigurationSettings(options = {}) {
const pageEtags = options.pageEtags ? [...options.pageEtags] : void 0;
delete options.pageEtags;
const pagedResult = {
firstPageLink: void 0,
getPage: async (pageLink) => {
const etag = pageEtags?.shift();
try {
const response = await this.checkConfigurationSettingsRequest(
{ ...options, etag },
pageLink
);
const link = response._response?.headers?.get("link");
const continuationToken = link ? (0, import_helpers.extractAfterTokenFromLinkHeader)(link) : void 0;
const currentResponse = {
...response,
etag: response._response?.headers?.get("etag"),
items: [],
continuationToken,
_response: response._response
};
return {
page: currentResponse,
nextPageLink: currentResponse.continuationToken
};
} catch (error) {
const err = error;
const link = err.response?.headers?.get("link");
const continuationToken = link ? (0, import_helpers.extractAfterTokenFromLinkHeader)(link) : void 0;
if (err.statusCode === 304) {
err.message = `Status 304: No updates for this page`;
import_logger.logger.info(
`[checkConfigurationSettings] No updates for this page. The current etag for the page is ${etag}`
);
return {
page: {
items: [],
etag,
_response: { ...err.response, status: 304 }
},
nextPageLink: continuationToken
};
}
throw err;
}
},
toElements: (page) => page.items
};
return (0, import_core_paging.getPagedAsyncIterator)(pagedResult);
}
/**
* Lists settings from the Azure App Configuration service for snapshots based on name, optionally
* filtered by key names, labels and accept datetime.
*
* Example code:
* ```ts snippet:ListConfigurationSettingsForSnashots
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const allSettingsWithLabel = client.listConfigurationSettingsForSnashots({
* snapshotName: "MySnapshot",
* });
* ```
* @param options - Optional parameters for the request.
*/
listConfigurationSettingsForSnapshot(snapshotName, options = {}) {
const pagedResult = {
firstPageLink: void 0,
getPage: async (pageLink) => {
const response = await this.sendConfigurationSettingsRequest(
{ snapshotName, ...options },
pageLink
);
const currentResponse = {
...response,
items: response.items != null ? response.items?.map(import_helpers.transformKeyValue) : [],
continuationToken: response.nextLink ? (0, import_helpers.extractAfterTokenFromNextLink)(response.nextLink) : void 0
};
return {
page: currentResponse,
nextPageLink: currentResponse.continuationToken
};
},
toElements: (page) => page.items
};
return (0, import_core_paging.getPagedAsyncIterator)(pagedResult);
}
/**
* Get a list of labels from the Azure App Configuration service
*
* Example code:
* ```ts snippet:ListLabels
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const allSettingsWithLabel = client.listLabels({ nameFilter: "prod*" });
* ```
* @param options - Optional parameters for the request.
*/
listLabels(options = {}) {
const pagedResult = {
firstPageLink: void 0,
getPage: async (pageLink) => {
const response = await this.sendLabelsRequest(options, pageLink);
const currentResponse = {
...response,
items: response.items ?? [],
continuationToken: response.nextLink ? (0, import_helpers.extractAfterTokenFromNextLink)(response.nextLink) : void 0,
_response: response._response
};
return {
page: currentResponse,
nextPageLink: currentResponse.continuationToken
};
},
toElements: (page) => page.items
};
return (0, import_core_paging.getPagedAsyncIterator)(pagedResult);
}
get _context() {
return this.client._client;
}
async sendLabelsRequest(options = {}, pageLink) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.listConfigurationSettings",
options,
async (updatedOptions) => {
const rawResponse = await (0, import_operations._getLabelsSend)(this._context, {
...updatedOptions,
...(0, import_helpers.formatAcceptDateTime)(options),
...(0, import_helpers.formatLabelsFiltersAndSelect)(options),
after: pageLink,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
});
const parsed = await (0, import_operations._getLabelsDeserialize)(rawResponse);
return Object.assign(parsed, { _response: rawResponse });
}
);
}
async sendConfigurationSettingsRequest(options = {}, pageLink) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.listConfigurationSettings",
options,
async (updatedOptions) => {
const rawResponse = await (0, import_operations._getKeyValuesSend)(this._context, {
...updatedOptions,
...(0, import_helpers.formatAcceptDateTime)(options),
...(0, import_helpers.formatConfigurationSettingsFiltersAndSelect)(options),
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)({ etag: options.etag }, { onlyIfChanged: true }),
after: pageLink,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
});
const parsed = await (0, import_operations._getKeyValuesDeserialize)(rawResponse);
return Object.assign(parsed, { _response: rawResponse });
}
);
}
async checkConfigurationSettingsRequest(options = {}, pageLink) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.checkConfigurationSettings",
options,
async (updatedOptions) => {
const rawResponse = await (0, import_operations._checkKeyValuesSend)(this._context, {
...updatedOptions,
...(0, import_helpers.formatAcceptDateTime)(options),
...(0, import_helpers.formatConfigurationSettingsFiltersAndSelect)(options),
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)({ etag: options.etag }, { onlyIfChanged: true }),
after: pageLink,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
});
await (0, import_operations._checkKeyValuesDeserialize)(rawResponse);
return {
_response: {
...rawResponse,
headers: (0, import_core_rest_pipeline.createHttpHeaders)(rawResponse.headers)
}
};
}
);
}
/**
* Lists revisions of a set of keys, optionally filtered by key names,
* labels and accept datetime.
*
* Example code:
* ```ts snippet:ListRevisions
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const revisionsIterator = client.listRevisions({ keys: ["MyKey"] });
* ```
* @param options - Optional parameters for the request.
*/
listRevisions(options) {
const pagedResult = {
firstPageLink: void 0,
getPage: async (pageLink) => {
const response = await this.sendRevisionsRequest(options, pageLink);
const currentResponse = {
...response,
items: response.items != null ? response.items.map(import_helpers.transformKeyValue) : [],
continuationToken: response.nextLink ? (0, import_helpers.extractAfterTokenFromNextLink)(response.nextLink) : void 0
};
return {
page: currentResponse,
nextPageLink: currentResponse.continuationToken
};
},
toElements: (page) => page.items
};
return (0, import_core_paging.getPagedAsyncIterator)(pagedResult);
}
async sendRevisionsRequest(options = {}, pageLink) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.listRevisions",
options,
async (updatedOptions) => {
const rawResponse = await (0, import_operations._getRevisionsSend)(this._context, {
...updatedOptions,
...(0, import_helpers.formatAcceptDateTime)(options),
...(0, import_helpers.formatFiltersAndSelect)(updatedOptions),
after: pageLink,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
});
const parsed = await (0, import_operations._getRevisionsDeserialize)(rawResponse);
return Object.assign(parsed, { _response: rawResponse });
}
);
}
/**
* Sets the value of a key in the Azure App Configuration service, allowing for an optional etag.
* @param key - The name of the key.
* @param configurationSetting - A configuration value.
* @param options - Optional parameters for the request.
*
* Example code:
* ```ts snippet:SetConfigurationSetting
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* await client.setConfigurationSetting({ key: "MyKey", value: "MyValue" });
* ```
*/
async setConfigurationSetting(configurationSetting, options = {}) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.setConfigurationSetting",
options,
async (updatedOptions) => {
const keyValue = (0, import_helpers.serializeAsConfigurationSettingParam)(configurationSetting);
import_logger.logger.info("[setConfigurationSetting] Setting new key value");
const response = (0, import_helpers.transformKeyValueResponse)(
await this.client.putKeyValue("application/json", configurationSetting.key, {
...updatedOptions,
label: configurationSetting.label,
entity: keyValue,
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)(configurationSetting, options),
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
})
);
(0, import_helpers.assertResponse)(response);
return response;
}
);
}
/**
* Sets or clears a key's read-only status.
* @param id - The id of the configuration setting to modify.
*/
async setReadOnly(id, readOnly, options = {}) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.setReadOnly",
options,
async (newOptions) => {
let response;
if (readOnly) {
import_logger.logger.info("[setReadOnly] Setting read-only status to ${readOnly}");
response = await this.client.putLock(id.key, {
...newOptions,
label: id.label,
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)(id, options),
requestOptions: {
...newOptions.requestOptions,
skipUrlEncoding: true
}
});
} else {
import_logger.logger.info("[setReadOnly] Deleting read-only lock");
response = await this.client.deleteLock(id.key, {
...newOptions,
label: id.label,
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)(id, options),
requestOptions: {
...newOptions.requestOptions,
skipUrlEncoding: true
}
});
}
response = (0, import_helpers.transformKeyValueResponse)(response);
(0, import_helpers.assertResponse)(response);
return response;
}
);
}
/**
* Adds an external synchronization token to ensure service requests receive up-to-date values.
*
* @param syncToken - The synchronization token value.
*/
updateSyncToken(syncToken) {
this._syncTokens.addSyncTokenFromHeaderValue(syncToken);
}
/**
* Begins creating a snapshot for Azure App Configuration service, fails if it
* already exists.
*/
beginCreateSnapshot(snapshot, options = {}) {
return import_tracing.tracingClient.withSpan(
`${AppConfigurationClient.name}.beginCreateSnapshot`,
options,
async (updatedOptions) => {
const generatedSnapshot = (0, import_helpers.snapshotInfoToGenerated)(snapshot);
const poller = (0, import_pollingHelpers.getLongRunningPoller)(
this._context,
async (result) => (0, import_helpers.transformSnapshotResponse)(
await (0, import_operations._createSnapshotDeserialize)(result)
),
["201", "200", "202"],
{
updateIntervalInMs: updatedOptions?.updateIntervalInMs,
abortSignal: updatedOptions?.abortSignal,
getInitialResponse: () => (0, import_operations._createSnapshotSend)(
this._context,
"application/vnd.microsoft.appconfig.snapshot+json",
snapshot.name,
generatedSnapshot,
{
...updatedOptions,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
}
),
resourceLocationConfig: "original-uri"
}
);
return (0, import_lroShim.wrapPoller)(poller);
}
);
}
/**
* Begins creating a snapshot for Azure App Configuration service, waits until it is done,
* fails if it already exists.
*/
beginCreateSnapshotAndWait(snapshot, options = {}) {
return import_tracing.tracingClient.withSpan(
`${AppConfigurationClient.name}.beginCreateSnapshotAndWait`,
options,
async (updatedOptions) => {
const generatedSnapshot = (0, import_helpers.snapshotInfoToGenerated)(snapshot);
const poller = (0, import_pollingHelpers.getLongRunningPoller)(
this._context,
async (result) => (0, import_helpers.transformSnapshotResponse)(
await (0, import_operations._createSnapshotDeserialize)(result)
),
["201", "200", "202"],
{
updateIntervalInMs: updatedOptions?.updateIntervalInMs,
abortSignal: updatedOptions?.abortSignal,
getInitialResponse: () => (0, import_operations._createSnapshotSend)(
this._context,
"application/vnd.microsoft.appconfig.snapshot+json",
snapshot.name,
generatedSnapshot,
{
...updatedOptions,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
}
),
resourceLocationConfig: "original-uri"
}
);
return poller.pollUntilDone();
}
);
}
/**
* Get a snapshot from Azure App Configuration service
*
* Example usage:
* ```ts snippet:GetSnapshot
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const retrievedSnapshot = await client.getSnapshot("testsnapshot");
* console.log("Retrieved snapshot:", retrievedSnapshot);
* ```
* @param name - The name of the snapshot.
* @param options - Optional parameters for the request.
*/
getSnapshot(name, options = {}) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.getSnapshot",
options,
async (updatedOptions) => {
import_logger.logger.info("[getSnapshot] Get a snapshot");
const originalResponse = await this.client.getSnapshot(name, {
...updatedOptions,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
});
const response = (0, import_helpers.transformSnapshotResponse)(originalResponse);
(0, import_helpers.assertResponse)(response);
return response;
}
);
}
/**
* Recover an archived snapshot back to ready status
*
* Example usage:
* ```ts snippet:RecoverSnapshot
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const result = await client.recoverSnapshot("MySnapshot");
* ```
* @param name - The name of the snapshot.
* @param options - Optional parameters for the request.
*/
recoverSnapshot(name, options = {}) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.recoverSnapshot",
options,
async (updatedOptions) => {
import_logger.logger.info("[recoverSnapshot] Recover a snapshot");
const originalResponse = await this.client.updateSnapshot(
"application/merge-patch+json",
name,
{ status: "ready" },
{
...updatedOptions,
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)(
{ etag: options.etag },
{ onlyIfUnchanged: true, ...options }
),
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
}
);
const response = (0, import_helpers.transformSnapshotResponse)(originalResponse);
(0, import_helpers.assertResponse)(response);
return response;
}
);
}
/**
* Archive a ready snapshot
*
* Example usage:
* ```ts snippet:ArchiveSnapshot
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const result = await client.archiveSnapshot({ name: "MySnapshot" });
* ```
* @param name - The name of the snapshot.
* @param options - Optional parameters for the request.
*/
archiveSnapshot(name, options = {}) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.archiveSnapshot",
options,
async (updatedOptions) => {
import_logger.logger.info("[archiveSnapshot] Archive a snapshot");
const originalResponse = await this.client.updateSnapshot(
"application/merge-patch+json",
name,
{ status: "archived" },
{
...updatedOptions,
...(0, import_helpers.checkAndFormatIfAndIfNoneMatch)(
{ etag: options.etag },
{ onlyIfUnchanged: true, ...options }
),
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
}
);
const response = (0, import_helpers.transformSnapshotResponse)(originalResponse);
(0, import_helpers.assertResponse)(response);
return response;
}
);
}
/**
* List all snapshots from Azure App Configuration service
*
* Example usage:
* ```ts snippet:ListSnapshots
* import { DefaultAzureCredential } from "@azure/identity";
* import { AppConfigurationClient } from "@azure/app-configuration";
*
* // The endpoint for your App Configuration resource
* const endpoint = "https://example.azconfig.io";
* const credential = new DefaultAzureCredential();
* const client = new AppConfigurationClient(endpoint, credential);
*
* const snapshots = await client.listSnapshots();
*
* for await (const snapshot of snapshots) {
* console.log(`Found snapshot: ${snapshot.name}`);
* }
* ```
* @param options - Optional parameters for the request.
*/
listSnapshots(options = {}) {
const pagedResult = {
firstPageLink: void 0,
getPage: async (pageLink) => {
const response = await this.sendSnapShotsRequest(options, pageLink);
const currentResponse = {
...response,
items: response.items != null ? response.items.map((s) => (0, import_helpers.transformSnapshotResponse)(s)) : [],
continuationToken: response.nextLink ? (0, import_helpers.extractAfterTokenFromNextLink)(response.nextLink) : void 0
};
return {
page: currentResponse,
nextPageLink: currentResponse.continuationToken
};
},
toElements: (page) => page.items
};
return (0, import_core_paging.getPagedAsyncIterator)(pagedResult);
}
async sendSnapShotsRequest(options = {}, pageLink) {
return import_tracing.tracingClient.withSpan(
"AppConfigurationClient.listSnapshots",
options,
async (updatedOptions) => {
const rawResponse = await (0, import_operations._getSnapshotsSend)(this._context, {
...updatedOptions,
...(0, import_helpers.formatSnapshotFiltersAndSelect)(options),
after: pageLink,
requestOptions: {
...updatedOptions.requestOptions,
skipUrlEncoding: true
}
});
const parsed = await (0, import_operations._getSnapshotsDeserialize)(rawResponse);
return Object.assign(parsed, { _response: rawResponse });
}
);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AppConfigurationClient
});
//# sourceMappingURL=appConfigurationClient.js.map