[web-pubsub] Migrate `@azure/web-pubsub` to new core pipeline (#16010)

Update to latest core packages and improve pipeline robustness.
This commit is contained in:
Jeff Fisher 2021-06-28 13:02:34 -07:00 коммит произвёл GitHub
Родитель 13772c290e
Коммит 21f28dcfdb
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
44 изменённых файлов: 1125 добавлений и 795 удалений

Просмотреть файл

@ -271,6 +271,12 @@
{
"name": "iot-device-update",
"path": "sdk/deviceupdate/iot-device-update"
},
{
"path": "sdk/web-pubsub/web-pubsub"
},
{
"path": "sdk/web-pubsub/web-pubsub-express"
}
],
"settings": {

Просмотреть файл

@ -129,6 +129,13 @@ class NodeHttpClient implements HttpClient {
request
};
// Responses to HEAD must not have a body.
// If they do return a body, that body must be ignored.
if (request.method === "HEAD") {
resolve(response);
return;
}
responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
const onDownloadProgress = request.onDownloadProgress;
@ -142,7 +149,11 @@ class NodeHttpClient implements HttpClient {
if (request.streamResponseStatusCodes?.has(response.status)) {
response.readableStreamBody = responseStream;
} else {
response.bodyAsText = await streamToText(responseStream);
try {
response.bodyAsText = await streamToText(responseStream);
} catch (e) {
reject(e);
}
}
resolve(response);

Просмотреть файл

@ -17,7 +17,10 @@ export function decompressResponsePolicy(): PipelinePolicy {
return {
name: decompressResponsePolicyName,
async sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {
request.headers.set("Accept-Encoding", "gzip,deflate");
// HEAD requests have no body
if (request.method !== "HEAD") {
request.headers.set("Accept-Encoding", "gzip,deflate");
}
return next(request);
}
};

Просмотреть файл

@ -1,5 +1,9 @@
# Release History
## 1.0.0-beta.2 (UNRELEASED)
- Removed unnecessary dependencies.
## 1.0.0-beta.1 (2021-04-23)
This is the first release of the @azure/web-pubsub-express package.

Просмотреть файл

@ -1,6 +1,6 @@
{
"name": "@azure/web-pubsub-express",
"version": "1.0.0-beta.1",
"version": "1.0.0-beta.2",
"description": "Azure Web PubSub CloudEvents handlers",
"sdk-type": "client",
"main": "dist/index.js",
@ -57,18 +57,12 @@
"homepage": "https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/search/search/",
"sideEffects": false,
"dependencies": {
"@azure/core-auth": "^1.3.0",
"@azure/core-http": "^2.0.0",
"@azure/core-tracing": "1.0.0-preview.12",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0",
"jsonwebtoken": "^8.5.1",
"cloudevents": "^4.0.0"
},
"devDependencies": {
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/identity": "^1.1.0",
"@azure/test-utils-recorder": "^1.0.0",
"@microsoft/api-extractor": "7.7.11",
"@rollup/plugin-commonjs": "11.0.2",

Просмотреть файл

@ -2,8 +2,13 @@
## 1.0.0-beta.3 (Unreleased)
### Breaking Changes
- `hasUser` has been removed from `GroupClient` as that operation is no longer supported by the service.
- Updated to have void returns for most operations. If you were previously using `RestResponse`, you can instead use the `onResponse` callback in the operation options. See README for an example.
## 1.0.0-beta.2 (2021-05-19)
Remove "url" dependency
## 1.0.0-beta.1 (2021-04-23)

Просмотреть файл

@ -118,6 +118,18 @@ const payload = new Uint8Array(10);
await serviceClient.sendToAll(payload.buffer);
```
### Access the raw HTTP response for an operation
```js
const { WebPubSubServiceClient } = require("@azure/web-pubsub");
function onResponse(rawResponse: FullOperationResponse): void {
console.log(rawResponse);
}
const serviceClient = new WebPubSubServiceClient("<ConnectionString>", "<hubName>");
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });
```
## Troubleshooting
### Enable logs

Просмотреть файл

@ -29,7 +29,7 @@
"test:node": "npm run build:test && npm run unit-test:node && npm run integration-test:node",
"test": "npm run build:test && npm run unit-test && npm run integration-test",
"unit-test:browser": "echo \"Browser is not supported.\" && exit 0",
"unit-test:node": "mocha --reporter ../../../common/tools/mocha-multi-reporter.js dist-test/index.node.js",
"unit-test:node": "mocha --exit --reporter ../../../common/tools/mocha-multi-reporter.js dist-test/index.node.js",
"unit-test": "npm run unit-test:node && npm run unit-test:browser",
"docs": "typedoc --excludePrivate --excludeNotExported --excludeExternals --stripInternal --mode file --out ./dist/docs ./src"
},
@ -61,7 +61,8 @@
"sideEffects": false,
"dependencies": {
"@azure/core-auth": "^1.3.0",
"@azure/core-http": "^2.0.0",
"@azure/core-client": "^1.0.0",
"@azure/core-rest-pipeline": "^1.1.0",
"@azure/core-tracing": "1.0.0-preview.12",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0",
@ -78,12 +79,12 @@
"@rollup/plugin-multi-entry": "^3.0.0",
"@rollup/plugin-node-resolve": "^8.0.0",
"@rollup/plugin-replace": "^2.2.0",
"@types/chai": "^4.1.6",
"@types/jsonwebtoken": "~8.5.0",
"@types/mocha": "^7.0.2",
"@types/node": "^8.0.0",
"@types/query-string": "6.2.0",
"@types/sinon": "^9.0.4",
"assert": "^1.4.1",
"chai": "^4.2.0",
"cross-env": "^7.0.2",
"dotenv": "^8.2.0",

Просмотреть файл

@ -5,10 +5,9 @@
```ts
import { AzureKeyCredential } from '@azure/core-auth';
import { HttpRequestBody } from '@azure/core-http';
import { OperationOptions } from '@azure/core-http';
import { PipelineOptions } from '@azure/core-http';
import { RestResponse } from '@azure/core-http';
import { CommonClientOptions } from '@azure/core-client';
import { OperationOptions } from '@azure/core-client';
import { RequestBodyType } from '@azure/core-rest-pipeline';
export { AzureKeyCredential }
@ -40,7 +39,7 @@ export interface GroupAddUserOptions extends OperationOptions {
}
// @public
export interface GroupAdminClientOptions extends PipelineOptions {
export interface GroupAdminClientOptions extends CommonClientOptions {
}
// @public
@ -72,7 +71,7 @@ export interface HasConnectionOptions extends OperationOptions {
}
// @public
export interface HubAdminClientOptions extends PipelineOptions {
export interface HubAdminClientOptions extends CommonClientOptions {
}
// @public
@ -141,18 +140,17 @@ export type Permission = "joinLeaveGroup" | "sendToGroup";
// @public (undocumented)
export interface WebPubSubGroup {
addConnection(connectionId: string, options?: GroupAddConnectionOptions): Promise<RestResponse>;
addUser(username: string, options?: GroupAddUserOptions): Promise<RestResponse>;
addConnection(connectionId: string, options?: GroupAddConnectionOptions): Promise<void>;
addUser(username: string, options?: GroupAddUserOptions): Promise<void>;
readonly apiVersion: string;
readonly endpoint: string;
readonly groupName: string;
hasUser(username: string, options?: GroupHasUserOptions): Promise<boolean>;
readonly hubName: string;
removeConnection(connectionId: string, options?: GroupRemoveConnectionOptions): Promise<RestResponse>;
removeUser(username: string, options?: GroupRemoveUserOptions): Promise<RestResponse>;
sendToAll(message: string, options: GroupSendTextToAllOptions): Promise<RestResponse>;
sendToAll(message: JSONTypes, options?: GroupSendToAllOptions): Promise<RestResponse>;
sendToAll(message: HttpRequestBody, options?: GroupSendToAllOptions): Promise<RestResponse>;
removeConnection(connectionId: string, options?: GroupRemoveConnectionOptions): Promise<void>;
removeUser(username: string, options?: GroupRemoveUserOptions): Promise<void>;
sendToAll(message: string, options: GroupSendTextToAllOptions): Promise<void>;
sendToAll(message: JSONTypes, options?: GroupSendToAllOptions): Promise<void>;
sendToAll(message: RequestBodyType, options?: GroupSendToAllOptions): Promise<void>;
}
// @public
@ -160,27 +158,27 @@ export class WebPubSubServiceClient {
constructor(connectionString: string, hubName: string, options?: HubAdminClientOptions);
constructor(endpoint: string, credential: AzureKeyCredential, hubName: string, options?: HubAdminClientOptions);
readonly apiVersion: string;
closeConnection(connectionId: string, options?: CloseConnectionOptions): Promise<RestResponse>;
closeConnection(connectionId: string, options?: CloseConnectionOptions): Promise<void>;
endpoint: string;
getAuthenticationToken(options?: GetAuthenticationTokenOptions): Promise<GetAuthenticationTokenResponse>;
grantPermission(connectionId: string, permission: Permission, options?: HubGrantPermissionOptions): Promise<RestResponse>;
grantPermission(connectionId: string, permission: Permission, options?: HubGrantPermissionOptions): Promise<void>;
group(groupName: string): WebPubSubGroup;
hasConnection(connectionId: string, options?: HasConnectionOptions): Promise<boolean>;
hasGroup(groupName: string, options?: HubHasGroupOptions): Promise<boolean>;
hasPermission(connectionId: string, permission: Permission, options?: HubHasPermissionOptions): Promise<RestResponse>;
hasPermission(connectionId: string, permission: Permission, options?: HubHasPermissionOptions): Promise<boolean>;
hasUser(username: string, options?: HubHasUserOptions): Promise<boolean>;
readonly hubName: string;
removeUserFromAllGroups(userId: string, options?: CloseConnectionOptions): Promise<RestResponse>;
revokePermission(connectionId: string, permission: Permission, options?: HubRevokePermissionOptions): Promise<RestResponse>;
sendToAll(message: string, options: HubSendTextToAllOptions): Promise<RestResponse>;
sendToAll(message: JSONTypes, options?: HubSendToAllOptions): Promise<RestResponse>;
sendToAll(message: HttpRequestBody, options?: HubSendToAllOptions): Promise<RestResponse>;
sendToConnection(connectionId: string, message: string, options: HubSendTextToConnectionOptions): Promise<RestResponse>;
sendToConnection(connectionId: string, message: JSONTypes, options?: HubSendToConnectionOptions): Promise<RestResponse>;
sendToConnection(connectionId: string, message: HttpRequestBody | JSONTypes, options?: HubSendToConnectionOptions | HubSendTextToConnectionOptions): Promise<RestResponse>;
sendToUser(username: string, message: string, options: HubSendTextToUserOptions): Promise<RestResponse>;
sendToUser(username: string, message: JSONTypes, options?: HubSendToUserOptions): Promise<RestResponse>;
sendToUser(username: string, message: HttpRequestBody, options?: HubSendToUserOptions | HubSendTextToUserOptions): Promise<RestResponse>;
removeUserFromAllGroups(userId: string, options?: CloseConnectionOptions): Promise<void>;
revokePermission(connectionId: string, permission: Permission, options?: HubRevokePermissionOptions): Promise<void>;
sendToAll(message: string, options: HubSendTextToAllOptions): Promise<void>;
sendToAll(message: JSONTypes, options?: HubSendToAllOptions): Promise<void>;
sendToAll(message: RequestBodyType, options?: HubSendToAllOptions): Promise<void>;
sendToConnection(connectionId: string, message: string, options: HubSendTextToConnectionOptions): Promise<void>;
sendToConnection(connectionId: string, message: JSONTypes, options?: HubSendToConnectionOptions): Promise<void>;
sendToConnection(connectionId: string, message: RequestBodyType, options?: HubSendToConnectionOptions | HubSendTextToConnectionOptions): Promise<void>;
sendToUser(username: string, message: string, options: HubSendTextToUserOptions): Promise<void>;
sendToUser(username: string, message: JSONTypes, options?: HubSendToUserOptions): Promise<void>;
sendToUser(username: string, message: RequestBodyType, options?: HubSendToUserOptions | HubSendTextToUserOptions): Promise<void>;
}

Просмотреть файл

@ -28,4 +28,7 @@ async function main() {
chatHub.sendToAll(data.buffer);
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -20,4 +20,7 @@ async function main() {
await chatHub.sendToUser("Tn3XcrAbHI0OE36XvbWwige4ac096c1", "Hi there!");
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -16,7 +16,6 @@ const adminGroup = chatHub.group("admin");
async function main() {
// adding and removing users
await adminGroup.addUser("bterlson");
await adminGroup.hasUser("bterlson"); // true
await adminGroup.removeUser("xirzec");
// adding and removing specific connections
@ -24,4 +23,7 @@ async function main() {
await adminGroup.removeConnection("Tn3XcrAbHI0OE36XvbWwige4ac096c1");
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -51,8 +51,13 @@ Alternatively, run a single sample with the correct environment variables set (s
npx cross-env WPS_CONNECTION_STRING="<wps connection string>" node broadcasting.js
```
[broadcasting]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/web-pubsub/web-pubsub/samples/v1/javascript/broadcasting.js
[directmessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/web-pubsub/web-pubsub/samples/v1/javascript/directMessage.js
[managinggroups]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/web-pubsub/web-pubsub/samples/v1/javascript/managingGroups.js
## Next Steps
Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients.
[broadcasting]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/web-pubsub/web-pubsub/samples/v1/javascript/broadcasting.js
[directmessage]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/web-pubsub/web-pubsub/samples/v1/javascript/directMessage.js
[managinggroups]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/web-pubsub/web-pubsub/samples/v1/javascript/managingGroups.js
[apiref]: https://docs.microsoft.com/javascript/api/@azure/web-pubsub
[freesub]: https://azure.microsoft.com/free/
[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/web-pubsub/web-pubsub/README.md

Просмотреть файл

@ -28,4 +28,7 @@ async function main() {
chatHub.sendToAll(data.buffer);
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -20,4 +20,7 @@ async function main() {
await chatHub.sendToUser("Tn3XcrAbHI0OE36XvbWwige4ac096c1", "Hi there!");
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -16,7 +16,6 @@ const adminGroup = chatHub.group("admin");
async function main() {
// adding and removing users
await adminGroup.addUser("bterlson");
await adminGroup.hasUser("bterlson"); // true
await adminGroup.removeUser("xirzec");
// adding and removing specific connections
@ -24,4 +23,7 @@ async function main() {
await adminGroup.removeConnection("Tn3XcrAbHI0OE36XvbWwige4ac096c1");
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -3,7 +3,7 @@
"private": true,
"version": "1.0.0",
"description": "Azure Web PubSub client library samples for JavaScript",
"engine": {
"engines": {
"node": ">=12.0.0"
},
"repository": {

Просмотреть файл

@ -54,7 +54,7 @@ npm run build
4. Run whichever samples you like (note that some samples may require additional setup, see the table above):
```bash
node dist/broadcasting.ts
node dist/broadcasting.js
```
Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform):
@ -63,9 +63,14 @@ Alternatively, run a single sample with the correct environment variables set (s
npx cross-env WPS_CONNECTION_STRING="<wps connection string>" node dist/broadcasting.js
```
[broadcasting]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/web-pubsub/web-pubsub/samples/v1/typescript/src/broadcasting.ts
[directmessage]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/web-pubsub/web-pubsub/samples/v1/typescript/src/directMessage.ts
[managinggroups]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/web-pubsub/web-pubsub/samples/v1/typescript/src/managingGroups.ts
## Next Steps
Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients.
[broadcasting]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/web-pubsub/web-pubsub/samples/v1/typescript/src/broadcasting.ts
[directmessage]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/web-pubsub/web-pubsub/samples/v1/typescript/src/directMessage.ts
[managinggroups]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/web-pubsub/web-pubsub/samples/v1/typescript/src/managingGroups.ts
[apiref]: https://docs.microsoft.com/javascript/api/@azure/web-pubsub
[freesub]: https://azure.microsoft.com/free/
[package]: https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/web-pubsub/web-pubsub/README.md
[typescript]: https://www.typescriptlang.org/docs/home.html

Просмотреть файл

@ -3,7 +3,7 @@
"private": true,
"version": "1.0.0",
"description": "Azure Web PubSub client library samples for TypeScript",
"engine": {
"engines": {
"node": ">=12.0.0"
},
"scripts": {

Просмотреть файл

@ -28,4 +28,7 @@ async function main() {
chatHub.sendToAll(data.buffer);
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -20,4 +20,7 @@ async function main() {
await chatHub.sendToUser("Tn3XcrAbHI0OE36XvbWwige4ac096c1", "Hi there!");
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -16,7 +16,6 @@ const adminGroup = chatHub.group("admin");
async function main() {
// adding and removing users
await adminGroup.addUser("bterlson");
await adminGroup.hasUser("bterlson"); // true
await adminGroup.removeUser("xirzec");
// adding and removing specific connections
@ -24,4 +23,7 @@ async function main() {
await adminGroup.removeConnection("Tn3XcrAbHI0OE36XvbWwige4ac096c1");
}
main();
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});

Просмотреть файл

@ -11,5 +11,7 @@
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**.ts"]
"include": [
"src/**.ts"
]
}

Просмотреть файл

@ -1,22 +0,0 @@
import { HealthApi, WebPubSub } from "./operations";
import { AzureWebPubSubServiceRestAPIContext } from "./azureWebPubSubServiceRestAPIContext";
import { AzureWebPubSubServiceRestAPIOptionalParams } from "./models";
export class AzureWebPubSubServiceRestAPI extends AzureWebPubSubServiceRestAPIContext {
/**
* Initializes a new instance of the AzureWebPubSubServiceRestAPI class.
* @param $host server parameter
* @param options The parameter options
*/
constructor(
$host: string,
options?: AzureWebPubSubServiceRestAPIOptionalParams
) {
super($host, options);
this.healthApi = new HealthApi(this);
this.webPubSub = new WebPubSub(this);
}
healthApi: HealthApi;
webPubSub: WebPubSub;
}

Просмотреть файл

@ -1,49 +0,0 @@
import * as coreHttp from "@azure/core-http";
import { AzureWebPubSubServiceRestAPIOptionalParams } from "./models";
const packageName = "WebPubSub";
const packageVersion = "1.0.0";
/**
* @hidden
*/
export class AzureWebPubSubServiceRestAPIContext extends coreHttp.ServiceClient {
$host: string;
apiVersion?: string;
/**
* Initializes a new instance of the AzureWebPubSubServiceRestAPIContext class.
* @param $host server parameter
* @param options The parameter options
*/
constructor(
$host: string,
options?: AzureWebPubSubServiceRestAPIOptionalParams
) {
if ($host === undefined) {
throw new Error("'$host' cannot be null");
}
// Initializing default values for options
if (!options) {
options = {};
}
if (!options.userAgent) {
const defaultUserAgent = coreHttp.getDefaultUserAgentValue();
options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`;
}
super(undefined, options);
this.requestContentType = "application/json; charset=utf-8";
this.baseUri = options.endpoint || "{$host}";
// Parameter assignments
this.$host = $host;
// Assigning values to Constant parameters
this.apiVersion = options.apiVersion || "2020-10-01";
}
}

Просмотреть файл

@ -0,0 +1,29 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import { HealthApiImpl, WebPubSubImpl } from "./operations";
import { HealthApi, WebPubSub } from "./operationsInterfaces";
import { GeneratedClientContext } from "./generatedClientContext";
import { GeneratedClientOptionalParams } from "./models";
/** @internal */
export class GeneratedClient extends GeneratedClientContext {
/**
* Initializes a new instance of the GeneratedClient class.
* @param $host server parameter
* @param options The parameter options
*/
constructor($host: string, options?: GeneratedClientOptionalParams) {
super($host, options);
this.healthApi = new HealthApiImpl(this);
this.webPubSub = new WebPubSubImpl(this);
}
healthApi: HealthApi;
webPubSub: WebPubSub;
}

Просмотреть файл

@ -0,0 +1,56 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreClient from "@azure/core-client";
import { GeneratedClientOptionalParams } from "./models";
/** @internal */
export class GeneratedClientContext extends coreClient.ServiceClient {
$host: string;
apiVersion?: string;
/**
* Initializes a new instance of the GeneratedClientContext class.
* @param $host server parameter
* @param options The parameter options
*/
constructor($host: string, options?: GeneratedClientOptionalParams) {
if ($host === undefined) {
throw new Error("'$host' cannot be null");
}
// Initializing default values for options
if (!options) {
options = {};
}
const defaults: GeneratedClientOptionalParams = {
requestContentType: "application/json; charset=utf-8"
};
const packageDetails = `azsdk-js-web-pubsub/1.0.0-beta.3`;
const userAgentPrefix =
options.userAgentOptions && options.userAgentOptions.userAgentPrefix
? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
: `${packageDetails}`;
const optionsWithDefaults = {
...defaults,
...options,
userAgentOptions: {
userAgentPrefix
},
baseUri: options.endpoint || "{$host}"
};
super(optionsWithDefaults);
// Parameter assignments
this.$host = $host;
// Assigning values to Constant parameters
this.apiVersion = options.apiVersion || "2021-05-01-preview";
}
}

Просмотреть файл

@ -1,3 +1,12 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
export * from "./models";
export { AzureWebPubSubServiceRestAPI } from "./azureWebPubSubServiceRestAPI";
export { AzureWebPubSubServiceRestAPIContext } from "./azureWebPubSubServiceRestAPIContext";
export { GeneratedClient } from "./generatedClient";
export { GeneratedClientContext } from "./generatedClientContext";
export * from "./operationsInterfaces";

Просмотреть файл

@ -1,114 +1,142 @@
import * as coreHttp from "@azure/core-http";
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
/** Known values of {@link Enum0} that the service accepts. */
export const enum KnownEnum0 {
import * as coreClient from "@azure/core-client";
/** Known values of {@link WebPubSubPermission} that the service accepts. */
export const enum KnownWebPubSubPermission {
SendToGroup = "sendToGroup",
JoinLeaveGroup = "joinLeaveGroup"
}
/**
* Defines values for Enum0. \
* {@link KnownEnum0} can be used interchangeably with Enum0,
* Defines values for WebPubSubPermission. \
* {@link KnownWebPubSubPermission} can be used interchangeably with WebPubSubPermission,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* ### Known values supported by the service
* **sendToGroup** \
* **joinLeaveGroup**
*/
export type Enum0 = string;
/** Known values of {@link Enum1} that the service accepts. */
export const enum KnownEnum1 {
SendToGroup = "sendToGroup",
JoinLeaveGroup = "joinLeaveGroup"
}
/**
* Defines values for Enum1. \
* {@link KnownEnum1} can be used interchangeably with Enum1,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **sendToGroup** \
* **joinLeaveGroup**
*/
export type Enum1 = string;
/** Known values of {@link Enum2} that the service accepts. */
export const enum KnownEnum2 {
SendToGroup = "sendToGroup",
JoinLeaveGroup = "joinLeaveGroup"
}
/**
* Defines values for Enum2. \
* {@link KnownEnum2} can be used interchangeably with Enum2,
* this enum contains the known values that the service supports.
* ### Know values supported by the service
* **sendToGroup** \
* **joinLeaveGroup**
*/
export type Enum2 = string;
export type WebPubSubPermission = string;
/** Defines values for ContentType. */
export type ContentType = "application/json" | "application/octet-stream";
/** Optional parameters. */
export interface HealthApiGetServiceStatusOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubSendToAll$binaryOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** Excluded connection Ids. */
excluded?: string[];
}
/** Optional parameters. */
export interface WebPubSubSendToAll$textOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** Excluded connection Ids. */
excluded?: string[];
}
/** Optional parameters. */
export interface WebPubSubConnectionExistsOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubCloseClientConnectionOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** The reason closing the client connection. */
reason?: string;
}
/** Optional parameters. */
export interface WebPubSubSendToConnection$binaryOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubSendToConnection$textOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubGroupExistsOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubSendToGroup$binaryOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** Excluded connection Ids */
excluded?: string[];
}
/** Optional parameters. */
export interface WebPubSubSendToGroup$textOptionalParams
extends coreHttp.OperationOptions {
extends coreClient.OperationOptions {
/** Excluded connection Ids */
excluded?: string[];
}
/** Optional parameters. */
export interface WebPubSubAddConnectionToGroupOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubRemoveConnectionFromGroupOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubUserExistsOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubSendToUser$binaryOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubSendToUser$textOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubAddUserToGroupOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubRemoveUserFromGroupOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubRemoveUserFromAllGroupsOptionalParams
extends coreClient.OperationOptions {}
/** Optional parameters. */
export interface WebPubSubGrantPermissionOptionalParams
extends coreHttp.OperationOptions {
/** Optional. If not set, grant the permission to all the targets. If set, grant the permission to the specific target. The meaning of the target depends on the specific permission. */
extends coreClient.OperationOptions {
/** The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. */
targetName?: string;
}
/** Optional parameters. */
export interface WebPubSubRevokePermissionOptionalParams
extends coreHttp.OperationOptions {
/** Optional. If not set, revoke the permission for all targets. If set, revoke the permission for the specific target. The meaning of the target depends on the specific permission. */
extends coreClient.OperationOptions {
/** The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. */
targetName?: string;
}
/** Optional parameters. */
export interface WebPubSubCheckPermissionOptionalParams
extends coreHttp.OperationOptions {
/** Optional. If not set, get the permission for all targets. If set, get the permission for the specific target. The meaning of the target depends on the specific permission. */
extends coreClient.OperationOptions {
/** The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. */
targetName?: string;
}
/** Optional parameters. */
export interface AzureWebPubSubServiceRestAPIOptionalParams
extends coreHttp.ServiceClientOptions {
export interface GeneratedClientOptionalParams
extends coreClient.ServiceClientOptions {
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */

Просмотреть файл

@ -1,9 +1,16 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import {
OperationURLParameter,
OperationQueryParameter,
OperationParameter,
QueryCollectionFormat
} from "@azure/core-http";
OperationParameter
} from "@azure/core-client";
export const $host: OperationURLParameter = {
parameterPath: "$host",
@ -20,7 +27,7 @@ export const $host: OperationURLParameter = {
export const apiVersion: OperationQueryParameter = {
parameterPath: "apiVersion",
mapper: {
defaultValue: "2020-10-01",
defaultValue: "2021-05-01-preview",
isConstant: true,
serializedName: "api-version",
type: {
@ -78,6 +85,9 @@ export const message1: OperationParameter = {
export const hub: OperationURLParameter = {
parameterPath: "hub",
mapper: {
constraints: {
Pattern: new RegExp("^[A-Za-z][A-Za-z0-9_`,.[\\]]{0,127}$")
},
serializedName: "hub",
required: true,
type: {
@ -99,12 +109,15 @@ export const excluded: OperationQueryParameter = {
}
}
},
collectionFormat: QueryCollectionFormat.Multi
collectionFormat: "Multi"
};
export const connectionId: OperationURLParameter = {
parameterPath: "connectionId",
mapper: {
constraints: {
MinLength: 1
},
serializedName: "connectionId",
required: true,
type: {
@ -126,6 +139,10 @@ export const reason: OperationQueryParameter = {
export const group: OperationURLParameter = {
parameterPath: "group",
mapper: {
constraints: {
MaxLength: 1024,
MinLength: 1
},
serializedName: "group",
required: true,
type: {
@ -137,6 +154,9 @@ export const group: OperationURLParameter = {
export const userId: OperationURLParameter = {
parameterPath: "userId",
mapper: {
constraints: {
MinLength: 1
},
serializedName: "userId",
required: true,
type: {
@ -165,25 +185,3 @@ export const targetName: OperationQueryParameter = {
}
}
};
export const permission1: OperationURLParameter = {
parameterPath: "permission",
mapper: {
serializedName: "permission",
required: true,
type: {
name: "String"
}
}
};
export const permission2: OperationURLParameter = {
parameterPath: "permission",
mapper: {
serializedName: "permission",
required: true,
type: {
name: "String"
}
}
};

Просмотреть файл

@ -1,16 +1,26 @@
import * as coreHttp from "@azure/core-http";
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import { HealthApi } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Parameters from "../models/parameters";
import { AzureWebPubSubServiceRestAPIContext } from "../azureWebPubSubServiceRestAPIContext";
import { GeneratedClientContext } from "../generatedClientContext";
import { HealthApiGetServiceStatusOptionalParams } from "../models";
/** Class representing a HealthApi. */
export class HealthApi {
private readonly client: AzureWebPubSubServiceRestAPIContext;
export class HealthApiImpl implements HealthApi {
private readonly client: GeneratedClientContext;
/**
* Initialize a new instance of the class HealthApi class.
* @param client Reference to the service client
*/
constructor(client: AzureWebPubSubServiceRestAPIContext) {
constructor(client: GeneratedClientContext) {
this.client = client;
}
@ -18,22 +28,19 @@ export class HealthApi {
* Get service health status.
* @param options The options parameters.
*/
getHealthStatus(
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
getServiceStatus(
options?: HealthApiGetServiceStatusOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
getHealthStatusOperationSpec
) as Promise<coreHttp.RestResponse>;
{ options },
getServiceStatusOperationSpec
);
}
}
// Operation Specifications
const serializer = new coreHttp.Serializer({}, /* isXml */ false);
const serializer = coreClient.createSerializer({}, /* isXml */ false);
const getHealthStatusOperationSpec: coreHttp.OperationSpec = {
const getServiceStatusOperationSpec: coreClient.OperationSpec = {
path: "/api/health",
httpMethod: "HEAD",
responses: { 200: {}, default: {} },

Просмотреть файл

@ -1,2 +1,10 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
export * from "./healthApi";
export * from "./webPubSub";

Просмотреть файл

@ -1,30 +1,50 @@
import * as coreHttp from "@azure/core-http";
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import { WebPubSub } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as coreRestPipeline from "@azure/core-rest-pipeline";
import * as Parameters from "../models/parameters";
import { AzureWebPubSubServiceRestAPIContext } from "../azureWebPubSubServiceRestAPIContext";
import { GeneratedClientContext } from "../generatedClientContext";
import {
ContentType,
WebPubSubSendToAll$binaryOptionalParams,
WebPubSubSendToAll$textOptionalParams,
WebPubSubConnectionExistsOptionalParams,
WebPubSubCloseClientConnectionOptionalParams,
WebPubSubSendToConnection$binaryOptionalParams,
WebPubSubSendToConnection$textOptionalParams,
WebPubSubGroupExistsOptionalParams,
WebPubSubSendToGroup$binaryOptionalParams,
WebPubSubSendToGroup$textOptionalParams,
Enum0,
WebPubSubAddConnectionToGroupOptionalParams,
WebPubSubRemoveConnectionFromGroupOptionalParams,
WebPubSubUserExistsOptionalParams,
WebPubSubSendToUser$binaryOptionalParams,
WebPubSubSendToUser$textOptionalParams,
WebPubSubAddUserToGroupOptionalParams,
WebPubSubRemoveUserFromGroupOptionalParams,
WebPubSubRemoveUserFromAllGroupsOptionalParams,
WebPubSubPermission,
WebPubSubGrantPermissionOptionalParams,
Enum1,
WebPubSubRevokePermissionOptionalParams,
Enum2,
WebPubSubCheckPermissionOptionalParams
} from "../models";
/** Class representing a WebPubSub. */
export class WebPubSub {
private readonly client: AzureWebPubSubServiceRestAPIContext;
export class WebPubSubImpl implements WebPubSub {
private readonly client: GeneratedClientContext;
/**
* Initialize a new instance of the class WebPubSub class.
* @param client Reference to the service client
*/
constructor(client: AzureWebPubSubServiceRestAPIContext) {
constructor(client: GeneratedClientContext) {
this.client = client;
}
@ -39,9 +59,9 @@ export class WebPubSub {
sendToAll(
hub: string,
contentType: ContentType,
message: coreHttp.HttpRequestBody,
message: coreRestPipeline.RequestBodyType,
options?: WebPubSubSendToAll$binaryOptionalParams
): Promise<coreHttp.RestResponse>;
): Promise<void>;
/**
* Broadcast content inside request body to all the connected client connections.
* @param hub Target hub name, which should start with alphabetic characters and only contain
@ -55,7 +75,7 @@ export class WebPubSub {
contentType: "text/plain",
message: string,
options?: WebPubSubSendToAll$textOptionalParams
): Promise<coreHttp.RestResponse>;
): Promise<void>;
/**
* Broadcast content inside request body to all the connected client connections.
* @param args Includes all the parameters for this operation.
@ -65,13 +85,13 @@ export class WebPubSub {
| [
string,
ContentType,
coreHttp.HttpRequestBody,
coreRestPipeline.RequestBodyType,
WebPubSubSendToAll$binaryOptionalParams?
]
| [string, "text/plain", string, WebPubSubSendToAll$textOptionalParams?]
): Promise<coreHttp.RestResponse> {
let operationSpec: coreHttp.OperationSpec;
let operationArguments: coreHttp.OperationArguments;
): Promise<void> {
let operationSpec: coreClient.OperationSpec;
let operationArguments: coreClient.OperationArguments;
let options;
if (
args[1] === "application/json" ||
@ -99,13 +119,8 @@ export class WebPubSub {
`"contentType" must be a valid value but instead was "${args[1]}".`
);
}
operationArguments.options = coreHttp.operationOptionsToRequestOptionsBase(
options || {}
);
return this.client.sendOperationRequest(
operationArguments,
operationSpec
) as Promise<coreHttp.RestResponse>;
operationArguments.options = options || {};
return this.client.sendOperationRequest(operationArguments, operationSpec);
}
/**
@ -118,17 +133,12 @@ export class WebPubSub {
connectionExists(
hub: string,
connectionId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
connectionId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
options?: WebPubSubConnectionExistsOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, connectionId, options },
connectionExistsOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -142,16 +152,11 @@ export class WebPubSub {
hub: string,
connectionId: string,
options?: WebPubSubCloseClientConnectionOptionalParams
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
connectionId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, connectionId, options },
closeClientConnectionOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -167,9 +172,9 @@ export class WebPubSub {
hub: string,
connectionId: string,
contentType: ContentType,
message: coreHttp.HttpRequestBody,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse>;
message: coreRestPipeline.RequestBodyType,
options?: WebPubSubSendToConnection$binaryOptionalParams
): Promise<void>;
/**
* Send content inside request body to the specific connection.
* @param hub Target hub name, which should start with alphabetic characters and only contain
@ -184,8 +189,8 @@ export class WebPubSub {
connectionId: string,
contentType: "text/plain",
message: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse>;
options?: WebPubSubSendToConnection$textOptionalParams
): Promise<void>;
/**
* Send content inside request body to the specific connection.
* @param args Includes all the parameters for this operation.
@ -196,13 +201,19 @@ export class WebPubSub {
string,
string,
ContentType,
coreHttp.HttpRequestBody,
coreHttp.OperationOptions?
coreRestPipeline.RequestBodyType,
WebPubSubSendToConnection$binaryOptionalParams?
]
| [string, string, "text/plain", string, coreHttp.OperationOptions?]
): Promise<coreHttp.RestResponse> {
let operationSpec: coreHttp.OperationSpec;
let operationArguments: coreHttp.OperationArguments;
| [
string,
string,
"text/plain",
string,
WebPubSubSendToConnection$textOptionalParams?
]
): Promise<void> {
let operationSpec: coreClient.OperationSpec;
let operationArguments: coreClient.OperationArguments;
let options;
if (
args[2] === "application/json" ||
@ -232,13 +243,8 @@ export class WebPubSub {
`"contentType" must be a valid value but instead was "${args[2]}".`
);
}
operationArguments.options = coreHttp.operationOptionsToRequestOptionsBase(
options || {}
);
return this.client.sendOperationRequest(
operationArguments,
operationSpec
) as Promise<coreHttp.RestResponse>;
operationArguments.options = options || {};
return this.client.sendOperationRequest(operationArguments, operationSpec);
}
/**
@ -251,17 +257,12 @@ export class WebPubSub {
groupExists(
hub: string,
group: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
group,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
options?: WebPubSubGroupExistsOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, group, options },
groupExistsOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -277,9 +278,9 @@ export class WebPubSub {
hub: string,
group: string,
contentType: ContentType,
message: coreHttp.HttpRequestBody,
message: coreRestPipeline.RequestBodyType,
options?: WebPubSubSendToGroup$binaryOptionalParams
): Promise<coreHttp.RestResponse>;
): Promise<void>;
/**
* Send content inside request body to a group of connections.
* @param hub Target hub name, which should start with alphabetic characters and only contain
@ -295,7 +296,7 @@ export class WebPubSub {
contentType: "text/plain",
message: string,
options?: WebPubSubSendToGroup$textOptionalParams
): Promise<coreHttp.RestResponse>;
): Promise<void>;
/**
* Send content inside request body to a group of connections.
* @param args Includes all the parameters for this operation.
@ -306,7 +307,7 @@ export class WebPubSub {
string,
string,
ContentType,
coreHttp.HttpRequestBody,
coreRestPipeline.RequestBodyType,
WebPubSubSendToGroup$binaryOptionalParams?
]
| [
@ -316,9 +317,9 @@ export class WebPubSub {
string,
WebPubSubSendToGroup$textOptionalParams?
]
): Promise<coreHttp.RestResponse> {
let operationSpec: coreHttp.OperationSpec;
let operationArguments: coreHttp.OperationArguments;
): Promise<void> {
let operationSpec: coreClient.OperationSpec;
let operationArguments: coreClient.OperationArguments;
let options;
if (
args[2] === "application/json" ||
@ -348,13 +349,8 @@ export class WebPubSub {
`"contentType" must be a valid value but instead was "${args[2]}".`
);
}
operationArguments.options = coreHttp.operationOptionsToRequestOptionsBase(
options || {}
);
return this.client.sendOperationRequest(
operationArguments,
operationSpec
) as Promise<coreHttp.RestResponse>;
operationArguments.options = options || {};
return this.client.sendOperationRequest(operationArguments, operationSpec);
}
/**
@ -369,18 +365,12 @@ export class WebPubSub {
hub: string,
group: string,
connectionId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
group,
connectionId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
options?: WebPubSubAddConnectionToGroupOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, group, connectionId, options },
addConnectionToGroupOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -395,18 +385,12 @@ export class WebPubSub {
hub: string,
group: string,
connectionId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
group,
connectionId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
options?: WebPubSubRemoveConnectionFromGroupOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, group, connectionId, options },
removeConnectionFromGroupOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -419,17 +403,12 @@ export class WebPubSub {
userExists(
hub: string,
userId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
userId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
options?: WebPubSubUserExistsOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, userId, options },
userExistsOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -445,9 +424,9 @@ export class WebPubSub {
hub: string,
userId: string,
contentType: ContentType,
message: coreHttp.HttpRequestBody,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse>;
message: coreRestPipeline.RequestBodyType,
options?: WebPubSubSendToUser$binaryOptionalParams
): Promise<void>;
/**
* Send content inside request body to the specific user.
* @param hub Target hub name, which should start with alphabetic characters and only contain
@ -462,8 +441,8 @@ export class WebPubSub {
userId: string,
contentType: "text/plain",
message: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse>;
options?: WebPubSubSendToUser$textOptionalParams
): Promise<void>;
/**
* Send content inside request body to the specific user.
* @param args Includes all the parameters for this operation.
@ -474,13 +453,19 @@ export class WebPubSub {
string,
string,
ContentType,
coreHttp.HttpRequestBody,
coreHttp.OperationOptions?
coreRestPipeline.RequestBodyType,
WebPubSubSendToUser$binaryOptionalParams?
]
| [string, string, "text/plain", string, coreHttp.OperationOptions?]
): Promise<coreHttp.RestResponse> {
let operationSpec: coreHttp.OperationSpec;
let operationArguments: coreHttp.OperationArguments;
| [
string,
string,
"text/plain",
string,
WebPubSubSendToUser$textOptionalParams?
]
): Promise<void> {
let operationSpec: coreClient.OperationSpec;
let operationArguments: coreClient.OperationArguments;
let options;
if (
args[2] === "application/json" ||
@ -510,39 +495,8 @@ export class WebPubSub {
`"contentType" must be a valid value but instead was "${args[2]}".`
);
}
operationArguments.options = coreHttp.operationOptionsToRequestOptionsBase(
options || {}
);
return this.client.sendOperationRequest(
operationArguments,
operationSpec
) as Promise<coreHttp.RestResponse>;
}
/**
* Check whether a user exists in the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param userId Target user Id.
* @param options The options parameters.
*/
userExistsInGroup(
hub: string,
group: string,
userId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
group,
userId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
userExistsInGroupOperationSpec
) as Promise<coreHttp.RestResponse>;
operationArguments.options = options || {};
return this.client.sendOperationRequest(operationArguments, operationSpec);
}
/**
@ -557,18 +511,12 @@ export class WebPubSub {
hub: string,
group: string,
userId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
group,
userId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
options?: WebPubSubAddUserToGroupOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, group, userId, options },
addUserToGroupOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -583,18 +531,12 @@ export class WebPubSub {
hub: string,
group: string,
userId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
group,
userId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
options?: WebPubSubRemoveUserFromGroupOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, group, userId, options },
removeUserFromGroupOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -607,17 +549,12 @@ export class WebPubSub {
removeUserFromAllGroups(
hub: string,
userId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
userId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
options?: WebPubSubRemoveUserFromAllGroupsOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, userId, options },
removeUserFromAllGroupsOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -630,20 +567,14 @@ export class WebPubSub {
*/
grantPermission(
hub: string,
permission: Enum0,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubGrantPermissionOptionalParams
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
permission,
connectionId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, permission, connectionId, options },
grantPermissionOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -656,20 +587,14 @@ export class WebPubSub {
*/
revokePermission(
hub: string,
permission: Enum1,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubRevokePermissionOptionalParams
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
permission,
connectionId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, permission, connectionId, options },
revokePermissionOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
/**
@ -682,26 +607,20 @@ export class WebPubSub {
*/
checkPermission(
hub: string,
permission: Enum2,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubCheckPermissionOptionalParams
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
hub,
permission,
connectionId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
): Promise<void> {
return this.client.sendOperationRequest(
operationArguments,
{ hub, permission, connectionId, options },
checkPermissionOperationSpec
) as Promise<coreHttp.RestResponse>;
);
}
}
// Operation Specifications
const serializer = new coreHttp.Serializer({}, /* isXml */ false);
const serializer = coreClient.createSerializer({}, /* isXml */ false);
const sendToAll$binaryOperationSpec: coreHttp.OperationSpec = {
const sendToAll$binaryOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/:send",
httpMethod: "POST",
responses: { 202: {}, default: {} },
@ -712,7 +631,7 @@ const sendToAll$binaryOperationSpec: coreHttp.OperationSpec = {
mediaType: "binary",
serializer
};
const sendToAll$textOperationSpec: coreHttp.OperationSpec = {
const sendToAll$textOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/:send",
httpMethod: "POST",
responses: { 202: {}, default: {} },
@ -723,7 +642,7 @@ const sendToAll$textOperationSpec: coreHttp.OperationSpec = {
mediaType: "text",
serializer
};
const connectionExistsOperationSpec: coreHttp.OperationSpec = {
const connectionExistsOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/connections/{connectionId}",
httpMethod: "HEAD",
responses: { 200: {}, 404: {}, default: {} },
@ -731,7 +650,7 @@ const connectionExistsOperationSpec: coreHttp.OperationSpec = {
urlParameters: [Parameters.$host, Parameters.hub, Parameters.connectionId],
serializer
};
const closeClientConnectionOperationSpec: coreHttp.OperationSpec = {
const closeClientConnectionOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/connections/{connectionId}",
httpMethod: "DELETE",
responses: { 200: {}, default: {} },
@ -739,7 +658,7 @@ const closeClientConnectionOperationSpec: coreHttp.OperationSpec = {
urlParameters: [Parameters.$host, Parameters.hub, Parameters.connectionId],
serializer
};
const sendToConnection$binaryOperationSpec: coreHttp.OperationSpec = {
const sendToConnection$binaryOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/connections/{connectionId}/:send",
httpMethod: "POST",
responses: { 202: {}, default: {} },
@ -750,7 +669,7 @@ const sendToConnection$binaryOperationSpec: coreHttp.OperationSpec = {
mediaType: "binary",
serializer
};
const sendToConnection$textOperationSpec: coreHttp.OperationSpec = {
const sendToConnection$textOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/connections/{connectionId}/:send",
httpMethod: "POST",
responses: { 202: {}, default: {} },
@ -761,7 +680,7 @@ const sendToConnection$textOperationSpec: coreHttp.OperationSpec = {
mediaType: "text",
serializer
};
const groupExistsOperationSpec: coreHttp.OperationSpec = {
const groupExistsOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/groups/{group}",
httpMethod: "HEAD",
responses: { 200: {}, 404: {}, default: {} },
@ -769,7 +688,7 @@ const groupExistsOperationSpec: coreHttp.OperationSpec = {
urlParameters: [Parameters.$host, Parameters.hub, Parameters.group],
serializer
};
const sendToGroup$binaryOperationSpec: coreHttp.OperationSpec = {
const sendToGroup$binaryOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/groups/{group}/:send",
httpMethod: "POST",
responses: { 202: {}, default: {} },
@ -780,7 +699,7 @@ const sendToGroup$binaryOperationSpec: coreHttp.OperationSpec = {
mediaType: "binary",
serializer
};
const sendToGroup$textOperationSpec: coreHttp.OperationSpec = {
const sendToGroup$textOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/groups/{group}/:send",
httpMethod: "POST",
responses: { 202: {}, default: {} },
@ -791,7 +710,7 @@ const sendToGroup$textOperationSpec: coreHttp.OperationSpec = {
mediaType: "text",
serializer
};
const addConnectionToGroupOperationSpec: coreHttp.OperationSpec = {
const addConnectionToGroupOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/groups/{group}/connections/{connectionId}",
httpMethod: "PUT",
responses: { 200: {}, 404: {}, default: {} },
@ -804,10 +723,10 @@ const addConnectionToGroupOperationSpec: coreHttp.OperationSpec = {
],
serializer
};
const removeConnectionFromGroupOperationSpec: coreHttp.OperationSpec = {
const removeConnectionFromGroupOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/groups/{group}/connections/{connectionId}",
httpMethod: "DELETE",
responses: { 200: {}, 404: {}, default: {} },
responses: { 200: {}, default: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
@ -817,7 +736,7 @@ const removeConnectionFromGroupOperationSpec: coreHttp.OperationSpec = {
],
serializer
};
const userExistsOperationSpec: coreHttp.OperationSpec = {
const userExistsOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/users/{userId}",
httpMethod: "HEAD",
responses: { 200: {}, 404: {}, default: {} },
@ -825,7 +744,7 @@ const userExistsOperationSpec: coreHttp.OperationSpec = {
urlParameters: [Parameters.$host, Parameters.hub, Parameters.userId],
serializer
};
const sendToUser$binaryOperationSpec: coreHttp.OperationSpec = {
const sendToUser$binaryOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/users/{userId}/:send",
httpMethod: "POST",
responses: { 202: {}, default: {} },
@ -836,7 +755,7 @@ const sendToUser$binaryOperationSpec: coreHttp.OperationSpec = {
mediaType: "binary",
serializer
};
const sendToUser$textOperationSpec: coreHttp.OperationSpec = {
const sendToUser$textOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/users/{userId}/:send",
httpMethod: "POST",
responses: { 202: {}, default: {} },
@ -847,9 +766,9 @@ const sendToUser$textOperationSpec: coreHttp.OperationSpec = {
mediaType: "text",
serializer
};
const userExistsInGroupOperationSpec: coreHttp.OperationSpec = {
const addUserToGroupOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/users/{userId}/groups/{group}",
httpMethod: "HEAD",
httpMethod: "PUT",
responses: { 200: {}, 404: {}, default: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
@ -860,20 +779,7 @@ const userExistsInGroupOperationSpec: coreHttp.OperationSpec = {
],
serializer
};
const addUserToGroupOperationSpec: coreHttp.OperationSpec = {
path: "/api/hubs/{hub}/users/{userId}/groups/{group}",
httpMethod: "PUT",
responses: { 200: {}, default: {} },
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.hub,
Parameters.group,
Parameters.userId
],
serializer
};
const removeUserFromGroupOperationSpec: coreHttp.OperationSpec = {
const removeUserFromGroupOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/users/{userId}/groups/{group}",
httpMethod: "DELETE",
responses: { 200: {}, default: {} },
@ -886,7 +792,7 @@ const removeUserFromGroupOperationSpec: coreHttp.OperationSpec = {
],
serializer
};
const removeUserFromAllGroupsOperationSpec: coreHttp.OperationSpec = {
const removeUserFromAllGroupsOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/users/{userId}/groups",
httpMethod: "DELETE",
responses: { 200: {}, default: {} },
@ -894,7 +800,7 @@ const removeUserFromAllGroupsOperationSpec: coreHttp.OperationSpec = {
urlParameters: [Parameters.$host, Parameters.hub, Parameters.userId],
serializer
};
const grantPermissionOperationSpec: coreHttp.OperationSpec = {
const grantPermissionOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}",
httpMethod: "PUT",
responses: { 200: {}, default: {} },
@ -907,7 +813,7 @@ const grantPermissionOperationSpec: coreHttp.OperationSpec = {
],
serializer
};
const revokePermissionOperationSpec: coreHttp.OperationSpec = {
const revokePermissionOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}",
httpMethod: "DELETE",
responses: { 200: {}, default: {} },
@ -916,11 +822,11 @@ const revokePermissionOperationSpec: coreHttp.OperationSpec = {
Parameters.$host,
Parameters.hub,
Parameters.connectionId,
Parameters.permission1
Parameters.permission
],
serializer
};
const checkPermissionOperationSpec: coreHttp.OperationSpec = {
const checkPermissionOperationSpec: coreClient.OperationSpec = {
path: "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}",
httpMethod: "HEAD",
responses: { 200: {}, 404: {}, default: {} },
@ -929,7 +835,7 @@ const checkPermissionOperationSpec: coreHttp.OperationSpec = {
Parameters.$host,
Parameters.hub,
Parameters.connectionId,
Parameters.permission2
Parameters.permission
],
serializer
};

Просмотреть файл

@ -0,0 +1,20 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import { HealthApiGetServiceStatusOptionalParams } from "../models";
/** Interface representing a HealthApi. */
export interface HealthApi {
/**
* Get service health status.
* @param options The options parameters.
*/
getServiceStatus(
options?: HealthApiGetServiceStatusOptionalParams
): Promise<void>;
}

Просмотреть файл

@ -0,0 +1,10 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
export * from "./healthApi";
export * from "./webPubSub";

Просмотреть файл

@ -0,0 +1,272 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import * as coreRestPipeline from "@azure/core-rest-pipeline";
import {
ContentType,
WebPubSubSendToAll$binaryOptionalParams,
WebPubSubSendToAll$textOptionalParams,
WebPubSubConnectionExistsOptionalParams,
WebPubSubCloseClientConnectionOptionalParams,
WebPubSubSendToConnection$binaryOptionalParams,
WebPubSubSendToConnection$textOptionalParams,
WebPubSubGroupExistsOptionalParams,
WebPubSubSendToGroup$binaryOptionalParams,
WebPubSubSendToGroup$textOptionalParams,
WebPubSubAddConnectionToGroupOptionalParams,
WebPubSubRemoveConnectionFromGroupOptionalParams,
WebPubSubUserExistsOptionalParams,
WebPubSubSendToUser$binaryOptionalParams,
WebPubSubSendToUser$textOptionalParams,
WebPubSubAddUserToGroupOptionalParams,
WebPubSubRemoveUserFromGroupOptionalParams,
WebPubSubRemoveUserFromAllGroupsOptionalParams,
WebPubSubPermission,
WebPubSubGrantPermissionOptionalParams,
WebPubSubRevokePermissionOptionalParams,
WebPubSubCheckPermissionOptionalParams
} from "../models";
/** Interface representing a WebPubSub. */
export interface WebPubSub {
/**
* Broadcast content inside request body to all the connected client connections.
* @param args Includes all the parameters for this operation.
*/
sendToAll(
...args:
| [
string,
ContentType,
coreRestPipeline.RequestBodyType,
WebPubSubSendToAll$binaryOptionalParams?
]
| [string, "text/plain", string, WebPubSubSendToAll$textOptionalParams?]
): Promise<void>;
/**
* Check if the connection with the given connectionId exists.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param connectionId The connection Id.
* @param options The options parameters.
*/
connectionExists(
hub: string,
connectionId: string,
options?: WebPubSubConnectionExistsOptionalParams
): Promise<void>;
/**
* Close the client connection.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
closeClientConnection(
hub: string,
connectionId: string,
options?: WebPubSubCloseClientConnectionOptionalParams
): Promise<void>;
/**
* Send content inside request body to the specific connection.
* @param args Includes all the parameters for this operation.
*/
sendToConnection(
...args:
| [
string,
string,
ContentType,
coreRestPipeline.RequestBodyType,
WebPubSubSendToConnection$binaryOptionalParams?
]
| [
string,
string,
"text/plain",
string,
WebPubSubSendToConnection$textOptionalParams?
]
): Promise<void>;
/**
* Check if there are any client connections inside the given group
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param options The options parameters.
*/
groupExists(
hub: string,
group: string,
options?: WebPubSubGroupExistsOptionalParams
): Promise<void>;
/**
* Send content inside request body to a group of connections.
* @param args Includes all the parameters for this operation.
*/
sendToGroup(
...args:
| [
string,
string,
ContentType,
coreRestPipeline.RequestBodyType,
WebPubSubSendToGroup$binaryOptionalParams?
]
| [
string,
string,
"text/plain",
string,
WebPubSubSendToGroup$textOptionalParams?
]
): Promise<void>;
/**
* Add a connection to the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param connectionId Target connection Id
* @param options The options parameters.
*/
addConnectionToGroup(
hub: string,
group: string,
connectionId: string,
options?: WebPubSubAddConnectionToGroupOptionalParams
): Promise<void>;
/**
* Remove a connection from the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
removeConnectionFromGroup(
hub: string,
group: string,
connectionId: string,
options?: WebPubSubRemoveConnectionFromGroupOptionalParams
): Promise<void>;
/**
* Check if there are any client connections connected for the given user.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param userId Target user Id.
* @param options The options parameters.
*/
userExists(
hub: string,
userId: string,
options?: WebPubSubUserExistsOptionalParams
): Promise<void>;
/**
* Send content inside request body to the specific user.
* @param args Includes all the parameters for this operation.
*/
sendToUser(
...args:
| [
string,
string,
ContentType,
coreRestPipeline.RequestBodyType,
WebPubSubSendToUser$binaryOptionalParams?
]
| [
string,
string,
"text/plain",
string,
WebPubSubSendToUser$textOptionalParams?
]
): Promise<void>;
/**
* Add a user to the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param userId Target user Id.
* @param options The options parameters.
*/
addUserToGroup(
hub: string,
group: string,
userId: string,
options?: WebPubSubAddUserToGroupOptionalParams
): Promise<void>;
/**
* Remove a user from the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param userId Target user Id.
* @param options The options parameters.
*/
removeUserFromGroup(
hub: string,
group: string,
userId: string,
options?: WebPubSubRemoveUserFromGroupOptionalParams
): Promise<void>;
/**
* Remove a user from all groups.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param userId Target user Id.
* @param options The options parameters.
*/
removeUserFromAllGroups(
hub: string,
userId: string,
options?: WebPubSubRemoveUserFromAllGroupsOptionalParams
): Promise<void>;
/**
* Grant permission to the connection.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
grantPermission(
hub: string,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubGrantPermissionOptionalParams
): Promise<void>;
/**
* Revoke permission for the connection.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
revokePermission(
hub: string,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubRevokePermissionOptionalParams
): Promise<void>;
/**
* Check if a connection has permission to the specified action.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
checkPermission(
hub: string,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubCheckPermissionOptionalParams
): Promise<void>;
}

Просмотреть файл

@ -1,23 +1,18 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
OperationOptions,
RestResponse,
RestError,
HttpRequestBody,
PipelineOptions
} from "@azure/core-http";
import { AzureWebPubSubServiceRestAPI as GeneratedClient } from "./generated/azureWebPubSubServiceRestAPI";
import { CommonClientOptions, FullOperationResponse, OperationOptions } from "@azure/core-client";
import { RestError, RequestBodyType } from "@azure/core-rest-pipeline";
import { GeneratedClient } from "./generated/generatedClient";
import { createSpan } from "./tracing";
import normalizeSendToAllOptions from "./normalizeOptions";
import { getContentTypeForMessage } from "./utils";
import { getPayloadForMessage } from "./utils";
import { JSONTypes } from "./hubClient";
/**
* Options for constructing a GroupAdmin client.
*/
export interface GroupAdminClientOptions extends PipelineOptions {}
export interface GroupAdminClientOptions extends CommonClientOptions {}
/**
* Options for adding a connection to a group.
@ -92,7 +87,7 @@ export interface WebPubSubGroup {
* @param connectionId The connection id to add to this group
* @param options Additional options
*/
addConnection(connectionId: string, options?: GroupAddConnectionOptions): Promise<RestResponse>;
addConnection(connectionId: string, options?: GroupAddConnectionOptions): Promise<void>;
/**
* Remove a specific connection from this group
@ -100,10 +95,7 @@ export interface WebPubSubGroup {
* @param connectionId The connection id to remove from this group
* @param options Additional options
*/
removeConnection(
connectionId: string,
options?: GroupRemoveConnectionOptions
): Promise<RestResponse>;
removeConnection(connectionId: string, options?: GroupRemoveConnectionOptions): Promise<void>;
/**
* Add a user to this group
@ -111,15 +103,7 @@ export interface WebPubSubGroup {
* @param username The user name to add
* @param options Additional options
*/
addUser(username: string, options?: GroupAddUserOptions): Promise<RestResponse>;
/**
* Check if a user is in this group
*
* @param username The user name to check for
* @param options Additional options
*/
hasUser(username: string, options?: GroupHasUserOptions): Promise<boolean>;
addUser(username: string, options?: GroupAddUserOptions): Promise<void>;
/**
* Remove a user from this group
@ -127,7 +111,7 @@ export interface WebPubSubGroup {
* @param username The user name to remove
* @param options Additional options
*/
removeUser(username: string, options?: GroupRemoveUserOptions): Promise<RestResponse>;
removeUser(username: string, options?: GroupRemoveUserOptions): Promise<void>;
/**
* Send a text message to every connection in this group
@ -135,21 +119,21 @@ export interface WebPubSubGroup {
* @param message The message to send
* @param options Additional options
*/
sendToAll(message: string, options: GroupSendTextToAllOptions): Promise<RestResponse>;
sendToAll(message: string, options: GroupSendTextToAllOptions): Promise<void>;
/**
* Send a json message to every connection in this group
*
* @param message The message to send
* @param options Additional options
*/
sendToAll(message: JSONTypes, options?: GroupSendToAllOptions): Promise<RestResponse>;
sendToAll(message: JSONTypes, options?: GroupSendToAllOptions): Promise<void>;
/**
* Send a binary message to every connection in this group
*
* @param message The binary message to send
* @param options Additional options
*/
sendToAll(message: HttpRequestBody, options?: GroupSendToAllOptions): Promise<RestResponse>;
sendToAll(message: RequestBodyType, options?: GroupSendToAllOptions): Promise<void>;
}
/**
@ -196,31 +180,32 @@ export class WebPubSubGroupImpl implements WebPubSubGroup {
public async addConnection(
connectionId: string,
options: GroupAddConnectionOptions = {}
): Promise<RestResponse> {
): Promise<void> {
const { span, updatedOptions } = createSpan(
"WebPubSubServiceClient-group-addConnection",
options
);
try {
const res = await this.client.webPubSub.addConnectionToGroup(
this.hubName,
this.groupName,
connectionId,
updatedOptions
);
if (res._response.status === 404) {
throw new RestError(
`Connection id '${connectionId}' doesn't exist`,
undefined,
res._response.status,
res._response.request,
res._response
);
let response: FullOperationResponse | undefined;
function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {
response = rawResponse;
if (updatedOptions.onResponse) {
updatedOptions.onResponse(rawResponse, flatResponse);
}
}
await this.client.webPubSub.addConnectionToGroup(this.hubName, this.groupName, connectionId, {
...updatedOptions,
onResponse
});
return res;
if (response?.status === 404) {
throw new RestError(`Connection id '${connectionId}' doesn't exist`, {
statusCode: response?.status,
request: response?.request,
response: response
});
}
} finally {
span.end();
}
@ -235,21 +220,19 @@ export class WebPubSubGroupImpl implements WebPubSubGroup {
public async removeConnection(
connectionId: string,
options: GroupRemoveConnectionOptions = {}
): Promise<RestResponse> {
): Promise<void> {
const { span, updatedOptions } = createSpan(
"WebPubSubServiceClient-group-removeConnection",
options
);
try {
const res = await this.client.webPubSub.removeConnectionFromGroup(
await this.client.webPubSub.removeConnectionFromGroup(
this.hubName,
this.groupName,
connectionId,
updatedOptions
);
return res;
} finally {
span.end();
}
@ -261,11 +244,11 @@ export class WebPubSubGroupImpl implements WebPubSubGroup {
* @param username The user name to add
* @param options Additional options
*/
public async addUser(username: string, options: GroupAddUserOptions = {}): Promise<RestResponse> {
public async addUser(username: string, options: GroupAddUserOptions = {}): Promise<void> {
const { span, updatedOptions } = createSpan("WebPubSubServiceClient-group-addUser", options);
try {
return await this.client.webPubSub.addUserToGroup(
await this.client.webPubSub.addUserToGroup(
this.hubName,
this.groupName,
username,
@ -276,56 +259,17 @@ export class WebPubSubGroupImpl implements WebPubSubGroup {
}
}
/**
* Check if a user is in this group
*
* @param username The user name to check for
* @param options Additional options
*/
public async hasUser(username: string, options: GroupHasUserOptions = {}): Promise<boolean> {
const { span, updatedOptions } = createSpan("WebPubSubServiceClient-group-hasUser", options);
try {
const res = await this.client.webPubSub.userExistsInGroup(
this.hubName,
this.groupName,
username,
updatedOptions
);
if (res._response.status === 200) {
return true;
} else if (res._response.status === 404) {
return false;
} else {
// this is sad - wish this was handled by autorest.
throw new RestError(
res._response.bodyAsText!,
undefined,
res._response.status,
res._response.request,
res._response
);
}
} finally {
span.end();
}
}
/**
* Remove a user from this group
*
* @param username The user name to remove
* @param options Additional options
*/
public async removeUser(
username: string,
options: GroupRemoveUserOptions = {}
): Promise<RestResponse> {
public async removeUser(username: string, options: GroupRemoveUserOptions = {}): Promise<void> {
const { span, updatedOptions } = createSpan("WebPubSubServiceClient-group-removeUser", options);
try {
return await this.client.webPubSub.removeUserFromGroup(
await this.client.webPubSub.removeUserFromGroup(
this.hubName,
this.groupName,
username,
@ -342,49 +286,40 @@ export class WebPubSubGroupImpl implements WebPubSubGroup {
* @param message The message to send
* @param options Additional options
*/
public async sendToAll(
message: string,
options: GroupSendTextToAllOptions
): Promise<RestResponse>;
public async sendToAll(message: string, options: GroupSendTextToAllOptions): Promise<void>;
/**
* Send a json message to every connection in this group
*
* @param message The message to send
* @param options Additional options
*/
public async sendToAll(
message: JSONTypes,
options?: GroupSendToAllOptions
): Promise<RestResponse>;
public async sendToAll(message: JSONTypes, options?: GroupSendToAllOptions): Promise<void>;
/**
* Send a binary message to every connection in this group
*
* @param message The binary message to send
* @param options Additional options
*/
public async sendToAll(
message: HttpRequestBody,
options?: GroupSendToAllOptions
): Promise<RestResponse>;
public async sendToAll(message: RequestBodyType, options?: GroupSendToAllOptions): Promise<void>;
public async sendToAll(
message: string | HttpRequestBody,
message: JSONTypes | RequestBodyType,
options: GroupSendToAllOptions | GroupSendTextToAllOptions = {}
): Promise<RestResponse> {
): Promise<void> {
const normalizedOptions = normalizeSendToAllOptions(options);
const { span, updatedOptions } = createSpan(
"WebPubSubServiceClient-group-sendToAll",
normalizedOptions
);
const contentType = getContentTypeForMessage(message, updatedOptions);
const { contentType, payload } = getPayloadForMessage(message, updatedOptions);
try {
return await this.client.webPubSub.sendToGroup(
await this.client.webPubSub.sendToGroup(
this.hubName,
this.groupName,
contentType as any,
contentType === "application/json" ? JSON.stringify(message) : message,
contentType,
payload as any,
updatedOptions
);
} finally {

Просмотреть файл

@ -1,25 +1,18 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
OperationOptions,
RestResponse,
RestError,
HttpRequestBody,
InternalPipelineOptions,
createPipelineFromOptions,
PipelineOptions
} from "@azure/core-http";
import { AzureWebPubSubServiceRestAPI as GeneratedClient } from "./generated/azureWebPubSubServiceRestAPI";
import { CommonClientOptions, FullOperationResponse, OperationOptions } from "@azure/core-client";
import { InternalPipelineOptions, RestError, RequestBodyType } from "@azure/core-rest-pipeline";
import { GeneratedClient } from "./generated/generatedClient";
import { WebPubSubGroup, WebPubSubGroupImpl } from "./groupClient";
import normalizeSendToAllOptions from "./normalizeOptions";
import { AzureKeyCredential } from "@azure/core-auth";
import { webPubSubAzureKeyCredentialPolicyFactory } from "./webPubSubCredentialPolicy";
import { webPubSubKeyCredentialPolicy } from "./webPubSubCredentialPolicy";
import { createSpan } from "./tracing";
import { logger } from "./logger";
import { parseConnectionString } from "./parseConnectionString";
import jwt from "jsonwebtoken";
import { getContentTypeForMessage } from "./utils";
import { getPayloadForMessage } from "./utils";
/**
* Options for closing a connection to a hub.
@ -56,7 +49,7 @@ export type JSONTypes = string | number | boolean | object;
/**
* Options for constructing a HubAdmin client.
*/
export interface HubAdminClientOptions extends PipelineOptions {}
export interface HubAdminClientOptions extends CommonClientOptions {}
/**
* Options for checking if a connection exists.
@ -259,7 +252,7 @@ export class WebPubSubServiceClient {
this.endpoint = parsedCs.endpoint;
this.credential = parsedCs.credential;
this.hubName = credsOrHubName as string;
this.clientOptions = hubNameOrOpts as PipelineOptions;
this.clientOptions = hubNameOrOpts as HubAdminClientOptions;
}
const internalPipelineOptions: InternalPipelineOptions = {
@ -271,12 +264,8 @@ export class WebPubSubServiceClient {
}
};
const pipeline = createPipelineFromOptions(
internalPipelineOptions,
webPubSubAzureKeyCredentialPolicyFactory(this.credential)
);
this.client = new GeneratedClient(this.endpoint, pipeline);
this.client = new GeneratedClient(this.endpoint, internalPipelineOptions);
this.client.pipeline.addPolicy(webPubSubKeyCredentialPolicy(this.credential));
}
/**
@ -324,41 +313,39 @@ export class WebPubSubServiceClient {
* @param message The text message to send
* @param options Additional options
*/
public async sendToAll(message: string, options: HubSendTextToAllOptions): Promise<RestResponse>;
public async sendToAll(message: string, options: HubSendTextToAllOptions): Promise<void>;
/**
* Broadcast a JSON message to all connections on this hub.
*
* @param message The JSON message to send
* @param options Additional options
*/
public async sendToAll(message: JSONTypes, options?: HubSendToAllOptions): Promise<RestResponse>;
public async sendToAll(message: JSONTypes, options?: HubSendToAllOptions): Promise<void>;
/**
* Broadcast a binary message to all connections on this hub.
*
* @param message The message to send
* @param options Additional options
*/
public async sendToAll(
message: HttpRequestBody,
options?: HubSendToAllOptions
): Promise<RestResponse>;
public async sendToAll(message: RequestBodyType, options?: HubSendToAllOptions): Promise<void>;
public async sendToAll(
message: HttpRequestBody | string,
message: RequestBodyType | JSONTypes,
options: HubSendToAllOptions | HubSendTextToAllOptions = {}
): Promise<RestResponse> {
): Promise<void> {
const normalizedOptions = normalizeSendToAllOptions(options);
const { span, updatedOptions } = createSpan(
"WebPubSubServiceClient-hub-sendToAll",
normalizedOptions
);
const contentType = getContentTypeForMessage(message, updatedOptions);
const { contentType, payload } = getPayloadForMessage(message, updatedOptions);
try {
return await this.client.webPubSub.sendToAll(
this.hubName,
contentType as any,
contentType === "application/json" ? JSON.stringify(message) : message,
contentType,
payload as any,
updatedOptions
);
} finally {
@ -377,7 +364,7 @@ export class WebPubSubServiceClient {
username: string,
message: string,
options: HubSendTextToUserOptions
): Promise<RestResponse>;
): Promise<void>;
/**
* Send a JSON message to a specific user
@ -390,7 +377,7 @@ export class WebPubSubServiceClient {
username: string,
message: JSONTypes,
options?: HubSendToUserOptions
): Promise<RestResponse>;
): Promise<void>;
/**
* Send a binary message to a specific user
@ -401,24 +388,23 @@ export class WebPubSubServiceClient {
*/
public async sendToUser(
username: string,
message: HttpRequestBody,
message: RequestBodyType,
options?: HubSendToUserOptions | HubSendTextToUserOptions
): Promise<RestResponse>;
): Promise<void>;
public async sendToUser(
username: string,
message: string | HttpRequestBody,
message: RequestBodyType | JSONTypes,
options: HubSendToUserOptions = {}
): Promise<RestResponse> {
): Promise<void> {
const { span, updatedOptions } = createSpan("WebPubSubServiceClient-hub-sendToUser", options);
const contentType = getContentTypeForMessage(message, updatedOptions);
const { contentType, payload } = getPayloadForMessage(message, updatedOptions);
try {
return await this.client.webPubSub.sendToUser(
this.hubName,
username,
contentType as any,
contentType === "application/json" ? JSON.stringify(message) : message,
contentType,
payload as any,
updatedOptions
);
} finally {
@ -437,7 +423,7 @@ export class WebPubSubServiceClient {
connectionId: string,
message: string,
options: HubSendTextToConnectionOptions
): Promise<RestResponse>;
): Promise<void>;
/**
* Send a binary message to a specific connection
@ -450,7 +436,7 @@ export class WebPubSubServiceClient {
connectionId: string,
message: JSONTypes,
options?: HubSendToConnectionOptions
): Promise<RestResponse>;
): Promise<void>;
/**
* Send a binary message to a specific connection
@ -461,26 +447,26 @@ export class WebPubSubServiceClient {
*/
public async sendToConnection(
connectionId: string,
message: HttpRequestBody | JSONTypes,
message: RequestBodyType,
options?: HubSendToConnectionOptions | HubSendTextToConnectionOptions
): Promise<RestResponse>;
): Promise<void>;
public async sendToConnection(
connectionId: string,
message: string | HttpRequestBody,
message: RequestBodyType | JSONTypes,
options: HubSendToConnectionOptions = {}
): Promise<RestResponse> {
): Promise<void> {
const { span, updatedOptions } = createSpan(
"WebPubSubServiceClient-hub-sendToConnection",
options
);
const contentType = getContentTypeForMessage(message, updatedOptions);
const { contentType, payload } = getPayloadForMessage(message, updatedOptions);
try {
return await this.client.webPubSub.sendToConnection(
this.hubName,
connectionId,
contentType as any,
contentType === "application/json" ? JSON.stringify(message) : message,
contentType,
payload as any,
updatedOptions
);
} finally {
@ -504,25 +490,30 @@ export class WebPubSubServiceClient {
);
try {
const res = await this.client.webPubSub.connectionExists(
this.hubName,
connectionId,
updatedOptions
);
let response: FullOperationResponse | undefined;
function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {
response = rawResponse;
if (updatedOptions.onResponse) {
updatedOptions.onResponse(rawResponse, flatResponse);
}
}
if (res._response.status === 200) {
await this.client.webPubSub.connectionExists(this.hubName, connectionId, {
...updatedOptions,
onResponse
});
if (response?.status === 200) {
return true;
} else if (res._response.status === 404) {
} else if (response?.status === 404) {
return false;
} else {
// this is sad - wish this was handled by autorest.
throw new RestError(
res._response.bodyAsText!,
undefined,
res._response.status,
res._response.request,
res._response
);
throw new RestError(response?.bodyAsText!, {
statusCode: response?.status,
request: response?.request,
response: response
});
}
} finally {
span.end();
@ -538,7 +529,7 @@ export class WebPubSubServiceClient {
public async closeConnection(
connectionId: string,
options: CloseConnectionOptions = {}
): Promise<RestResponse> {
): Promise<void> {
const { span, updatedOptions } = createSpan(
"WebPubSubServiceClient-hub-removeConnection",
options
@ -563,18 +554,14 @@ export class WebPubSubServiceClient {
public async removeUserFromAllGroups(
userId: string,
options: CloseConnectionOptions = {}
): Promise<RestResponse> {
): Promise<void> {
const { span, updatedOptions } = createSpan(
"WebPubSubServiceClient-hub-removeUserFromAllGroups",
options
);
try {
return await this.client.webPubSub.removeUserFromAllGroups(
this.hubName,
userId,
updatedOptions
);
await this.client.webPubSub.removeUserFromAllGroups(this.hubName, userId, updatedOptions);
} finally {
span.end();
}
@ -590,20 +577,28 @@ export class WebPubSubServiceClient {
const { span, updatedOptions } = createSpan("WebPubSubServiceClient-hub-hasGroup", options);
try {
const res = await this.client.webPubSub.groupExists(this.hubName, groupName, updatedOptions);
let response: FullOperationResponse | undefined;
function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {
response = rawResponse;
if (updatedOptions.onResponse) {
updatedOptions.onResponse(rawResponse, flatResponse);
}
}
await this.client.webPubSub.groupExists(this.hubName, groupName, {
...updatedOptions,
onResponse
});
if (res._response.status === 200) {
if (response?.status === 200) {
return true;
} else if (res._response.status === 404) {
} else if (response?.status === 404) {
return false;
} else {
throw new RestError(
res._response.bodyAsText!,
undefined,
res._response.status,
res._response.request,
res._response
);
throw new RestError(response?.bodyAsText!, {
statusCode: response?.status,
request: response?.request,
response: response
});
}
} finally {
span.end();
@ -620,21 +615,29 @@ export class WebPubSubServiceClient {
const { span, updatedOptions } = createSpan("WebPubSubServiceClient-hub-hasUser", options);
try {
const res = await this.client.webPubSub.userExists(this.hubName, username, updatedOptions);
let response: FullOperationResponse | undefined;
function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {
response = rawResponse;
if (updatedOptions.onResponse) {
updatedOptions.onResponse(rawResponse, flatResponse);
}
}
await this.client.webPubSub.userExists(this.hubName, username, {
...updatedOptions,
onResponse
});
if (res._response.status === 200) {
if (response?.status === 200) {
return true;
} else if (res._response.status === 404) {
} else if (response?.status === 404) {
return false;
} else {
// this is sad - wish this was handled by autorest.
throw new RestError(
res._response.bodyAsText!,
undefined,
res._response.status,
res._response.request,
res._response
);
throw new RestError(response?.bodyAsText!, {
statusCode: response?.status,
request: response?.request,
response: response
});
}
} finally {
span.end();
@ -710,19 +713,37 @@ export class WebPubSubServiceClient {
connectionId: string,
permission: Permission,
options: HubHasPermissionOptions = {}
) {
): Promise<boolean> {
const { span, updatedOptions } = createSpan(
"WebPubSubServiceClient-hub-hasPermission",
options
);
try {
return await this.client.webPubSub.checkPermission(
this.hubName,
permission,
connectionId,
updatedOptions
);
let response: FullOperationResponse | undefined;
function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {
response = rawResponse;
if (updatedOptions.onResponse) {
updatedOptions.onResponse(rawResponse, flatResponse);
}
}
await this.client.webPubSub.checkPermission(this.hubName, permission, connectionId, {
...updatedOptions,
onResponse
});
if (response?.status === 200) {
return true;
} else if (response?.status === 404) {
return false;
} else {
// this is sad - wish this was handled by autorest.
throw new RestError(response?.bodyAsText!, {
statusCode: response?.status,
request: response?.request,
response: response
});
}
} finally {
span.end();
}

Просмотреть файл

@ -1,6 +1,6 @@
import { HttpRequestBody } from "@azure/core-http";
import { RequestBodyType } from "@azure/core-rest-pipeline";
function isHttpRequestBody(obj: unknown): obj is HttpRequestBody {
function isRequestBody(obj: unknown): obj is RequestBodyType {
return (
typeof obj === "function" ||
(typeof obj === "object" &&
@ -11,18 +11,32 @@ function isHttpRequestBody(obj: unknown): obj is HttpRequestBody {
);
}
export function getContentTypeForMessage(
message: unknown,
options: Record<string, any>
): "text/plain" | "application/json" | "application/octet-stream" {
export interface TextPlainPayload {
contentType: "text/plain";
payload: string;
}
export interface JsonPayload {
contentType: "application/json";
payload: string;
}
export interface BinaryPayload {
contentType: "application/octet-stream";
payload: RequestBodyType;
}
export type Payload = TextPlainPayload | JsonPayload | BinaryPayload;
export function getPayloadForMessage(message: unknown, options: Record<string, any>): Payload {
if (options?.contentType === "text/plain") {
if (typeof message !== "string") {
throw new TypeError("Message must be a string.");
}
return "text/plain";
} else if (isHttpRequestBody(message)) {
return "application/octet-stream";
return { contentType: "text/plain", payload: message };
} else if (isRequestBody(message)) {
return { contentType: "application/octet-stream", payload: message };
} else {
return "application/json";
return { contentType: "application/json", payload: JSON.stringify(message) };
}
}

Просмотреть файл

@ -1,48 +1,37 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { KeyCredential } from "@azure/core-auth";
import {
BaseRequestPolicy,
RequestPolicy,
RequestPolicyOptions,
WebResource,
HttpOperationResponse
} from "@azure/core-http";
import { AzureKeyCredential } from "@azure/core-auth";
PipelineResponse,
PipelineRequest,
SendRequest,
PipelinePolicy
} from "@azure/core-rest-pipeline";
import jwt from "jsonwebtoken";
export function webPubSubAzureKeyCredentialPolicyFactory(credential: AzureKeyCredential) {
/**
* The programmatic identifier of the webPubSubKeyCredentialPolicy.
*/
export const webPubSubKeyCredentialPolicyName = "webPubSubKeyCredentialPolicy";
/**
* Create an HTTP pipeline policy to authenticate a request
* using an `AzureKeyCredential` for Text Analytics
* @internal
*/
export function webPubSubKeyCredentialPolicy(credential: KeyCredential): PipelinePolicy {
return {
create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {
return new WebPubSubKeyCredentialPolicy(nextPolicy, options, credential);
name: webPubSubKeyCredentialPolicyName,
sendRequest(request: PipelineRequest, next: SendRequest): Promise<PipelineResponse> {
const bearerToken = jwt.sign({}, credential.key, {
audience: request.url,
expiresIn: "1h",
algorithm: "HS256"
});
request.headers.set("Authorization", `Bearer ${bearerToken}`);
return next(request);
}
};
}
export class WebPubSubKeyCredentialPolicy extends BaseRequestPolicy {
public credential: AzureKeyCredential;
constructor(
nextPolicy: RequestPolicy,
options: RequestPolicyOptions,
credential: AzureKeyCredential
) {
super(nextPolicy, options);
this.credential = credential;
}
public sendRequest(request: WebResource): Promise<HttpOperationResponse> {
request.headers.set(
"Authorization",
"Bearer " +
jwt.sign({}, this.credential.key, {
audience: request.url,
expiresIn: "1h",
algorithm: "HS256"
})
);
return this._nextPolicy.sendRequest(request);
}
}

Просмотреть файл

@ -0,0 +1,28 @@
# Azure Web PubSub Protocol Layer
> see https://aka.ms/autorest
## Configuration
```yaml
package-name: "@azure/web-pubsub"
title: GeneratedClient
description: Web PubSub Client
generate-metadata: false
license-header: MICROSOFT_MIT_NO_VERSION
output-folder: ../
source-code-folder-path: ./src/generated
input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/webpubsub/data-plane/WebPubSub/preview/2021-05-01-preview/webpubsub.json
add-credentials: false
package-version: 1.0.0-beta.3
v3: true
hide-clients: true
use-core-v2: true
use-extension:
"@autorest/modelerfour": "4.19.3"
```
## Customizations for Track 2 Generator
See the [AutoRest samples](https://github.com/Azure/autorest/tree/master/Samples/3b-custom-transformations)
for more about how we're customizing things.

Просмотреть файл

@ -2,7 +2,7 @@
// Licensed under the MIT license.
/* eslint-disable no-invalid-this */
import { parseConnectionString } from "../src/parseConnectionString";
import * as assert from "assert";
import { assert } from "chai";
describe("Can parse connection string", function() {
it("can parse valid connection string", async () => {

Просмотреть файл

@ -3,14 +3,19 @@
/* eslint-disable no-invalid-this */
import { env, Recorder, record } from "@azure/test-utils-recorder";
import { WebPubSubServiceClient, WebPubSubGroup } from "../src";
import * as assert from "assert";
import { assert } from "chai";
import environmentSetup from "./testEnv";
import { RestError } from "@azure/core-http";
import { FullOperationResponse } from "@azure/core-client";
import { RestError } from "@azure/core-rest-pipeline";
describe("Group client working with a group", function() {
this.timeout(30000);
let recorder: Recorder;
let client: WebPubSubGroup;
let lastResponse: FullOperationResponse | undefined;
function onResponse(response: FullOperationResponse) {
lastResponse = response;
}
beforeEach(function() {
recorder = record(this, environmentSetup);
const hubClient = new WebPubSubServiceClient(env.WPS_CONNECTION_STRING, "simplechat");
@ -18,49 +23,37 @@ describe("Group client working with a group", function() {
});
it("can broadcast to groups", async () => {
let res = await client.sendToAll("hello", { contentType: "text/plain" });
assert.equal(res._response.status, 202);
await client.sendToAll("hello", { contentType: "text/plain", onResponse });
assert.equal(lastResponse?.status, 202);
res = await client.sendToAll({ x: 1, y: 2 });
assert.equal(res._response.status, 202);
await client.sendToAll({ x: 1, y: 2 }, { onResponse });
assert.equal(lastResponse?.status, 202);
const binaryMessage = new Uint8Array(10);
res = await client.sendToAll(binaryMessage.buffer);
assert.equal(res._response.status, 202);
await client.sendToAll(binaryMessage.buffer, { onResponse });
assert.equal(lastResponse?.status, 202);
});
it("can manage connections", async () => {
// this endpoint returns 404 for connections not on the hub
let error: RestError;
let error: RestError | undefined;
try {
await client.addConnection("xxxx");
} catch (e) {
error = e;
}
assert.notStrictEqual(error!, undefined);
assert.equal(error!.name, "RestError");
assert.exists(error);
assert.strictEqual(error?.name, "RestError");
// this endpoint just returns 200 if the connection isn't present
const res2 = await client.removeConnection("xxxx");
assert.equal(res2._response.status, 200);
await client.removeConnection("xxxx", { onResponse });
assert.equal(lastResponse?.status, 200);
});
it("can manage users", async () => {
const res = await client.addUser("brian");
assert.equal(res._response.status, 200);
const hasBrian = await client.hasUser("brian");
assert.ok(hasBrian);
const hasJeff = await client.hasUser("jeff");
assert.ok(!hasJeff);
const res2 = await client.removeUser("brian");
assert.equal(res2._response.status, 200);
const hasBrianNow = await client.hasUser("brian");
assert.ok(!hasBrianNow);
await client.addUser("brian");
await client.removeUser("brian");
});
afterEach(async function() {

Просмотреть файл

@ -3,8 +3,9 @@
/* eslint-disable no-invalid-this */
import { env, Recorder, record } from "@azure/test-utils-recorder";
import { WebPubSubServiceClient, AzureKeyCredential } from "../src";
import * as assert from "assert";
import { assert } from "chai";
import environmentSetup from "./testEnv";
import { FullOperationResponse } from "@azure/core-client";
describe("HubClient", function() {
let recorder: Recorder;
@ -19,11 +20,6 @@ describe("HubClient", function() {
});
describe("Constructing a HubClient", () => {
let cred: AzureKeyCredential;
beforeEach(function() {
cred = new AzureKeyCredential(env.WPS_API_KEY);
});
it("takes a connection string, hub name, and options", () => {
assert.doesNotThrow(() => {
new WebPubSubServiceClient(env.WPS_CONNECTION_STRING, "test-hub", {
@ -34,62 +30,74 @@ describe("HubClient", function() {
it("takes an endpoint, an API key, a hub name, and options", () => {
assert.doesNotThrow(() => {
new WebPubSubServiceClient(env.ENDPOINT, cred, "test-hub", {
retryOptions: { maxRetries: 2 }
});
new WebPubSubServiceClient(
env.ENDPOINT,
new AzureKeyCredential(env.WPS_API_KEY),
"test-hub",
{
retryOptions: { maxRetries: 2 }
}
);
});
});
});
describe("Working with a hub", function() {
this.timeout(30000);
let client: WebPubSubServiceClient;
let lastResponse: FullOperationResponse | undefined;
function onResponse(response: FullOperationResponse) {
lastResponse = response;
}
beforeEach(function() {
client = new WebPubSubServiceClient(env.WPS_CONNECTION_STRING, "simplechat");
});
it("can broadcast", async () => {
let res = await client.sendToAll("hello", { contentType: "text/plain" });
assert.equal(res._response.status, 202);
await client.sendToAll("hello", { contentType: "text/plain", onResponse });
assert.equal(lastResponse?.status, 202);
res = await client.sendToAll({ x: 1, y: 2 });
assert.equal(res._response.status, 202);
await client.sendToAll({ x: 1, y: 2 }, { onResponse });
assert.equal(lastResponse?.status, 202);
const binaryMessage = new Uint8Array(10);
res = await client.sendToAll(binaryMessage.buffer);
assert.equal(res._response.status, 202);
await client.sendToAll(binaryMessage.buffer, { onResponse });
assert.equal(lastResponse?.status, 202);
});
it("can send messages to a user", async () => {
let res = await client.sendToUser("brian", "hello", { contentType: "text/plain" });
assert.equal(res._response.status, 202);
await client.sendToUser("brian", "hello", {
contentType: "text/plain",
onResponse
});
assert.equal(lastResponse?.status, 202);
res = await client.sendToUser("brian", { x: 1, y: 2 });
assert.equal(res._response.status, 202);
await client.sendToUser("brian", { x: 1, y: 2 }, { onResponse });
assert.equal(lastResponse?.status, 202);
const binaryMessage = new Uint8Array(10);
res = await client.sendToUser("brian", binaryMessage.buffer);
assert.equal(res._response.status, 202);
await client.sendToUser("brian", binaryMessage.buffer, { onResponse });
assert.equal(lastResponse?.status, 202);
});
it("can send messages to a connection", async () => {
let res = await client.sendToConnection("xxxx", "hello", { contentType: "text/plain" });
assert.equal(res._response.status, 202);
await client.sendToConnection("xxxx", "hello", { contentType: "text/plain", onResponse });
assert.equal(lastResponse?.status, 202);
res = await client.sendToConnection("xxxx", { x: 1, y: 2 });
assert.equal(res._response.status, 202);
await client.sendToConnection("xxxx", { x: 1, y: 2 }, { onResponse });
assert.equal(lastResponse?.status, 202);
const binaryMessage = new Uint8Array(10);
res = await client.sendToConnection("xxxx", binaryMessage.buffer);
assert.equal(res._response.status, 202);
await client.sendToConnection("xxxx", binaryMessage.buffer, { onResponse });
assert.equal(lastResponse?.status, 202);
});
it("can manage users", async () => {
// `removeUserFromAllGroups` always times out.
it.skip("can manage users", async () => {
this.timeout(Infinity);
const res = await client.hasUser("foo");
assert.ok(!res);
const res2 = await client.removeUserFromAllGroups("brian");
assert.equal(res2._response.status, 200);
await client.removeUserFromAllGroups("brian", { onResponse });
assert.equal(lastResponse?.status, 200);
});
it("can check if a connection exists", async () => {