Skip to content

Commit

Permalink
Exposing BatchSharedKeyCredentials in @azure/batch (#2998)
Browse files Browse the repository at this point in the history
* initial commit

* updating version to 7.0.0

* Resolved rollup issues and addressed review feedback
  • Loading branch information
amarzavery authored May 21, 2019
1 parent 06c59d0 commit 8cacc12
Show file tree
Hide file tree
Showing 30 changed files with 5,498 additions and 8,334 deletions.
2 changes: 1 addition & 1 deletion sdk/batch/batch/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The MIT License (MIT)

Copyright (c) 2018 Microsoft
Copyright (c) 2019 Microsoft

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
154 changes: 85 additions & 69 deletions sdk/batch/batch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ This package contains an isomorphic SDK for BatchServiceClient.

### How to Install

```
```bash
npm install @azure/batch
```

Expand All @@ -19,91 +19,107 @@ npm install @azure/batch

##### Install @azure/ms-rest-nodeauth

```
```bash
npm install @azure/ms-rest-nodeauth
```

##### Sample code
##### Authentication

```ts
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as msRestNodeAuth from "@azure/ms-rest-nodeauth";
import { BatchServiceClient, BatchServiceModels, BatchServiceMappers } from "@azure/batch";
const subscriptionId = process.env["AZURE_SUBSCRIPTION_ID"];

msRestNodeAuth.interactiveLogin().then((creds) => {
const client = new BatchServiceClient(creds, subscriptionId);
const maxResults = 1;
const timeout = 1;
const clientRequestId = ec7b1657-199d-4d8a-bbb2-89a11a42e02a;
const returnClientRequestId = true;
const ocpDate = new Date().toUTCString();
client.application.list(maxResults, timeout, clientRequestId, returnClientRequestId, ocpDate).then((result) => {
console.log("The result is:");
console.log(result);
});
}).catch((err) => {
console.error(err);
});
1. Use `AzureCliCredentials` exported from `@azure/ms-rest-nodeauth`.
**Please make sure to install Azure CLI and login using `az login`.**

```typescript
import { AzureCliCredentials } from "@azure/ms-rest-nodeauth";

const batchEndpoint = process.env["AZURE_BATCH_ENDPOINT"] || "";
async function main(): Promise<void> {
try {
const creds = await AzureCliCredentials.create({ resource: "https://batch.core.windows.net/" });
const client = new BatchServiceClient(creds, batchEndpoint);
} catch (err) {
console.log(err);
}
}
```

#### browser - Authentication, client creation and list application as an example written in JavaScript.
2. Use the `BatchSharedKeyCredentials` exported from `@azure/batch`.

```typescript
import { BatchServiceClient, BatchSharedKeyCredentials } from "@azure/batch";

##### Install @azure/ms-rest-browserauth
const batchAccountName = process.env["AZURE_BATCH_ACCOUNT_NAME"] || "";
const batchAccountKey = process.env["AZURE_BATCH_ACCOUNT_KEY"] || "";
const batchEndpoint = process.env["AZURE_BATCH_ENDPOINT"] || "";

async function main(): Promise<void> {
try {
const creds = new BatchSharedKeyCredentials(batchAccountName, batchAccountKey);
const client = new BatchServiceClient(creds, batchEndpoint);
} catch (err) {
console.log(err);
}
}
```
npm install @azure/ms-rest-browserauth

3. Use the `MSIVmTokenCredentials` exported from `@azure/ms-rest-nodeauth`.

```typescript
import { MSIVmTokenCredentials } from "@azure/ms-rest-nodeauth";

const batchEndpoint = process.env["AZURE_BATCH_ENDPOINT"] || "";

async function main(): Promise<void> {
try {
const creds = await msRestNodeAuth.loginWithVmMSI({
resource: "https://batch.core.windows.net/"
});
const client = new BatchServiceClient(creds, batchEndpoint);
} catch (err) {
console.log(err);
}
}
```

##### Sample code

See https://github.com/Azure/ms-rest-browserauth to learn how to authenticate to Azure in the browser.

- index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>@azure/batch sample</title>
<script src="node_modules/@azure/ms-rest-js/dist/msRest.browser.js"></script>
<script src="node_modules/@azure/ms-rest-azure-js/dist/msRestAzure.js"></script>
<script src="node_modules/@azure/ms-rest-browserauth/dist/msAuth.js"></script>
<script src="node_modules/@azure/batch/dist/batch.js"></script>
<script type="text/javascript">
const subscriptionId = "<Subscription_Id>";
const authManager = new msAuth.AuthManager({
clientId: "<client id for your Azure AD app>",
tenant: "<optional tenant for your organization>"
});
authManager.finalizeLogin().then((res) => {
if (!res.isLoggedIn) {
// may cause redirects
authManager.login();
}
const client = new Azure.Batch.BatchServiceClient(res.creds, subscriptionId);
const maxResults = 1;
const timeout = 1;
const clientRequestId = ec7b1657-199d-4d8a-bbb2-89a11a42e02a;
const returnClientRequestId = true;
const ocpDate = new Date().toUTCString();
client.application.list(maxResults, timeout, clientRequestId, returnClientRequestId, ocpDate).then((result) => {
console.log("The result is:");
console.log(result);
}).catch((err) => {
console.log("An error occurred:");
console.error(err);
});
});
</script>
</head>
<body></body>
</html>
```typescript
import { BatchServiceClient, BatchServiceModels, BatchSharedKeyCredentials } from "@azure/batch";

const batchAccountName = process.env["AZURE_BATCH_ACCOUNT_NAME"] || "";
const batchAccountKey = process.env["AZURE_BATCH_ACCOUNT_KEY"] || "";
const batchEndpoint = process.env["AZURE_BATCH_ENDPOINT"] || "";

const creds = new BatchSharedKeyCredentials(batchAccountName, batchAccountKey);
const client = new BatchServiceClient(creds, batchEndpoint);

const options: BatchServiceModels.JobListOptionalParams = {
jobListOptions: { maxResults: 10 }
};

async function loop(res: BatchServiceModels.JobListResponse, nextLink?: string): Promise<void> {
if (nextLink !== undefined) {
const res1 = await client.job.listNext(nextLink);
if (res1.length) {
for (const item of res1) {
res.push(item);
}
}
return loop(res, res1.odatanextLink);
}
return Promise.resolve();
}

async function main(): Promise<void> {
const result = await client.job.list(options);
await loop(result, result.odatanextLink);
console.dir(result, { depth: null, colors: true });
}

main().catch((err) => console.log("An error occurred: ", err));
```

## Related projects

- [Microsoft Azure SDK for Javascript](https://github.com/Azure/azure-sdk-for-js)


![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-js/sdk/batch/batch/README.png)
24 changes: 17 additions & 7 deletions sdk/batch/batch/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
"name": "@azure/batch",
"author": "Microsoft Corporation",
"description": "BatchServiceClient Library with typescript type definitions for node.js and browser.",
"version": "6.0.0",
"version": "7.0.0",
"dependencies": {
"@azure/ms-rest-azure-js": "^1.1.0",
"@azure/ms-rest-js": "^1.1.0",
"tslib": "^1.9.3"
"@azure/ms-rest-azure-js": "^1.3.4",
"@azure/ms-rest-js": "^1.8.7",
"buffer": "^5.2.1",
"jssha": "^2.3.1",
"tslib": "^1.9.3",
"url-parse": "^1.4.7"
},
"keywords": [
"node",
Expand All @@ -17,12 +20,18 @@
],
"license": "MIT",
"main": "./dist/batch.js",
"module": "./esm/batchServiceClient.js",
"types": "./esm/batchServiceClient.d.ts",
"module": "./esm/batchIndex.js",
"types": "./esm/batchIndex.d.ts",
"devDependencies": {
"@types/jssha": "^2.0.0",
"@types/url-parse": "^1.4.3",
"typescript": "^3.1.1",
"rollup": "^0.66.2",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-inject": "^2.2.0",
"rollup-plugin-json": "^3.1.0",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-sourcemaps": "^0.4.2",
"uglify-js": "^3.4.9"
},
"homepage": "https://github.com/azure/azure-sdk-for-js/tree/master/sdk/batch/batch",
Expand All @@ -43,6 +52,7 @@
"esm/**/*.d.ts",
"esm/**/*.d.ts.map",
"src/**/*.ts",
"README.md",
"rollup.config.js",
"tsconfig.json"
],
Expand All @@ -52,5 +62,5 @@
"prepack": "npm install && npm run build"
},
"sideEffects": false,
"authPublish": true
"autoPublish": true
}
35 changes: 28 additions & 7 deletions sdk/batch/batch/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import rollup from "rollup";
import nodeResolve from "rollup-plugin-node-resolve";
import sourcemaps from "rollup-plugin-sourcemaps";
import cjs from "rollup-plugin-commonjs";
import inject from "rollup-plugin-inject";
import json from "rollup-plugin-json";

/**
* @type {import('rollup').RollupFileOptions}
* @type {rollup.RollupFileOptions}
*/
const config = {
input: './esm/batchServiceClient.js',
input: "./esm/batchIndex.js",
external: ["@azure/ms-rest-js", "@azure/ms-rest-azure-js"],
output: {
file: "./dist/batch.js",
Expand All @@ -16,16 +22,31 @@ const config = {
},
banner: `/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
* Licensed under the MIT License. See License.txt in the project root for license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/`
},
plugins: [
nodeResolve({ module: true })
nodeResolve({ module: true, preferBuiltins: false }),
sourcemaps(),
cjs({
namedExports: {
"url-parse": ["url"],
jssha: ["jssha"]
}
}),
inject({
modules: {
Buffer: ["buffer", "Buffer"],
process: "process"
},
exclude: ["./**/package.json"]
}),

json()
]
};

export default config;
14 changes: 14 additions & 0 deletions sdk/batch/batch/src/batchIndex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/

export { BatchSharedKeyCredentials } from "./batchSharedKeyCredentials";
export {
BatchServiceClient,
BatchServiceClientContext,
BatchServiceMappers,
BatchServiceModels
} from "./batchServiceClient";
export * from "./operations";
6 changes: 4 additions & 2 deletions sdk/batch/batch/src/batchServiceClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*/

import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "./models";
import * as Mappers from "./models/mappers";
import * as operations from "./operations";
Expand All @@ -30,10 +31,11 @@ class BatchServiceClient extends BatchServiceClientContext {
/**
* Initializes a new instance of the BatchServiceClient class.
* @param credentials Credentials needed for the client to connect to Azure.
* @param batchUrl The base URL for all Azure Batch service requests.
* @param [options] The parameter options
*/
constructor(credentials: msRest.ServiceClientCredentials, options?: Models.BatchServiceClientOptions) {
super(credentials, options);
constructor(credentials: msRest.ServiceClientCredentials, batchUrl: string, options?: msRestAzure.AzureServiceClientOptions) {
super(credentials, batchUrl, options);
this.application = new operations.Application(this);
this.pool = new operations.Pool(this);
this.account = new operations.Account(this);
Expand Down
15 changes: 10 additions & 5 deletions sdk/batch/batch/src/batchServiceClientContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,30 @@
* regenerated.
*/

import * as Models from "./models";
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";

const packageName = "@azure/batch";
const packageVersion = "0.1.0";
const packageVersion = "7.0.0";

export class BatchServiceClientContext extends msRestAzure.AzureServiceClient {
credentials: msRest.ServiceClientCredentials;
apiVersion?: string;
batchUrl: string;

/**
* Initializes a new instance of the BatchServiceClient class.
* @param credentials Credentials needed for the client to connect to Azure.
* @param batchUrl The base URL for all Azure Batch service requests.
* @param [options] The parameter options
*/
constructor(credentials: msRest.ServiceClientCredentials, options?: Models.BatchServiceClientOptions) {
constructor(credentials: msRest.ServiceClientCredentials, batchUrl: string, options?: msRestAzure.AzureServiceClientOptions) {
if (credentials == undefined) {
throw new Error('\'credentials\' cannot be null.');
}
if (batchUrl == undefined) {
throw new Error('\'batchUrl\' cannot be null.');
}

if (!options) {
options = {};
Expand All @@ -39,12 +43,13 @@ export class BatchServiceClientContext extends msRestAzure.AzureServiceClient {

super(credentials, options);

this.apiVersion = '2018-08-01.7.0';
this.apiVersion = '2018-12-01.8.0';
this.acceptLanguage = 'en-US';
this.longRunningOperationRetryTimeout = 30;
this.baseUri = options.baseUri || this.baseUri || "https://batch.core.windows.net";
this.baseUri = "{batchUrl}";
this.requestContentType = "application/json; charset=utf-8";
this.credentials = credentials;
this.batchUrl = batchUrl;

if(options.acceptLanguage !== null && options.acceptLanguage !== undefined) {
this.acceptLanguage = options.acceptLanguage;
Expand Down
Loading

0 comments on commit 8cacc12

Please sign in to comment.