Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@microsoft/microsoft-graph-client

Package Overview
Dependencies
Maintainers
3
Versions
47
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@microsoft/microsoft-graph-client - npm Package Compare versions

Comparing version 1.4.0 to 1.5.2

lib/src/browser/index.d.ts

97

CHANGELOG.md

@@ -1,57 +0,82 @@

## Changelog
# Changelog
### 1.3.0
## 1.4.0
New Features
* Support for Large File upload [[#1](https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession), [#2](https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/tasks/LargeFileUploadTask.md)]
* Batching made easy [[#1](https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching), [#2](https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/content/Batching.md)]
- Added Search query param functionality
Bug Fixes
* https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/97
* https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/110
* https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/39
* https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/111
### 1.2.0
- https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/115
- https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/107
## 1.3.0
New Features
- Support for Large File upload [[#1](https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession), [#2](https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/tasks/LargeFileUploadTask.md)]
- Batching made easy [[#1](https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching), [#2](https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/content/Batching.md)]
Bug Fixes
- https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/97
- https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/110
- https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/39
- https://github.com/microsoftgraph/msgraph-sdk-javascript/issues/111
## 1.2.0
Updates
* Two output js files, one with polyfills for Fetch-API and ES6-Promises ([lib/graph-js-sdk-web.js](./lib/graph-js-sdk-web.js)) and one without ([lib/graph-js-sdk-core.js](./lib/graph-js-sdk-core.js))
[Refer [README.md](https://github.com/microsoftgraph/msgraph-sdk-javascript#browser) for usage]
* Enum for ResponseType, which lists down the available ResponseType options in autocomplete
- Two output js files, one with polyfills for Fetch-API and ES6-Promises lib/graph-js-sdk-web.js and one without lib/graph-js-sdk-core.js [Refer [README.md](https://github.com/microsoftgraph/msgraph-sdk-javascript#browser) for usage]
- Enum for ResponseType, which lists down the available ResponseType options in autocomplete
Bug Fix
* Cannot access the property "request-id" of undefined in GraphError handling
### 1.1.0
- Cannot access the property "request-id" of undefined in GraphError handling
## 1.1.0
New Features
* Support for Multipart POST request
- Support for Multipart POST request
Updates
* Light weight FetchAPI dependency (in replacement for SuperAgent)
- Light weight FetchAPI dependency (in replacement for SuperAgent)
Bug Fixes
* Updated putStream and getStream to work for all sized files
* Added obfuscation for output js file (graph-js-sdk-web.js)
* Updated versions of mocha and chai to 5.2.0 and 4.1.2 to fix security vulnerability in growl (which is a dependency of mocha)
* Running unit test files under types directory
* Compiling ts files
#### 1.0.0
* Added tests for new Graph functionality - Delta query, Extensibility, OneNote, and more.
- Updated putStream and getStream to work for all sized files
- Added obfuscation for output js file (graph-js-sdk-web.js)
- Updated versions of mocha and chai to 5.2.0 and 4.1.2 to fix security vulnerability in growl (which is a dependency of mocha)
- Running unit test files under types directory
- Compiling ts files
#### 0.4.0
* Add support for ES5. Make sure to use `graph-js-sdk-web.js` for web apps
* Removed iterator helper method.
## 1.0.0
#### 0.3.1
* Support for Node.js versions 4 and 5
- Added tests for new Graph functionality - Delta query, Extensibility, OneNote, and more.
#### 0.3.0
* Migrated away from typings in client library core and TypeScript sample
## 0.4.0
#### 0.2.2
* Updated SuperAgent to version ``` 3.3.0 ```
- Add support for ES5. Make sure to use `graph-js-sdk-web.js` for web apps
- Removed iterator helper method.
#### 0.2.0
* **Breaking change for existing apps** - Initialize the client library with `MicrosoftGraph.Client.init({...})`. See the updated usage section below for code samples.
* Added response handling tests to simulate Graph calls
* Added type declarations file for core client library, which adds intellisense for chained methods.
## 0.3.1
- Support for Node.js versions 4 and 5
## 0.3.0
- Migrated away from typings in client library core and TypeScript sample
## 0.2.2
- Updated SuperAgent to version `3.3.0`
## 0.2.0
- **Breaking change for existing apps** - Initialize the client library with `MicrosoftGraph.Client.init({...})`. See the updated usage section below for code samples.
- Added response handling tests to simulate Graph calls
- Added type declarations file for core client library, which adds intellisense for chained methods.
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @interface

@@ -43,2 +49,3 @@ * Signature representing BatchRequestStep data

/**
* @class
* Class for handling BatchRequestContent

@@ -54,2 +61,3 @@ */

/**
* @public
* To keep track of requests, key will be id of the request and value will be the request json

@@ -59,25 +67,2 @@ */

/**
* Constructs a BatchRequestContent instance
* @param {BatchRequestStep[]} [requests] - Array of requests value
*/
constructor(requests?: BatchRequestStep[]);
/**
* Adds a request to the batch request content
* @param {BatchRequestStep} request - The request value
* @return The id of the added request
*/
addRequest(request: BatchRequestStep): string;
/**
* Removes request from the batch payload and its dependencies from all dependents
* @param {string} requestId - The id of a request that needs to be removed
* @return The boolean indicating removed status
*/
removeRequest(requestId: string): boolean;
/**
* @async
* Serialize content from BatchRequestContent instance
* @return The body content to make batch request
*/
getContent(): Promise<BatchRequestBody>;
/**
* @private

@@ -95,5 +80,6 @@ * @static

*
* @return The boolean indicating the validation status
* @param {Map<string, BatchRequestStep>} requests - The map of requests.
* @returns The boolean indicating the validation status
*/
static validateDependencies(requests: Map<string, BatchRequestStep>): boolean;
private static validateDependencies;
/**

@@ -105,3 +91,3 @@ * @private

* @param {IsomorphicRequest} request - The IsomorphicRequest Object instance
* @return A promise that resolves to JSON representation of a request
* @returns A promise that resolves to JSON representation of a request
*/

@@ -115,19 +101,50 @@ private static getRequestData;

* @param {IsomorphicRequest} request - The IsomorphicRequest object instance
* @return The Promise that resolves to a body value of a Request
* @returns The Promise that resolves to a body value of a Request
*/
private static getRequestBody;
/**
* @public
* @constructor
* Constructs a BatchRequestContent instance
* @param {BatchRequestStep[]} [requests] - Array of requests value
* @returns An instance of a BatchRequestContent
*/
constructor(requests?: BatchRequestStep[]);
/**
* @public
* Adds a request to the batch request content
* @param {BatchRequestStep} request - The request value
* @returns The id of the added request
*/
addRequest(request: BatchRequestStep): string;
/**
* @public
* Removes request from the batch payload and its dependencies from all dependents
* @param {string} requestId - The id of a request that needs to be removed
* @returns The boolean indicating removed status
*/
removeRequest(requestId: string): boolean;
/**
* @public
* @async
* Serialize content from BatchRequestContent instance
* @returns The body content to make batch request
*/
getContent(): Promise<BatchRequestBody>;
/**
* @public
* Adds a dependency for a given dependent request
*
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified the preceding request will be considered as a dependency
* @returns Nothing
*/
addDependency(dependentId: string, dependencyId?: string): void;
/**
* @public
* Removes a dependency for a given dependent request id
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified will remove all the dependencies of that request
* @return The boolean indicating removed status
* @returns The boolean indicating removed status
*/
removeDependency(dependentId: string, dependencyId?: string): boolean;
}
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/**

@@ -43,2 +15,3 @@ * @module BatchRequestContent

/**
* @class
* Class for handling BatchRequestContent

@@ -48,8 +21,10 @@ */

/**
* @public
* @constructor
* Constructs a BatchRequestContent instance
* @param {BatchRequestStep[]} [requests] - Array of requests value
* @returns An instance of a BatchRequestContent
*/
function BatchRequestContent(requests) {
var self = this;
self.requests = new Map();
this.requests = new Map();
if (typeof requests !== "undefined") {

@@ -64,3 +39,3 @@ var limit = BatchRequestContent.requestLimit;

var req = requests_1[_i];
self.addRequest(req);
this.addRequest(req);
}

@@ -70,103 +45,2 @@ }

/**
* Adds a request to the batch request content
* @param {BatchRequestStep} request - The request value
* @return The id of the added request
*/
BatchRequestContent.prototype.addRequest = function (request) {
var self = this, limit = BatchRequestContent.requestLimit;
if (request.id === "") {
var error = new Error("Id for a request is empty, Please provide an unique id");
error.name = "Empty Id For Request";
throw error;
}
if (self.requests.size === limit) {
var error = new Error("Maximum requests limit exceeded, Max allowed number of requests are " + limit);
error.name = "Limit Exceeded Error";
throw error;
}
if (self.requests.has(request.id)) {
var error = new Error("Adding request with duplicate id " + request.id + ", Make the id of the requests unique");
error.name = "Duplicate RequestId Error";
throw error;
}
self.requests.set(request.id, request);
return request.id;
};
/**
* Removes request from the batch payload and its dependencies from all dependents
* @param {string} requestId - The id of a request that needs to be removed
* @return The boolean indicating removed status
*/
BatchRequestContent.prototype.removeRequest = function (requestId) {
var self = this, deleteStatus = self.requests.delete(requestId), iterator = self.requests.entries(), cur = iterator.next();
/**
* Removing dependencies where this request is present as a dependency
*/
while (!cur.done) {
var dependencies = cur.value[1].dependsOn;
if (typeof dependencies !== "undefined") {
var index = dependencies.indexOf(requestId);
if (index !== -1) {
dependencies.splice(index, 1);
}
if (dependencies.length === 0) {
delete cur.value[1].dependsOn;
}
}
cur = iterator.next();
}
return deleteStatus;
};
/**
* @async
* Serialize content from BatchRequestContent instance
* @return The body content to make batch request
*/
BatchRequestContent.prototype.getContent = function () {
return __awaiter(this, void 0, void 0, function () {
var self, requestBody, requests, iterator, cur, error, error, requestStep, batchRequestData, error;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this, requestBody = {}, requests = [], iterator = self.requests.entries(), cur = iterator.next();
if (cur.done) {
error = new Error("No requests added yet, Please add at least one request.");
error.name = "Empty Payload";
throw error;
}
if (!BatchRequestContent.validateDependencies(self.requests)) {
error = new Error("Invalid dependency found, Dependency should be:\n1. Parallel - no individual request states a dependency in the dependsOn property.\n2. Serial - all individual requests depend on the previous individual request.\n3. Same - all individual requests that state a dependency in the dependsOn property, state the same dependency.");
error.name = "Invalid Dependency";
throw error;
}
_a.label = 1;
case 1:
if (!!cur.done) return [3 /*break*/, 3];
requestStep = cur.value[1];
return [4 /*yield*/, BatchRequestContent.getRequestData(requestStep.request)];
case 2:
batchRequestData = _a.sent();
/**
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching#request-format}
*/
if (batchRequestData.body !== undefined && (batchRequestData.headers === undefined || batchRequestData.headers["content-type"] === undefined)) {
error = new Error("Content-type header is not mentioned for request #" + requestStep.id + ", For request having body, Content-type header should be mentioned");
error.name = "Invalid Content-type header";
throw error;
}
batchRequestData.id = requestStep.id;
if (requestStep.dependsOn !== undefined && requestStep.dependsOn.length > 0) {
batchRequestData.dependsOn = requestStep.dependsOn;
}
requests.push(batchRequestData);
cur = iterator.next();
return [3 /*break*/, 1];
case 3:
requestBody.requests = requests;
return [2 /*return*/, requestBody];
}
});
});
};
/**
* @private

@@ -184,7 +58,9 @@ * @static

*
* @return The boolean indicating the validation status
* @param {Map<string, BatchRequestStep>} requests - The map of requests.
* @returns The boolean indicating the validation status
*/
BatchRequestContent.validateDependencies = function (requests) {
var isParallel = function (requests) {
var iterator = requests.entries(), cur = iterator.next();
var isParallel = function (reqs) {
var iterator = reqs.entries();
var cur = iterator.next();
while (!cur.done) {

@@ -199,4 +75,5 @@ var curReq = cur.value[1];

};
var isSerial = function (requests) {
var iterator = requests.entries(), cur = iterator.next();
var isSerial = function (reqs) {
var iterator = reqs.entries();
var cur = iterator.next();
var firstRequest = cur.value[1];

@@ -218,5 +95,7 @@ if (firstRequest.dependsOn !== undefined && firstRequest.dependsOn.length > 0) {

};
var isSame = function (requests) {
var iterator = requests.entries(), cur = iterator.next();
var firstRequest = cur.value[1], dependencyId;
var isSame = function (reqs) {
var iterator = reqs.entries();
var cur = iterator.next();
var firstRequest = cur.value[1];
var dependencyId;
if (firstRequest.dependsOn === undefined || firstRequest.dependsOn.length === 0) {

@@ -228,3 +107,3 @@ dependencyId = firstRequest.id;

var fDependencyId = firstRequest.dependsOn[0];
if (fDependencyId !== firstRequest.id && requests.has(fDependencyId)) {
if (fDependencyId !== firstRequest.id && reqs.has(fDependencyId)) {
dependencyId = fDependencyId;

@@ -263,3 +142,3 @@ }

}
return (isParallel(requests) || isSerial(requests) || isSame(requests));
return isParallel(requests) || isSerial(requests) || isSame(requests);
};

@@ -272,19 +151,16 @@ /**

* @param {IsomorphicRequest} request - The IsomorphicRequest Object instance
* @return A promise that resolves to JSON representation of a request
* @returns A promise that resolves to JSON representation of a request
*/
BatchRequestContent.getRequestData = function (request) {
return __awaiter(this, void 0, void 0, function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var requestData, hasHttpRegex, headers, _a;
return __generator(this, function (_b) {
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
requestData = {};
hasHttpRegex = new RegExp("^https?:\/\/");
if (hasHttpRegex.test(request.url)) {
// Stripping off hostname, port and url scheme
requestData.url = "/" + request.url.split(/.*?\/\/.*?\//)[1];
}
else {
requestData.url = request.url;
}
requestData = {
url: "",
};
hasHttpRegex = new RegExp("^https?://");
// Stripping off hostname, port and url scheme
requestData.url = hasHttpRegex.test(request.url) ? "/" + request.url.split(/.*?\/\/.*?\//)[1] : request.url;
requestData.method = request.method;

@@ -319,8 +195,8 @@ headers = {};

* @param {IsomorphicRequest} request - The IsomorphicRequest object instance
* @return The Promise that resolves to a body value of a Request
* @returns The Promise that resolves to a body value of a Request
*/
BatchRequestContent.getRequestBody = function (request) {
return __awaiter(this, void 0, void 0, function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var bodyParsed, body, cloneReq, e_1, blob_1, reader_1, buffer, e_2;
return __generator(this, function (_a) {
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {

@@ -353,3 +229,3 @@ case 0:

reader_1.addEventListener("load", function () {
var dataURL = reader_1.result,
var dataURL = reader_1.result;
/**

@@ -364,3 +240,4 @@ * Some valid dataURL schemes:

*/
regex = new RegExp("^\s*data:(.+?\/.+?(;.+?\=.+?)*)?(;base64)?,(.*)\s*$"), segments = regex.exec(dataURL);
var regex = new RegExp("^s*data:(.+?/.+?(;.+?=.+?)*)?(;base64)?,(.*)s*$");
var segments = regex.exec(dataURL);
resolve(segments[4]);

@@ -392,10 +269,121 @@ }, false);

/**
* @public
* Adds a request to the batch request content
* @param {BatchRequestStep} request - The request value
* @returns The id of the added request
*/
BatchRequestContent.prototype.addRequest = function (request) {
var limit = BatchRequestContent.requestLimit;
if (request.id === "") {
var error = new Error("Id for a request is empty, Please provide an unique id");
error.name = "Empty Id For Request";
throw error;
}
if (this.requests.size === limit) {
var error = new Error("Maximum requests limit exceeded, Max allowed number of requests are " + limit);
error.name = "Limit Exceeded Error";
throw error;
}
if (this.requests.has(request.id)) {
var error = new Error("Adding request with duplicate id " + request.id + ", Make the id of the requests unique");
error.name = "Duplicate RequestId Error";
throw error;
}
this.requests.set(request.id, request);
return request.id;
};
/**
* @public
* Removes request from the batch payload and its dependencies from all dependents
* @param {string} requestId - The id of a request that needs to be removed
* @returns The boolean indicating removed status
*/
BatchRequestContent.prototype.removeRequest = function (requestId) {
var deleteStatus = this.requests.delete(requestId);
var iterator = this.requests.entries();
var cur = iterator.next();
/**
* Removing dependencies where this request is present as a dependency
*/
while (!cur.done) {
var dependencies = cur.value[1].dependsOn;
if (typeof dependencies !== "undefined") {
var index = dependencies.indexOf(requestId);
if (index !== -1) {
dependencies.splice(index, 1);
}
if (dependencies.length === 0) {
delete cur.value[1].dependsOn;
}
}
cur = iterator.next();
}
return deleteStatus;
};
/**
* @public
* @async
* Serialize content from BatchRequestContent instance
* @returns The body content to make batch request
*/
BatchRequestContent.prototype.getContent = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var requests, requestBody, iterator, cur, error, error, requestStep, batchRequestData, error;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
requests = [];
requestBody = {
requests: requests,
};
iterator = this.requests.entries();
cur = iterator.next();
if (cur.done) {
error = new Error("No requests added yet, Please add at least one request.");
error.name = "Empty Payload";
throw error;
}
if (!BatchRequestContent.validateDependencies(this.requests)) {
error = new Error("Invalid dependency found, Dependency should be:\n1. Parallel - no individual request states a dependency in the dependsOn property.\n2. Serial - all individual requests depend on the previous individual request.\n3. Same - all individual requests that state a dependency in the dependsOn property, state the same dependency.");
error.name = "Invalid Dependency";
throw error;
}
_a.label = 1;
case 1:
if (!!cur.done) return [3 /*break*/, 3];
requestStep = cur.value[1];
return [4 /*yield*/, BatchRequestContent.getRequestData(requestStep.request)];
case 2:
batchRequestData = (_a.sent());
/**
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching#request-format}
*/
if (batchRequestData.body !== undefined && (batchRequestData.headers === undefined || batchRequestData.headers["content-type"] === undefined)) {
error = new Error("Content-type header is not mentioned for request #" + requestStep.id + ", For request having body, Content-type header should be mentioned");
error.name = "Invalid Content-type header";
throw error;
}
batchRequestData.id = requestStep.id;
if (requestStep.dependsOn !== undefined && requestStep.dependsOn.length > 0) {
batchRequestData.dependsOn = requestStep.dependsOn;
}
requests.push(batchRequestData);
cur = iterator.next();
return [3 /*break*/, 1];
case 3:
requestBody.requests = requests;
return [2 /*return*/, requestBody];
}
});
});
};
/**
* @public
* Adds a dependency for a given dependent request
*
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified the preceding request will be considered as a dependency
* @returns Nothing
*/
BatchRequestContent.prototype.addDependency = function (dependentId, dependencyId) {
var self = this;
if (!self.requests.has(dependentId)) {
if (!this.requests.has(dependentId)) {
var error = new Error("Dependent " + dependentId + " does not exists, Please check the id");

@@ -405,3 +393,3 @@ error.name = "Invalid Dependent";

}
if (typeof dependencyId !== "undefined" && !self.requests.has(dependencyId)) {
if (typeof dependencyId !== "undefined" && !this.requests.has(dependencyId)) {
var error = new Error("Dependency " + dependencyId + " does not exists, Please check the id");

@@ -412,7 +400,7 @@ error.name = "Invalid Dependency";

if (typeof dependencyId !== "undefined") {
var dependent = self.requests.get(dependentId);
var dependent = this.requests.get(dependentId);
if (dependent.dependsOn === undefined) {
dependent.dependsOn = [];
}
if (dependent.dependsOn.includes(dependencyId)) {
if (dependent.dependsOn.indexOf(dependencyId) !== -1) {
var error = new Error("Dependency " + dependencyId + " is already added for the request " + dependentId);

@@ -425,3 +413,5 @@ error.name = "Duplicate Dependency";

else {
var prev = void 0, iterator = self.requests.entries(), cur = iterator.next();
var iterator = this.requests.entries();
var prev = void 0;
var cur = iterator.next();
while (!cur.done && cur.value[1].id !== dependentId) {

@@ -432,12 +422,12 @@ prev = cur;

if (typeof prev !== "undefined") {
var dependencyId_1 = prev.value[0];
var dId = prev.value[0];
if (cur.value[1].dependsOn === undefined) {
cur.value[1].dependsOn = [];
}
if (cur.value[1].dependsOn.includes(dependencyId_1)) {
var error = new Error("Dependency " + dependencyId_1 + " is already added for the request " + dependentId);
if (cur.value[1].dependsOn.indexOf(dId) !== -1) {
var error = new Error("Dependency " + dId + " is already added for the request " + dependentId);
error.name = "Duplicate Dependency";
throw error;
}
cur.value[1].dependsOn.push(dependencyId_1);
cur.value[1].dependsOn.push(dId);
}

@@ -452,6 +442,7 @@ else {

/**
* @public
* Removes a dependency for a given dependent request id
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified will remove all the dependencies of that request
* @return The boolean indicating removed status
* @returns The boolean indicating removed status
*/

@@ -458,0 +449,0 @@ BatchRequestContent.prototype.removeDependency = function (dependentId, dependencyId) {

/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module BatchResponseContent

@@ -15,3 +21,3 @@ */

* @property {KeyValuePairObject[]} responses - An array of key value pair representing response object for every request
* @property {string} @nextLink - The nextLink value to get next set of responses in case of asynchronous batch requests
* @property {string} [@nextLink] - The nextLink value to get next set of responses in case of asynchronous batch requests
*/

@@ -23,2 +29,3 @@ interface BatchResponseBody {

/**
* @class
* Class that handles BatchResponseContent

@@ -36,31 +43,40 @@ */

/**
* @public
* @constructor
* Creates the BatchResponseContent instance
* @param {BatchResponseBody} response - The response body returned for batch request from server
* @returns An instance of a BatchResponseContent
*/
constructor(response: BatchResponseBody);
/**
* @private
* Creates native Response object from the json representation of it.
* @param {KeyValuePairObject} responseJSON - The response json value
* @returns The Response Object instance
*/
private createResponseObject;
/**
* @public
* Updates the Batch response content instance with given responses.
* @param {BatchResponseBody} response - The response json representing batch response message
* @returns Nothing
*/
update(response: BatchResponseBody): void;
/**
* Creates native Response object from the json representation of it.
* @param {KeyValuePairObject} responseJSON - The response json value
* @return The Response Object instance
*/
private createResponseObject;
/**
* @public
* To get the response of a request for a given request id
* @param {string} requestId - The request id value
* @return The Response object instance for the particular request
* @returns The Response object instance for the particular request
*/
getResponseById(requestId: string): Response;
/**
* @public
* To get all the responses of the batch request
* @return The Map of id and Response objects
* @returns The Map of id and Response objects
*/
getResponses(): Map<string, Response>;
/**
* @public
* To get the iterator for the responses
* @return The Iterable generator for the response objects
* @returns The Iterable generator for the response objects
*/

@@ -67,0 +83,0 @@ getResponsesIterator(): IterableIterator<[string, Response]>;

"use strict";
/**
* @module BatchResponseContent
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/**
* @class
* Class that handles BatchResponseContent

@@ -38,29 +16,21 @@ */

/**
* @public
* @constructor
* Creates the BatchResponseContent instance
* @param {BatchResponseBody} response - The response body returned for batch request from server
* @returns An instance of a BatchResponseContent
*/
function BatchResponseContent(response) {
var self = this;
self.responses = new Map();
self.update(response);
this.responses = new Map();
this.update(response);
}
/**
* Updates the Batch response content instance with given responses.
* @param {BatchResponseBody} response - The response json representing batch response message
*/
BatchResponseContent.prototype.update = function (response) {
var self = this;
self.nextLink = response["@nextLink"];
var responses = response.responses;
for (var i = 0, l = responses.length; i < l; i++) {
self.responses.set(responses[i].id, self.createResponseObject(responses[i]));
}
};
/**
* @private
* Creates native Response object from the json representation of it.
* @param {KeyValuePairObject} responseJSON - The response json value
* @return The Response Object instance
* @returns The Response Object instance
*/
BatchResponseContent.prototype.createResponseObject = function (responseJSON) {
var body = responseJSON.body, options = {};
var body = responseJSON.body;
var options = {};
options.status = responseJSON.status;

@@ -74,5 +44,19 @@ if (responseJSON.statusText !== undefined) {

/**
* @public
* Updates the Batch response content instance with given responses.
* @param {BatchResponseBody} response - The response json representing batch response message
* @returns Nothing
*/
BatchResponseContent.prototype.update = function (response) {
this.nextLink = response["@nextLink"];
var responses = response.responses;
for (var i = 0, l = responses.length; i < l; i++) {
this.responses.set(responses[i].id, this.createResponseObject(responses[i]));
}
};
/**
* @public
* To get the response of a request for a given request id
* @param {string} requestId - The request id value
* @return The Response object instance for the particular request
* @returns The Response object instance for the particular request
*/

@@ -83,4 +67,5 @@ BatchResponseContent.prototype.getResponseById = function (requestId) {

/**
* @public
* To get all the responses of the batch request
* @return The Map of id and Response objects
* @returns The Map of id and Response objects
*/

@@ -91,11 +76,13 @@ BatchResponseContent.prototype.getResponses = function () {

/**
* @public
* To get the iterator for the responses
* @return The Iterable generator for the response objects
* @returns The Iterable generator for the response objects
*/
BatchResponseContent.prototype.getResponsesIterator = function () {
var self, iterator, cur;
return __generator(this, function (_a) {
var iterator, cur;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this, iterator = self.responses.entries(), cur = iterator.next();
iterator = this.responses.entries();
cur = iterator.next();
_a.label = 1;

@@ -102,0 +89,0 @@ case 1:

@@ -1,94 +0,342 @@

import { Promise } from 'es6-promise';
import 'isomorphic-fetch';
import { Options, URLComponents, GraphRequestCallback, FetchOptions } from "./common";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { HTTPClient } from "./HTTPClient";
import { ClientOptions } from "./IClientOptions";
import { GraphRequestCallback } from "./IGraphRequestCallback";
import { MiddlewareOptions } from "./middleware/options/IMiddlewareOptions";
import { ResponseType } from "./ResponseType";
/**
* @interface
* Signature to representing key value pairs
* @property {[key: string] : string | number} - The Key value pair
*/
interface KeyValuePairObjectStringNumber {
[key: string]: string | number;
}
/**
* @interface
* Signature to define URL components
* @template http://graph.microsoft.com/VERSION/PATH?QUERYSTRING&OTHER_QUERY_PARAMS
*
* @property {string} host - The host to which the request needs to be made
* @property {string} version - Version of the graph endpoint
* @property {string} [path] - The path of the resource request
* @property {KeyValuePairObjectStringNumber} oDataQueryParams - The oData Query Params
* @property {KeyValuePairObjectStringNumber} otherURLQueryParams - The other query params for a request
*/
export interface URLComponents {
host: string;
version: string;
path?: string;
oDataQueryParams: KeyValuePairObjectStringNumber;
otherURLQueryParams: KeyValuePairObjectStringNumber;
}
/**
* @class
* A Class representing GraphRequest
*/
export declare class GraphRequest {
config: Options;
urlComponents: URLComponents;
_options: FetchOptions;
_headers: {
[key: string]: string;
};
_responseType: string;
constructor(config: Options, path: string);
header(headerKey: string, headerValue: string): this;
headers(headers: {
[key: string]: string | number;
}): this;
option(key: string, value: any): this;
/**
* @private
* A member variable to hold HTTPClient instance
*/
private httpClient;
/**
* @private
* A member variable to hold client options
*/
private config;
/**
* @private
* A member to hold URL Components data
*/
private urlComponents;
/**
* @private
* A member to hold custom header options for a request
*/
private _headers;
/**
* @private
* A member to hold custom options for a request
*/
private _options;
/**
* @private
* A member to hold the array of middleware options for a request
*/
private _middlewareOptions;
/**
* @private
* A member to hold custom response type for a request
*/
private _responseType;
/**
* @public
* @constructor
* Creates an instance of GraphRequest
* @param {HTTPClient} httpClient - The HTTPClient instance
* @param {ClientOptions} config - The options for making request
* @param {string} path - A path string
*/
constructor(httpClient: HTTPClient, config: ClientOptions, path: string);
/**
* @private
* Parses the path string and creates URLComponents out of it
* @param {string} path - The request path string
* @returns Nothing
*/
private parsePath;
/**
* @private
* Adds the query parameter as comma separated values
* @param {string} propertyName - The name of a property
* @param {string|string[]} propertyValue - The vale of a property
* @param {IArguments} additionalProperties - The additional properties
* @returns Nothing
*/
private addCsvQueryParameter;
/**
* @private
* Builds the full url from the URLComponents to make a request
* @returns The URL string that is qualified to make a request to graph endpoint
*/
private buildFullUrl;
/**
* @private
* Builds the query string from the URLComponents
* @returns The Constructed query string
*/
private createQueryString;
/**
* @private
* Updates the custom headers and options for a request
* @param {FetchOptions} options - The request options object
* @returns Nothing
*/
private updateRequestOptions;
/**
* @private
* @async
* Adds the custom headers and options to the request and makes the HTTPClient send request call
* @param {RequestInfo} request - The request url string or the Request object value
* @param {FetchOptions} options - The options to make a request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the response content
*/
private send;
/**
* @public
* Sets the custom header for a request
* @param {string} headerKey - A header key
* @param {string} headerValue - A header value
* @returns The same GraphRequest instance that is being called with
*/
header(headerKey: string, headerValue: string): GraphRequest;
/**
* @public
* Sets the custom headers for a request
* @param {KeyValuePairObjectStringNumber} headers - The headers key value pair object
* @returns The same GraphRequest instance that is being called with
*/
headers(headers: KeyValuePairObjectStringNumber): GraphRequest;
/**
* @public
* Sets the option for making a request
* @param {string} key - The key value
* @param {any} value - The value
* @returns The same GraphRequest instance that is being called with
*/
option(key: string, value: any): GraphRequest;
/**
* @public
* Sets the options for making a request
* @param {{ [key: string]: any }} options - The options key value pair
* @returns The same GraphRequest instance that is being called with
*/
options(options: {
[key: string]: any;
}): this;
parsePath(rawPath: string): void;
private urlJoin;
buildFullUrl(): string;
version(v: string): GraphRequest;
}): GraphRequest;
/**
* @public
* Sets the middleware options for a request
* @param {MiddlewareOptions[]} options - The array of middleware options
* @returns The same GraphRequest instance that is being called with
*/
middlewareOptions(options: MiddlewareOptions[]): GraphRequest;
/**
* @public
* Sets the api endpoint version for a request
* @param {string} version - The version value
* @returns The same GraphRequest instance that is being called with
*/
version(version: string): GraphRequest;
/**
* @public
* Sets the api endpoint version for a request
* @param {ResponseType} responseType - The response type value
* @returns The same GraphRequest instance that is being called with
*/
responseType(responseType: ResponseType): GraphRequest;
/**
* @public
* To add properties for select OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with
*/
select(properties: string | string[]): GraphRequest;
/**
* @public
* To add properties for expand OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with
*/
expand(properties: string | string[]): GraphRequest;
/**
* @public
* To add properties for orderby OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with
*/
orderby(properties: string | string[]): GraphRequest;
/**
* @public
* To add query string for filter OData Query param
* @param {string} filterStr - The filter query string
* @returns The same GraphRequest instance that is being called with
*/
filter(filterStr: string): GraphRequest;
/**
* @public
* To add criterion for search OData Query param
* @param {string} searchStr - The search criterion string
* @returns The same GraphRequest instance that is being called with
*/
search(searchStr: string): GraphRequest;
filter(filterStr: string): GraphRequest;
/**
* @public
* To add number for top OData Query param
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with
*/
top(n: number): GraphRequest;
/**
* @public
* To add number for skip OData Query param
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with
*/
skip(n: number): GraphRequest;
/**
* @public
* To add token string for skipToken OData Query param
* @param {string} token - The token value
* @returns The same GraphRequest instance that is being called with
*/
skipToken(token: string): GraphRequest;
count(count: boolean): GraphRequest;
responseType(responseType: string): GraphRequest;
private addCsvQueryParameter;
delete(callback?: GraphRequestCallback): Promise<any>;
/**
* Alias for delete call
* @public
* To add boolean for count OData Query param
* @param {boolean} isCount - The count boolean
* @returns The same GraphRequest instance that is being called with
*/
del(callback?: GraphRequestCallback): Promise<any>;
patch(content: any, callback?: GraphRequestCallback): Promise<any>;
count(isCount: boolean): GraphRequest;
/**
* @public
* Appends query string to the urlComponent
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query value
* @returns The same GraphRequest instance that is being called with
*/
query(queryDictionaryOrString: string | KeyValuePairObjectStringNumber): GraphRequest;
/**
* @public
* @async
* Makes a http request with GET method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the get response
*/
get(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes a http request with POST method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
post(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* Alias for Post call
* @public
* @async
* Alias for Post request call
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
create(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes http request with PUT method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the put response
*/
put(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* Alias for update call
* @public
* @async
* Makes http request with PATCH method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
patch(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Alias for PATCH request
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
update(content: any, callback?: GraphRequestCallback): Promise<any>;
get(callback?: GraphRequestCallback): Promise<any>;
getStream(callback: GraphRequestCallback): Promise<any>;
putStream(stream: any, callback: GraphRequestCallback): Promise<any>;
/**
* @private
* Sends request and routes response to the callback or resolves to promise
* @param {RequestInfo} request - The Request object or url string value
* @param {FetchOptions} options - The options for the fetch api request
* @param {GraphRequestCallback} callback - The callback that needs to be called on response
* @return The promise in case if the callback param is empty
* @public
* @async
* Makes http request with DELETE method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
private sendRequestAndRouteResponse;
delete(callback?: GraphRequestCallback): Promise<any>;
/**
* @private
* Gets the Promise that will resolve or reject with fetch api request
* @param {RequestInfo} request - The Request object or url string value
* @param {FetchOptions} options - The options for the fetch api request
* @return The Promise that resolves with Response
* @public
* @async
* Alias for delete request call
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
private routeResponseToPromise;
del(callback?: GraphRequestCallback): Promise<any>;
/**
* @private
* Makes request to the service by getting auth token from the auth provider
* @param {RequestInfo} request - The Request object or url string value
* @param {FetchOptions} options - The options for the fetch api request
* @param {GraphRequestCallback} callback - The callback function
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the getStream response
*/
private routeResponseToCallback;
getStream(callback?: GraphRequestCallback): Promise<any>;
/**
* @private
* Customizes the fetch options with the Auth token, SDKVersion header and customization applied via init, .header, .headers, .option, .options etc
* @param {FetchOptions} options - The options for the fetch api request
* @param {string} accessToken - The access token value
* @return The fetch options with customization
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {any} stream - The stream instance
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the putStream response
*/
private configureRequestOptions;
query(queryDictionaryOrString: string | {
[key: string]: string | number;
}): GraphRequest;
private createQueryString;
private parseDocumentResponse;
private convertResponseType;
putStream(stream: any, callback?: GraphRequestCallback): Promise<any>;
}
export {};
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
var es6_promise_1 = require("es6-promise");
require("isomorphic-fetch");
var common_1 = require("./common");
var ResponseHandler_1 = require("./ResponseHandler");
var tslib_1 = require("tslib");
/**
* @module GraphRequest
*/
var Constants_1 = require("./Constants");
var GraphErrorHandler_1 = require("./GraphErrorHandler");
var GraphRequestUtil_1 = require("./GraphRequestUtil");
var GraphResponseHandler_1 = require("./GraphResponseHandler");
var MiddlewareControl_1 = require("./middleware/MiddlewareControl");
var RequestMethod_1 = require("./RequestMethod");
var ResponseType_1 = require("./ResponseType");
var GraphHelper_1 = require("./GraphHelper");
/**
* @class
* A Class representing GraphRequest
*/
var GraphRequest = /** @class */ (function () {
function GraphRequest(config, path) {
var self = this;
self.config = config;
self._options = {};
self._headers = {};
self.urlComponents = {
host: self.config.baseUrl,
version: self.config.defaultVersion,
/* tslint:enable: variable-name */
/**
* @public
* @constructor
* Creates an instance of GraphRequest
* @param {HTTPClient} httpClient - The HTTPClient instance
* @param {ClientOptions} config - The options for making request
* @param {string} path - A path string
*/
function GraphRequest(httpClient, config, path) {
var _this = this;
/**
* @private
* Parses the path string and creates URLComponents out of it
* @param {string} path - The request path string
* @returns Nothing
*/
this.parsePath = function (path) {
// Strips out the base of the url if they passed in
if (path.indexOf("https://") !== -1) {
path = path.replace("https://", "");
// Find where the host ends
var endOfHostStrPos = path.indexOf("/");
if (endOfHostStrPos !== -1) {
// Parse out the host
_this.urlComponents.host = "https://" + path.substring(0, endOfHostStrPos);
// Strip the host from path
path = path.substring(endOfHostStrPos + 1, path.length);
}
// Remove the following version
var endOfVersionStrPos = path.indexOf("/");
if (endOfVersionStrPos !== -1) {
// Parse out the version
_this.urlComponents.version = path.substring(0, endOfVersionStrPos);
// Strip version from path
path = path.substring(endOfVersionStrPos + 1, path.length);
}
}
// Strip out any leading "/"
if (path.charAt(0) === "/") {
path = path.substr(1);
}
var queryStrPos = path.indexOf("?");
if (queryStrPos === -1) {
// No query string
_this.urlComponents.path = path;
}
else {
_this.urlComponents.path = path.substr(0, queryStrPos);
// Capture query string into oDataQueryParams and otherURLQueryParams
var queryParams = path.substring(queryStrPos + 1, path.length).split("&");
for (var _i = 0, queryParams_1 = queryParams; _i < queryParams_1.length; _i++) {
var queryParam = queryParams_1[_i];
var qParams = queryParam.split("=");
var key = qParams[0];
var value = qParams[1];
if (GraphRequestUtil_1.oDataQueryNames.indexOf(key) !== -1) {
_this.urlComponents.oDataQueryParams[key] = value;
}
else {
_this.urlComponents.otherURLQueryParams[key] = value;
}
}
}
};
this.httpClient = httpClient;
this.config = config;
this.urlComponents = {
host: this.config.baseUrl,
version: this.config.defaultVersion,
oDataQueryParams: {},
otherURLQueryParams: {}
otherURLQueryParams: {},
};
self.parsePath(path);
this._headers = {};
this._options = {};
this._middlewareOptions = [];
this.parsePath(path);
}
/**
* @private
* Adds the query parameter as comma separated values
* @param {string} propertyName - The name of a property
* @param {string|string[]} propertyValue - The vale of a property
* @param {IArguments} additionalProperties - The additional properties
* @returns Nothing
*/
GraphRequest.prototype.addCsvQueryParameter = function (propertyName, propertyValue, additionalProperties) {
// If there are already $propertyName value there, append a ","
this.urlComponents.oDataQueryParams[propertyName] = this.urlComponents.oDataQueryParams[propertyName] ? this.urlComponents.oDataQueryParams[propertyName] + "," : "";
var allValues = [];
if (additionalProperties.length > 1 && typeof propertyValue === "string") {
allValues = Array.prototype.slice.call(additionalProperties);
}
else if (typeof propertyValue === "string") {
allValues.push(propertyValue);
}
else {
allValues = allValues.concat(propertyValue);
}
this.urlComponents.oDataQueryParams[propertyName] += allValues.join(",");
};
/**
* @private
* Builds the full url from the URLComponents to make a request
* @returns The URL string that is qualified to make a request to graph endpoint
*/
GraphRequest.prototype.buildFullUrl = function () {
var url = GraphRequestUtil_1.urlJoin([this.urlComponents.host, this.urlComponents.version, this.urlComponents.path]) + this.createQueryString();
if (this.config.debugLogging) {
console.log(url); // tslint:disable-line: no-console
}
return url;
};
/**
* @private
* Builds the query string from the URLComponents
* @returns The Constructed query string
*/
GraphRequest.prototype.createQueryString = function () {
// Combining query params from oDataQueryParams and otherURLQueryParams
var urlComponents = this.urlComponents;
var query = [];
if (Object.keys(urlComponents.oDataQueryParams).length !== 0) {
for (var property in urlComponents.oDataQueryParams) {
if (urlComponents.oDataQueryParams.hasOwnProperty(property)) {
query.push(property + "=" + urlComponents.oDataQueryParams[property]);
}
}
}
if (Object.keys(urlComponents.otherURLQueryParams).length !== 0) {
for (var property in urlComponents.otherURLQueryParams) {
if (urlComponents.otherURLQueryParams.hasOwnProperty(property)) {
query.push(property + "=" + urlComponents.otherURLQueryParams[property]);
}
}
}
return query.length > 0 ? "?" + query.join("&") : "";
};
/**
* @private
* Updates the custom headers and options for a request
* @param {FetchOptions} options - The request options object
* @returns Nothing
*/
GraphRequest.prototype.updateRequestOptions = function (options) {
var defaultHeaders = {
SdkVersion: "graph-js-" + Constants_1.PACKAGE_VERSION,
};
var optionsHeaders = tslib_1.__assign({}, options.headers);
if (this.config.fetchOptions !== undefined) {
var fetchOptions = tslib_1.__assign({}, this.config.fetchOptions);
Object.assign(options, fetchOptions);
if (typeof this.config.fetchOptions.headers !== undefined) {
options.headers = tslib_1.__assign({}, this.config.fetchOptions.headers);
}
}
Object.assign(options, this._options);
Object.assign(optionsHeaders, defaultHeaders);
if (options.headers !== undefined) {
Object.assign(optionsHeaders, options.headers);
}
Object.assign(optionsHeaders, this._headers);
options.headers = optionsHeaders;
};
/**
* @private
* @async
* Adds the custom headers and options to the request and makes the HTTPClient send request call
* @param {RequestInfo} request - The request url string or the Request object value
* @param {FetchOptions} options - The options to make a request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the response content
*/
GraphRequest.prototype.send = function (request, options, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var rawResponse, middlewareControl, context_1, response, error_1, statusCode, gError;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
middlewareControl = new MiddlewareControl_1.MiddlewareControl(this._middlewareOptions);
this.updateRequestOptions(options);
_a.label = 1;
case 1:
_a.trys.push([1, 4, , 6]);
return [4 /*yield*/, this.httpClient.sendRequest({
request: request,
options: options,
middlewareControl: middlewareControl,
})];
case 2:
context_1 = _a.sent();
rawResponse = context_1.response;
return [4 /*yield*/, GraphResponseHandler_1.GraphResponseHandler.getResponse(rawResponse, this._responseType, callback)];
case 3:
response = _a.sent();
return [2 /*return*/, response];
case 4:
error_1 = _a.sent();
statusCode = void 0;
if (typeof rawResponse !== "undefined") {
statusCode = rawResponse.status;
}
return [4 /*yield*/, GraphErrorHandler_1.GraphErrorHandler.getError(error_1, statusCode, callback)];
case 5:
gError = _a.sent();
throw gError;
case 6: return [2 /*return*/];
}
});
});
};
/**
* @public
* Sets the custom header for a request
* @param {string} headerKey - A header key
* @param {string} headerValue - A header value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.header = function (headerKey, headerValue) {
var self = this;
self._headers[headerKey] = headerValue;
return self;
this._headers[headerKey] = headerValue;
return this;
};
/**
* @public
* Sets the custom headers for a request
* @param {KeyValuePairObjectStringNumber} headers - The headers key value pair object
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.headers = function (headers) {
var self = this;
for (var key in headers) {
self._headers[key] = headers[key];
if (headers.hasOwnProperty(key)) {
this._headers[key] = headers[key];
}
}
return self;
return this;
};
/**
* @public
* Sets the option for making a request
* @param {string} key - The key value
* @param {any} value - The value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.option = function (key, value) {
var self = this;
self._options[key] = value;
return self;
this._options[key] = value;
return this;
};
/**
* @public
* Sets the options for making a request
* @param {{ [key: string]: any }} options - The options key value pair
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.options = function (options) {
var self = this;
for (var key in options) {
self._options[key] = options[key];
}
return self;
};
GraphRequest.prototype.parsePath = function (rawPath) {
// break rawPath into this.urlComponents
// strip out the base url if they passed it in
if (rawPath.indexOf("https://") != -1) {
rawPath = rawPath.replace("https://", "");
// find where the host ends
var endOfHostStrPos = rawPath.indexOf("/");
this.urlComponents.host = "https://" + rawPath.substring(0, endOfHostStrPos); // parse out the host
// strip the host from rawPath
rawPath = rawPath.substring(endOfHostStrPos + 1, rawPath.length);
// then remove the following version
var endOfVersionStrPos = rawPath.indexOf("/");
// parse out the version
this.urlComponents.version = rawPath.substring(0, endOfVersionStrPos);
// strip version from rawPath
rawPath = rawPath.substring(endOfVersionStrPos + 1, rawPath.length);
}
// strip out any leading "/"
if (rawPath.charAt(0) == "/") {
rawPath = rawPath.substr(1);
}
var queryStrPos = rawPath.indexOf("?");
// let afterPath =
if (queryStrPos == -1) {
// no query string
this.urlComponents.path = rawPath;
}
else {
this.urlComponents.path = rawPath.substr(0, queryStrPos);
// capture query string into
// this.urlComponents.oDataQueryParams
// and
// this.urlComponents.otherURLQueryParams
var queryParams = rawPath.substring(queryStrPos + 1, rawPath.length).split("&");
for (var _i = 0, queryParams_1 = queryParams; _i < queryParams_1.length; _i++) {
var queryParam = queryParams_1[_i];
//queryParam: a=b
var queryParams_2 = queryParam.split("=");
var key = queryParams_2[0];
var value = queryParams_2[1];
if (common_1.oDataQueryNames.indexOf(key)) {
this.urlComponents.oDataQueryParams[key] = value;
}
else {
this.urlComponents.otherURLQueryParams[key] = value;
}
if (options.hasOwnProperty(key)) {
this._options[key] = options[key];
}
}
return this;
};
GraphRequest.prototype.urlJoin = function (urlSegments) {
var tr = function (s) { return s.replace(/\/+$/, ''); };
var tl = function (s) { return s.replace(/^\/+/, ''); };
var joiner = function (pre, cur) { return [tr(pre), tl(cur)].join('/'); };
var parts = Array.prototype.slice.call(urlSegments);
return parts.reduce(joiner);
/**
* @public
* Sets the middleware options for a request
* @param {MiddlewareOptions[]} options - The array of middleware options
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.middlewareOptions = function (options) {
this._middlewareOptions = options;
return this;
};
GraphRequest.prototype.buildFullUrl = function () {
var url = this.urlJoin([this.urlComponents.host,
this.urlComponents.version,
this.urlComponents.path])
+ this.createQueryString();
if (this.config.debugLogging) {
console.log(url);
}
return url;
/**
* @public
* Sets the api endpoint version for a request
* @param {string} version - The version value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.version = function (version) {
this.urlComponents.version = version;
return this;
};
GraphRequest.prototype.version = function (v) {
this.urlComponents.version = v;
/**
* @public
* Sets the api endpoint version for a request
* @param {ResponseType} responseType - The response type value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.responseType = function (responseType) {
this._responseType = responseType;
return this;
};
/**
* @public
* To add properties for select OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with
*/
/*

@@ -128,2 +332,8 @@ * Accepts .select("displayName,birthday")

};
/**
* @public
* To add properties for expand OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.expand = function (properties) {

@@ -133,2 +343,8 @@ this.addCsvQueryParameter("$expand", properties, arguments);

};
/**
* @public
* To add properties for orderby OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.orderby = function (properties) {

@@ -138,158 +354,309 @@ this.addCsvQueryParameter("$orderby", properties, arguments);

};
GraphRequest.prototype.search = function (searchStr) {
this.urlComponents.oDataQueryParams["$search"] = "\"" + searchStr + "\"";
/**
* @public
* To add query string for filter OData Query param
* @param {string} filterStr - The filter query string
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.filter = function (filterStr) {
this.urlComponents.oDataQueryParams.$filter = filterStr;
return this;
};
GraphRequest.prototype.filter = function (filterStr) {
this.urlComponents.oDataQueryParams["$filter"] = filterStr;
/**
* @public
* To add criterion for search OData Query param
* @param {string} searchStr - The search criterion string
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.search = function (searchStr) {
this.urlComponents.oDataQueryParams.$search = searchStr;
return this;
};
/**
* @public
* To add number for top OData Query param
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.top = function (n) {
this.urlComponents.oDataQueryParams["$top"] = n;
this.urlComponents.oDataQueryParams.$top = n;
return this;
};
/**
* @public
* To add number for skip OData Query param
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.skip = function (n) {
this.urlComponents.oDataQueryParams["$skip"] = n;
this.urlComponents.oDataQueryParams.$skip = n;
return this;
};
/**
* @public
* To add token string for skipToken OData Query param
* @param {string} token - The token value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.skipToken = function (token) {
this.urlComponents.oDataQueryParams["$skipToken"] = token;
this.urlComponents.oDataQueryParams.$skipToken = token;
return this;
};
GraphRequest.prototype.count = function (count) {
this.urlComponents.oDataQueryParams["$count"] = count.toString();
/**
* @public
* To add boolean for count OData Query param
* @param {boolean} isCount - The count boolean
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.count = function (isCount) {
this.urlComponents.oDataQueryParams.$count = isCount.toString();
return this;
};
GraphRequest.prototype.responseType = function (responseType) {
this._responseType = responseType;
return this;
};
// helper for $select, $expand and $orderby (must be comma separated)
GraphRequest.prototype.addCsvQueryParameter = function (propertyName, propertyValue, additionalProperties) {
// if there are already $propertyName value there, append a ","
this.urlComponents.oDataQueryParams[propertyName] = this.urlComponents.oDataQueryParams[propertyName] ? this.urlComponents.oDataQueryParams[propertyName] + "," : "";
var allValues = [];
if (typeof propertyValue === "string") {
allValues.push(propertyValue);
/**
* @public
* Appends query string to the urlComponent
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.query = function (queryDictionaryOrString) {
var otherURLQueryParams = this.urlComponents.otherURLQueryParams;
if (typeof queryDictionaryOrString === "string") {
var querySplit = queryDictionaryOrString.split("=");
var queryKey = querySplit[0];
var queryValue = querySplit[1];
otherURLQueryParams[queryKey] = queryValue;
}
else { // propertyValue passed in as array
allValues = allValues.concat(propertyValue);
else {
for (var key in queryDictionaryOrString) {
if (queryDictionaryOrString.hasOwnProperty(key)) {
otherURLQueryParams[key] = queryDictionaryOrString[key];
}
}
}
// merge in additionalProperties
if (additionalProperties.length > 1 && typeof propertyValue === "string") {
allValues = Array.prototype.slice.call(additionalProperties);
}
this.urlComponents.oDataQueryParams[propertyName] += allValues.join(",");
return this;
};
GraphRequest.prototype.delete = function (callback) {
var self = this, url = self.buildFullUrl(), options = {
method: RequestMethod_1.RequestMethod.DELETE
};
return self.sendRequestAndRouteResponse(url, options, callback);
/**
* @public
* @async
* Makes a http request with GET method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the get response
*/
GraphRequest.prototype.get = function (callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, response, error_2;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.buildFullUrl();
options = {
method: RequestMethod_1.RequestMethod.GET,
};
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.send(url, options, callback)];
case 2:
response = _a.sent();
return [2 /*return*/, response];
case 3:
error_2 = _a.sent();
throw error_2;
case 4: return [2 /*return*/];
}
});
});
};
/**
* Alias for delete call
* @public
* @async
* Makes a http request with POST method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
GraphRequest.prototype.del = function (callback) {
return this.delete(callback);
};
GraphRequest.prototype.patch = function (content, callback) {
var self = this, url = self.buildFullUrl(), options = {
method: RequestMethod_1.RequestMethod.PATCH,
body: GraphHelper_1.GraphHelper.serializeContent(content),
headers: {
"Content-Type": "application/json"
}
};
return self.sendRequestAndRouteResponse(url, options, callback);
};
GraphRequest.prototype.post = function (content, callback) {
var self = this, url = self.buildFullUrl(), options = {
method: RequestMethod_1.RequestMethod.POST,
body: GraphHelper_1.GraphHelper.serializeContent(content),
headers: (content.constructor !== undefined && content.constructor.name === "FormData") ? {} : {
"Content-Type": "application/json"
}
};
return self.sendRequestAndRouteResponse(url, options, callback);
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, response, error_3;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.buildFullUrl();
options = {
method: RequestMethod_1.RequestMethod.POST,
body: GraphRequestUtil_1.serializeContent(content),
headers: content.constructor !== undefined && content.constructor.name === "FormData"
? {}
: {
"Content-Type": "application/json",
},
};
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.send(url, options, callback)];
case 2:
response = _a.sent();
return [2 /*return*/, response];
case 3:
error_3 = _a.sent();
throw error_3;
case 4: return [2 /*return*/];
}
});
});
};
/**
* Alias for Post call
* @public
* @async
* Alias for Post request call
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
GraphRequest.prototype.create = function (content, callback) {
return this.post(content, callback);
return tslib_1.__awaiter(this, void 0, void 0, function () {
var error_4;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.post(content, callback)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
error_4 = _a.sent();
throw error_4;
case 3: return [2 /*return*/];
}
});
});
};
/**
* @public
* @async
* Makes http request with PUT method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the put response
*/
GraphRequest.prototype.put = function (content, callback) {
var self = this, url = self.buildFullUrl(), options = {
method: RequestMethod_1.RequestMethod.PUT,
body: GraphHelper_1.GraphHelper.serializeContent(content),
headers: {
"Content-Type": "application/octet-stream"
}
};
return self.sendRequestAndRouteResponse(url, options, callback);
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, response, error_5;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.buildFullUrl();
options = {
method: RequestMethod_1.RequestMethod.PUT,
body: GraphRequestUtil_1.serializeContent(content),
headers: {
"Content-Type": "application/octet-stream",
},
};
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.send(url, options, callback)];
case 2:
response = _a.sent();
return [2 /*return*/, response];
case 3:
error_5 = _a.sent();
throw error_5;
case 4: return [2 /*return*/];
}
});
});
};
/**
* Alias for update call
* @public
* @async
* Makes http request with PATCH method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
GraphRequest.prototype.update = function (content, callback) {
return this.patch(content, callback);
GraphRequest.prototype.patch = function (content, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, response, error_6;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.buildFullUrl();
options = {
method: RequestMethod_1.RequestMethod.PATCH,
body: GraphRequestUtil_1.serializeContent(content),
headers: {
"Content-Type": "application/json",
},
};
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.send(url, options, callback)];
case 2:
response = _a.sent();
return [2 /*return*/, response];
case 3:
error_6 = _a.sent();
throw error_6;
case 4: return [2 /*return*/];
}
});
});
};
GraphRequest.prototype.get = function (callback) {
var self = this, url = self.buildFullUrl(), options = {
method: RequestMethod_1.RequestMethod.GET
};
return self.sendRequestAndRouteResponse(url, options, callback);
};
GraphRequest.prototype.getStream = function (callback) {
var self = this, url = self.buildFullUrl(), options = {
method: RequestMethod_1.RequestMethod.GET
};
self.responseType(ResponseType_1.ResponseType.STREAM);
return self.sendRequestAndRouteResponse(url, options, callback);
};
GraphRequest.prototype.putStream = function (stream, callback) {
var self = this, url = self.buildFullUrl(), options = {
method: RequestMethod_1.RequestMethod.PUT,
headers: {
"Content-Type": "application/octet-stream",
},
body: stream
};
return self.sendRequestAndRouteResponse(url, options, callback);
};
/**
* @private
* Sends request and routes response to the callback or resolves to promise
* @param {RequestInfo} request - The Request object or url string value
* @param {FetchOptions} options - The options for the fetch api request
* @param {GraphRequestCallback} callback - The callback that needs to be called on response
* @return The promise in case if the callback param is empty
* @public
* @async
* Alias for PATCH request
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
GraphRequest.prototype.sendRequestAndRouteResponse = function (request, options, callback) {
// return a promise when Promises are supported and no callback was provided
if (callback == null && typeof es6_promise_1.Promise !== "undefined") {
return this.routeResponseToPromise(request, options);
}
else {
this.routeResponseToCallback(request, options, callback);
}
GraphRequest.prototype.update = function (content, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var error_7;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.patch(content, callback)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
error_7 = _a.sent();
throw error_7;
case 3: return [2 /*return*/];
}
});
});
};
/**
* @private
* Gets the Promise that will resolve or reject with fetch api request
* @param {RequestInfo} request - The Request object or url string value
* @param {FetchOptions} options - The options for the fetch api request
* @return The Promise that resolves with Response
* @public
* @async
* Makes http request with DELETE method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
GraphRequest.prototype.routeResponseToPromise = function (request, options) {
var _this = this;
return new es6_promise_1.Promise(function (resolve, reject) {
_this.routeResponseToCallback(request, options, function (err, body) {
if (err != null) {
reject(err);
GraphRequest.prototype.delete = function (callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, response, error_8;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.buildFullUrl();
options = {
method: RequestMethod_1.RequestMethod.DELETE,
};
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.send(url, options, callback)];
case 2:
response = _a.sent();
return [2 /*return*/, response];
case 3:
error_8 = _a.sent();
throw error_8;
case 4: return [2 /*return*/];
}
else {
resolve(body);
}
});

@@ -299,154 +666,94 @@ });

/**
* @private
* Makes request to the service by getting auth token from the auth provider
* @param {RequestInfo} request - The Request object or url string value
* @param {FetchOptions} options - The options for the fetch api request
* @param {GraphRequestCallback} callback - The callback function
* @public
* @async
* Alias for delete request call
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
GraphRequest.prototype.routeResponseToCallback = function (request, options, callback) {
var _this = this;
if (callback === void 0) { callback = function () { }; }
var self = this;
self.config.authProvider(function (err, accessToken) {
if (err == null && accessToken != null) {
options = self.configureRequestOptions(options, accessToken);
fetch(request, options).then(function (response) {
_this.convertResponseType(response).then(function (responseValue) {
ResponseHandler_1.ResponseHandler.init(response, undefined, responseValue, callback);
}).catch(function (error) {
ResponseHandler_1.ResponseHandler.init(response, error, undefined, callback);
});
}).catch(function (error) {
ResponseHandler_1.ResponseHandler.init(undefined, error, undefined, callback);
});
}
else {
callback(err, null, null);
}
GraphRequest.prototype.del = function (callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var error_9;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.delete(callback)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
error_9 = _a.sent();
throw error_9;
case 3: return [2 /*return*/];
}
});
});
};
/**
* @private
* Customizes the fetch options with the Auth token, SDKVersion header and customization applied via init, .header, .headers, .option, .options etc
* @param {FetchOptions} options - The options for the fetch api request
* @param {string} accessToken - The access token value
* @return The fetch options with customization
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the getStream response
*/
GraphRequest.prototype.configureRequestOptions = function (options, accessToken) {
var self = this, defaultHeaders = {
Authorization: "Bearer " + accessToken,
SdkVersion: "graph-js-" + common_1.PACKAGE_VERSION
};
var configuredOptions = {
headers: {}
};
Object.assign(configuredOptions, self.config.fetchOptions, self._options, options);
Object.assign(configuredOptions.headers, defaultHeaders, self._headers, options.headers);
return configuredOptions;
};
// append query strings to the url, accepts either a string like $select=displayName or a dictionary {"$select": "displayName"}
GraphRequest.prototype.query = function (queryDictionaryOrString) {
if (typeof queryDictionaryOrString === "string") { // is string
var queryStr = queryDictionaryOrString;
var queryKey = queryStr.split("=")[0];
var queryValue = queryStr.split("=")[1];
this.urlComponents.otherURLQueryParams[queryKey] = queryValue;
}
else { // is dictionary
for (var key in queryDictionaryOrString) {
this.urlComponents.otherURLQueryParams[key] = queryDictionaryOrString[key];
}
}
return this;
};
// ex: ?$select=displayName&$filter=startsWith(displayName, 'A')
// does not include starting ?
GraphRequest.prototype.createQueryString = function () {
// need to combine first this.urlComponents.oDataQueryParams and this.urlComponents.otherURLQueryParams
var q = [];
if (Object.keys(this.urlComponents.oDataQueryParams).length != 0) {
for (var property in this.urlComponents.oDataQueryParams) {
q.push(property + "=" + this.urlComponents.oDataQueryParams[property]);
}
}
if (Object.keys(this.urlComponents.otherURLQueryParams).length != 0) {
for (var property in this.urlComponents.otherURLQueryParams) {
q.push(property + "=" + this.urlComponents.otherURLQueryParams[property]);
}
}
if (q.length > 0) {
return "?" + q.join("&");
}
return "";
};
GraphRequest.prototype.parseDocumentResponse = function (response, type) {
if (typeof DOMParser !== "undefined") {
return new es6_promise_1.Promise(function (resolve, reject) {
response.text().then(function (xmlString) {
try {
var parser = new DOMParser(), xmlDoc = parser.parseFromString(xmlString, type);
resolve(xmlDoc);
}
catch (error) {
reject(error);
}
});
GraphRequest.prototype.getStream = function (callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, stream, error_10;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.buildFullUrl();
options = {
method: RequestMethod_1.RequestMethod.GET,
};
this.responseType(ResponseType_1.ResponseType.STREAM);
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.send(url, options, callback)];
case 2:
stream = _a.sent();
return [2 /*return*/, stream];
case 3:
error_10 = _a.sent();
throw error_10;
case 4: return [2 /*return*/];
}
});
}
else {
return es6_promise_1.Promise.resolve(response.body);
}
});
};
GraphRequest.prototype.convertResponseType = function (response) {
var self = this, responseValue;
if (!self._responseType) {
self._responseType = '';
}
switch (self._responseType.toLowerCase()) {
case ResponseType_1.ResponseType.ARRAYBUFFER:
responseValue = response.arrayBuffer();
break;
case ResponseType_1.ResponseType.BLOB:
responseValue = response.blob();
break;
case ResponseType_1.ResponseType.DOCUMENT:
responseValue = self.parseDocumentResponse(response, "text/xml");
break;
case ResponseType_1.ResponseType.JSON:
responseValue = response.json();
break;
case ResponseType_1.ResponseType.STREAM:
responseValue = es6_promise_1.Promise.resolve(response.body);
break;
case ResponseType_1.ResponseType.TEXT:
responseValue = response.text();
break;
default:
var contentType = response.headers.get("Content-type");
if (contentType !== null) {
var mimeType = contentType.split(";")[0], documentContentTypes = ["text/html", "text/xml", "application/xml", "application/xhtml+xml"];
if (documentContentTypes.includes(mimeType)) {
responseValue = self.parseDocumentResponse(response, mimeType);
}
else {
responseValue = response.json();
}
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {any} stream - The stream instance
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the putStream response
*/
GraphRequest.prototype.putStream = function (stream, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, response, error_11;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.buildFullUrl();
options = {
method: RequestMethod_1.RequestMethod.PUT,
headers: {
"Content-Type": "application/octet-stream",
},
body: stream,
};
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.send(url, options, callback)];
case 2:
response = _a.sent();
return [2 /*return*/, response];
case 3:
error_11 = _a.sent();
throw error_11;
case 4: return [2 /*return*/];
}
else {
/**
* RFC specification {@link https://tools.ietf.org/html/rfc7231#section-3.1.1.5} says:
* A sender that generates a message containing a payload body SHOULD
* generate a Content-Type header field in that message unless the
* intended media type of the enclosed representation is unknown to the
* sender. If a Content-Type header field is not present, the recipient
* MAY either assume a media type of "application/octet-stream"
* ([RFC2046], Section 4.5.1) or examine the data to determine its type.
*
* So assuming it as a stream type so returning the body.
*/
responseValue = es6_promise_1.Promise.resolve(response.body);
}
break;
}
return responseValue;
});
});
};

@@ -453,0 +760,0 @@ return GraphRequest;

@@ -1,15 +0,30 @@

import { Options } from "./common";
import { GraphRequest } from "./GraphRequest";
export declare class Client {
config: Options;
static init(clientOptions?: Options): Client;
api(path: string): GraphRequest;
}
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export * from "./content/BatchRequestContent";
export * from "./content/BatchResponseContent";
export * from "./middleware/AuthenticationHandler";
export * from "./middleware/HTTPMessageHandler";
export * from "./middleware/IMiddleware";
export * from "./middleware/RetryHandler";
export * from "./middleware/options/AuthenticationHandlerOptions";
export * from "./middleware/options/IMiddlewareOptions";
export * from "./middleware/options/RetryHandlerOptions";
export * from "./tasks/OneDriveLargeFileUploadTask";
export * from "./tasks/PageIterator";
export * from "./Client";
export * from "./GraphError";
export * from "./GraphRequest";
export * from "./common";
export * from "./IAuthProvider";
export * from "./IAuthenticationProvider";
export * from "./IAuthenticationProviderOptions";
export * from "./IAuthProviderCallback";
export * from "./IClientOptions";
export * from "./IContext";
export * from "./IFetchOptions";
export * from "./IGraphRequestCallback";
export * from "./IOptions";
export * from "./ResponseType";
export * from "./ResponseHandler";
export * from "./tasks/OneDriveLargeFileUploadTask";
export * from "./tasks/PageIterator";
export * from "./content/BatchRequestContent";
export * from "./content/BatchResponseContent";
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
var common_1 = require("./common");
var GraphRequest_1 = require("./GraphRequest");
var Client = /** @class */ (function () {
function Client() {
// specify client defaults
this.config = {
debugLogging: false,
defaultVersion: common_1.DEFAULT_VERSION,
baseUrl: common_1.GRAPH_BASE_URL
};
}
Client.init = function (clientOptions) {
var graphClient = new Client();
for (var key in clientOptions) {
graphClient.config[key] = clientOptions[key];
}
return graphClient;
};
/*
* Entry point for calling api
*/
Client.prototype.api = function (path) {
return new GraphRequest_1.GraphRequest(this.config, path);
};
return Client;
}());
exports.Client = Client;
__export(require("./GraphRequest"));
__export(require("./common"));
__export(require("./ResponseType"));
__export(require("./ResponseHandler"));
__export(require("./tasks/OneDriveLargeFileUploadTask"));
__export(require("./tasks/PageIterator"));
__export(require("./content/BatchRequestContent"));
__export(require("./content/BatchResponseContent"));
var tslib_1 = require("tslib");
var PolyFill_1 = require("./PolyFill");
/**
* Polyfilling Promise and fetch if not present
*/
PolyFill_1.init();
tslib_1.__exportStar(require("./content/BatchRequestContent"), exports);
tslib_1.__exportStar(require("./content/BatchResponseContent"), exports);
tslib_1.__exportStar(require("./middleware/AuthenticationHandler"), exports);
tslib_1.__exportStar(require("./middleware/HTTPMessageHandler"), exports);
tslib_1.__exportStar(require("./middleware/RetryHandler"), exports);
tslib_1.__exportStar(require("./middleware/options/AuthenticationHandlerOptions"), exports);
tslib_1.__exportStar(require("./middleware/options/RetryHandlerOptions"), exports);
tslib_1.__exportStar(require("./tasks/OneDriveLargeFileUploadTask"), exports);
tslib_1.__exportStar(require("./tasks/PageIterator"), exports);
tslib_1.__exportStar(require("./Client"), exports);
tslib_1.__exportStar(require("./GraphError"), exports);
tslib_1.__exportStar(require("./GraphRequest"), exports);
tslib_1.__exportStar(require("./ResponseType"), exports);
//# sourceMappingURL=index.js.map
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module Range
*/
/**
* Class representing Range
*/
* @class
* Class representing Range
*/
export declare class Range {
/** The minimum value of the range */
/**
* @public
* The minimum value of the range
*/
minValue: number;
/** The maximum value of the range */
/**
* @public
* The maximum value of the range
*/
maxValue: number;
/**
* @public
* @constructor
* Creates a range for given min and max values
* @param {number} [minVal = -1] - The minimum value.
* @param {number} [maxVal = -1] - The maximum value.
* @returns An instance of a Range
*/
constructor(minVal?: number, maxVal?: number);
}
"use strict";
/**
* @module Range
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Class representing Range
*/
* @module Range
*/
/**
* @class
* Class representing Range
*/
var Range = /** @class */ (function () {
/**
* @public
* @constructor
* Creates a range for given min and max values
* @param {number} [minVal = -1] - The minimum value.
* @param {number} [maxVal = -1] - The maximum value.
* @returns An instance of a Range
*/

@@ -18,5 +28,4 @@ function Range(minVal, maxVal) {

if (maxVal === void 0) { maxVal = -1; }
var self = this;
self.minValue = minVal;
self.maxValue = maxVal;
this.minValue = minVal;
this.maxValue = maxVal;
}

@@ -23,0 +32,0 @@ return Range;

@@ -0,1 +1,16 @@

/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @enum
* Enum for RequestMethods
* @property {string} GET - The get request type
* @property {string} PATCH - The patch request type
* @property {string} POST - The post request type
* @property {string} PUT - The put request type
* @property {string} DELETE - The delete request type
*/
export declare enum RequestMethod {

@@ -2,0 +17,0 @@ GET = "GET",

"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @enum
* Enum for RequestMethods
* @property {string} GET - The get request type
* @property {string} PATCH - The patch request type
* @property {string} POST - The post request type
* @property {string} PUT - The put request type
* @property {string} DELETE - The delete request type
*/
var RequestMethod;

@@ -4,0 +19,0 @@ (function (RequestMethod) {

/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @enum

@@ -6,3 +12,3 @@ * Enum for ResponseType values

* @property {string} BLOB - To download content as a [binary/blob] {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob}
* @property {string} DOCUMENT - This downloads content as a json, See [this for more info]{@link https://github.com/microsoftgraph/msgraph-sdk-javascript/pull/63}
* @property {string} DOCUMENT - This downloads content as a document or stream
* @property {string} JSON - To download response content as a json

@@ -17,4 +23,5 @@ * @property {string} STREAM - To download response as a [stream]{@link https://nodejs.org/api/stream.html}

JSON = "json",
RAW = "raw",
STREAM = "stream",
TEXT = "text"
}
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @enum

@@ -7,3 +14,3 @@ * Enum for ResponseType values

* @property {string} BLOB - To download content as a [binary/blob] {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob}
* @property {string} DOCUMENT - This downloads content as a json, See [this for more info]{@link https://github.com/microsoftgraph/msgraph-sdk-javascript/pull/63}
* @property {string} DOCUMENT - This downloads content as a document or stream
* @property {string} JSON - To download response content as a json

@@ -13,3 +20,2 @@ * @property {string} STREAM - To download response as a [stream]{@link https://nodejs.org/api/stream.html}

*/
Object.defineProperty(exports, "__esModule", { value: true });
var ResponseType;

@@ -21,2 +27,3 @@ (function (ResponseType) {

ResponseType["JSON"] = "json";
ResponseType["RAW"] = "raw";
ResponseType["STREAM"] = "stream";

@@ -23,0 +30,0 @@ ResponseType["TEXT"] = "text";

/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module LargeFileUploadTask

@@ -47,20 +53,39 @@ */

/**
* @class
* Class representing LargeFileUploadTask
*/
export declare class LargeFileUploadTask {
/** The GraphClient instance */
client: Client;
/** The object holding file details */
file: FileObject;
/** The object holding options for the task */
options: LargeFileUploadTaskOptions;
/** The object for upload session */
uploadSession: LargeFileUploadSession;
/** The next range needs to be uploaded */
nextRange: Range;
/**
* Default value for the rangeSize
*/
* @private
* Default value for the rangeSize
*/
private DEFAULT_FILE_SIZE;
/**
* @protected
* The GraphClient instance
*/
protected client: Client;
/**
* @protected
* The object holding file details
*/
protected file: FileObject;
/**
* @protected
* The object holding options for the task
*/
protected options: LargeFileUploadTaskOptions;
/**
* @protected
* The object for upload session
*/
protected uploadSession: LargeFileUploadSession;
/**
* @protected
* The next range needs to be uploaded
*/
protected nextRange: Range;
/**
* @public
* @constructor
* Constructs a LargeFileUploadTask

@@ -71,33 +96,41 @@ * @param {Client} client - The GraphClient instance

* @param {LargeFileUploadTaskOptions} options - The upload task options
* @returns An instance of LargeFileUploadTask
*/
constructor(client: Client, file: FileObject, uploadSession: LargeFileUploadSession, options: LargeFileUploadTaskOptions);
/**
* @public
* Parses given range string to the Range instance
* @param {string[]} ranges - The ranges value
* @return The range instance
* @returns The range instance
*/
parseRange(ranges: string[]): Range;
/**
* @public
* Updates the expiration date and the next range
* @param {UploadStatusResponse} response - The response of the upload status
* @returns Nothing
*/
updateTaskStatus(response: UploadStatusResponse): void;
/**
* @public
* Gets next range that needs to be uploaded
* @return The range instance
* @returns The range instance
*/
getNextRange(): Range;
/**
* @public
* Slices the file content to the given range
* @param {Range} range - The range value
* @return The sliced ArrayBuffer or Blob
* @returns The sliced ArrayBuffer or Blob
*/
sliceFile(range: Range): ArrayBuffer | Blob;
/**
* @public
* @async
* Uploads file to the server in a sequential order by slicing the file
* @return The promise resolves to uploaded response
* @returns The promise resolves to uploaded response
*/
upload(): Promise<any>;
/**
* @public
* @async

@@ -111,17 +144,20 @@ * Uploads given slice to the server

/**
* @public
* @async
* Deletes upload session in the server
* @return The promise resolves to cancelled response
* @returns The promise resolves to cancelled response
*/
cancel(): Promise<any>;
/**
* @public
* @async
* Gets status for the upload session
* @return The promise resolves to the status enquiry response
* @returns The promise resolves to the status enquiry response
*/
getStatus(): Promise<any>;
/**
* @public
* @async
* Resumes upload session and continue uploading the file from the last sent range
* @return The promise resolves to the uploaded response
* @returns The promise resolves to the uploaded response
*/

@@ -128,0 +164,0 @@ resume(): Promise<any>;

"use strict";
/**
* @module LargeFileUploadTask
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var Range_1 = require("../Range");
;
/**
* @class
* Class representing LargeFileUploadTask

@@ -48,2 +17,4 @@ */

/**
* @public
* @constructor
* Constructs a LargeFileUploadTask

@@ -54,22 +25,24 @@ * @param {Client} client - The GraphClient instance

* @param {LargeFileUploadTaskOptions} options - The upload task options
* @returns An instance of LargeFileUploadTask
*/
function LargeFileUploadTask(client, file, uploadSession, options) {
/**
* Default value for the rangeSize
*/
* @private
* Default value for the rangeSize
*/
this.DEFAULT_FILE_SIZE = 5 * 1024 * 1024;
var self = this;
self.client = client;
self.file = file;
this.client = client;
this.file = file;
if (options.rangeSize === undefined) {
options.rangeSize = self.DEFAULT_FILE_SIZE;
options.rangeSize = this.DEFAULT_FILE_SIZE;
}
self.options = options;
self.uploadSession = uploadSession;
self.nextRange = new Range_1.Range(0, self.options.rangeSize - 1);
this.options = options;
this.uploadSession = uploadSession;
this.nextRange = new Range_1.Range(0, this.options.rangeSize - 1);
}
/**
* @public
* Parses given range string to the Range instance
* @param {string[]} ranges - The ranges value
* @return The range instance
* @returns The range instance
*/

@@ -81,3 +54,5 @@ LargeFileUploadTask.prototype.parseRange = function (ranges) {

}
var firstRange = rangeStr.split("-"), minVal = parseInt(firstRange[0]), maxVal = parseInt(firstRange[1]);
var firstRange = rangeStr.split("-");
var minVal = parseInt(firstRange[0], 10);
var maxVal = parseInt(firstRange[1], 10);
if (Number.isNaN(maxVal)) {

@@ -89,22 +64,24 @@ maxVal = this.file.size - 1;

/**
* @public
* Updates the expiration date and the next range
* @param {UploadStatusResponse} response - The response of the upload status
* @returns Nothing
*/
LargeFileUploadTask.prototype.updateTaskStatus = function (response) {
var self = this;
self.uploadSession.expiry = new Date(response.expirationDateTime);
self.nextRange = self.parseRange(response.nextExpectedRanges);
this.uploadSession.expiry = new Date(response.expirationDateTime);
this.nextRange = this.parseRange(response.nextExpectedRanges);
};
/**
* @public
* Gets next range that needs to be uploaded
* @return The range instance
* @returns The range instance
*/
LargeFileUploadTask.prototype.getNextRange = function () {
var self = this;
if (self.nextRange.minValue === -1) {
return self.nextRange;
if (this.nextRange.minValue === -1) {
return this.nextRange;
}
var minVal = self.nextRange.minValue, maxValue = minVal + self.options.rangeSize - 1;
if (maxValue >= self.file.size) {
maxValue = self.file.size - 1;
var minVal = this.nextRange.minValue;
var maxValue = minVal + this.options.rangeSize - 1;
if (maxValue >= this.file.size) {
maxValue = this.file.size - 1;
}

@@ -114,5 +91,6 @@ return new Range_1.Range(minVal, maxValue);

/**
* @public
* Slices the file content to the given range
* @param {Range} range - The range value
* @return The sliced ArrayBuffer or Blob
* @returns The sliced ArrayBuffer or Blob
*/

@@ -124,20 +102,18 @@ LargeFileUploadTask.prototype.sliceFile = function (range) {

/**
* @public
* @async
* Uploads file to the server in a sequential order by slicing the file
* @return The promise resolves to uploaded response
* @returns The promise resolves to uploaded response
*/
LargeFileUploadTask.prototype.upload = function () {
return __awaiter(this, void 0, void 0, function () {
var self, nextRange, err, fileSlice, response, err_1;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var nextRange, err, fileSlice, response, err_1;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
_a.trys.push([0, 4, , 5]);
_a.label = 1;
case 1:
_a.trys.push([1, 5, , 6]);
_a.label = 2;
case 2:
if (!true) return [3 /*break*/, 4];
nextRange = self.getNextRange();
if (!true) return [3 /*break*/, 3];
nextRange = this.getNextRange();
if (nextRange.maxValue === -1) {

@@ -148,5 +124,5 @@ err = new Error("Task with which you are trying to upload is already completed, Please check for your uploaded file");

}
fileSlice = self.sliceFile(nextRange);
return [4 /*yield*/, self.uploadSlice(fileSlice, nextRange, self.file.size)];
case 3:
fileSlice = this.sliceFile(nextRange);
return [4 /*yield*/, this.uploadSlice(fileSlice, nextRange, this.file.size)];
case 2:
response = _a.sent();

@@ -158,10 +134,10 @@ // Upon completion of upload process incase of onedrive, driveItem is returned, which contains id

else {
self.updateTaskStatus(response);
this.updateTaskStatus(response);
}
return [3 /*break*/, 2];
case 4: return [3 /*break*/, 6];
case 5:
return [3 /*break*/, 1];
case 3: return [3 /*break*/, 5];
case 4:
err_1 = _a.sent();
throw err_1;
case 6: return [2 /*return*/];
case 5: return [2 /*return*/];
}

@@ -172,2 +148,3 @@ });

/**
* @public
* @async

@@ -180,23 +157,20 @@ * Uploads given slice to the server

LargeFileUploadTask.prototype.uploadSlice = function (fileSlice, range, totalSize) {
return __awaiter(this, void 0, void 0, function () {
var self, err_2;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var err_2;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, self.client
.api(self.uploadSession.url)
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.client
.api(this.uploadSession.url)
.headers({
"Content-Length": "" + (range.maxValue - range.minValue + 1),
"Content-Range": "bytes " + range.minValue + "-" + range.maxValue + "/" + totalSize
"Content-Range": "bytes " + range.minValue + "-" + range.maxValue + "/" + totalSize,
})
.put(fileSlice)];
case 2: return [2 /*return*/, _a.sent()];
case 3:
case 1: return [2 /*return*/, _a.sent()];
case 2:
err_2 = _a.sent();
throw err_2;
case 4: return [2 /*return*/];
case 3: return [2 /*return*/];
}

@@ -207,24 +181,20 @@ });

/**
* @public
* @async
* Deletes upload session in the server
* @return The promise resolves to cancelled response
* @returns The promise resolves to cancelled response
*/
LargeFileUploadTask.prototype.cancel = function () {
return __awaiter(this, void 0, void 0, function () {
var self, err_3;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var err_3;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, self.client
.api(self.uploadSession.url)
.delete()];
case 2: return [2 /*return*/, _a.sent()];
case 3:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.client.api(this.uploadSession.url).delete()];
case 1: return [2 /*return*/, _a.sent()];
case 2:
err_3 = _a.sent();
throw err_3;
case 4: return [2 /*return*/];
case 3: return [2 /*return*/];
}

@@ -235,27 +205,23 @@ });

/**
* @public
* @async
* Gets status for the upload session
* @return The promise resolves to the status enquiry response
* @returns The promise resolves to the status enquiry response
*/
LargeFileUploadTask.prototype.getStatus = function () {
return __awaiter(this, void 0, void 0, function () {
var self, response, err_4;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var response, err_4;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
_a.label = 1;
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.client.api(this.uploadSession.url).get()];
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, self.client
.api(self.uploadSession.url)
.get()];
case 2:
response = _a.sent();
self.updateTaskStatus(response);
this.updateTaskStatus(response);
return [2 /*return*/, response];
case 3:
case 2:
err_4 = _a.sent();
throw err_4;
case 4: return [2 /*return*/];
case 3: return [2 /*return*/];
}

@@ -266,25 +232,23 @@ });

/**
* @public
* @async
* Resumes upload session and continue uploading the file from the last sent range
* @return The promise resolves to the uploaded response
* @returns The promise resolves to the uploaded response
*/
LargeFileUploadTask.prototype.resume = function () {
return __awaiter(this, void 0, void 0, function () {
var self, err_5;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var err_5;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
_a.label = 1;
_a.trys.push([0, 3, , 4]);
return [4 /*yield*/, this.getStatus()];
case 1:
_a.trys.push([1, 4, , 5]);
return [4 /*yield*/, self.getStatus()];
case 2:
_a.sent();
return [4 /*yield*/, self.upload()];
case 3: return [2 /*return*/, _a.sent()];
case 4:
return [4 /*yield*/, this.upload()];
case 2: return [2 /*return*/, _a.sent()];
case 3:
err_5 = _a.sent();
throw err_5;
case 5: return [2 /*return*/];
case 4: return [2 /*return*/];
}

@@ -291,0 +255,0 @@ });

/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/// <reference types="node" />
/**
* @module OneDriveLargeFileUploadTask
*/
/// <reference types="node" />
import { Client } from "../index";

@@ -20,2 +26,3 @@ import { FileObject, LargeFileUploadSession, LargeFileUploadTask, LargeFileUploadTaskOptions } from "./LargeFileUploadTask";

/**
* @class
* Class representing OneDriveLargeFileUploadTask

@@ -25,14 +32,9 @@ */

/**
* @private
* @static
* Default path for the file being uploaded
*/
static DEFAULT_UPLOAD_PATH: string;
private static DEFAULT_UPLOAD_PATH;
/**
* Constructs a OneDriveLargeFileUploadTask
* @param {Client} client - The GraphClient instance
* @param {FileObject} file - The FileObject holding details of a file that needs to be uploaded
* @param {LargeFileUploadSession} uploadSession - The upload session to which the upload has to be done
* @param {LargeFileUploadTaskOptions} options - The upload task options
*/
constructor(client: Client, file: FileObject, uploadSession: LargeFileUploadSession, options: LargeFileUploadTaskOptions);
/**
* @public
* @static

@@ -44,6 +46,7 @@ * @async

* @param {OneDriveLargeFileUploadOptions} options - The options for upload task
* @return The promise that will be resolves to OneDriveLargeFileUploadTask instance
* @returns The promise that will be resolves to OneDriveLargeFileUploadTask instance
*/
static create(client: Client, file: Blob | Buffer | File, options: OneDriveLargeFileUploadOptions): Promise<any>;
/**
* @public
* @static

@@ -53,6 +56,7 @@ * Constructs the create session url for Onedrive

* @param {path} [path = OneDriveLargeFileUploadTask.DEFAULT_UPLOAD_PATH] - The path for the upload
* @return The constructed create session url
* @returns The constructed create session url
*/
static constructCreateSessionUrl(fileName: string, path?: string): string;
/**
* @public
* @static

@@ -64,9 +68,21 @@ * @async

* @param {string} fileName - The name of a file to upload, (with extension)
* @return The promise that resolves to LargeFileUploadSession
* @returns The promise that resolves to LargeFileUploadSession
*/
static createUploadSession(client: Client, requestUrl: string, fileName: string): Promise<any>;
/**
* @public
* @constructor
* Constructs a OneDriveLargeFileUploadTask
* @param {Client} client - The GraphClient instance
* @param {FileObject} file - The FileObject holding details of a file that needs to be uploaded
* @param {LargeFileUploadSession} uploadSession - The upload session to which the upload has to be done
* @param {LargeFileUploadTaskOptions} options - The upload task options
* @returns An instance of OneDriveLargeFileUploadTask
*/
constructor(client: Client, file: FileObject, uploadSession: LargeFileUploadSession, options: LargeFileUploadTaskOptions);
/**
* @public
* Commits upload session to end uploading
* @param {string} requestUrl - The URL to commit the upload session
* @return The promise resolves to committed response
* @returns The promise resolves to committed response
*/

@@ -73,0 +89,0 @@ commit(requestUrl: string): Promise<any>;

"use strict";
/**
* @module OneDriveLargeFileUploadTask
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var LargeFileUploadTask_1 = require("./LargeFileUploadTask");
var OneDriveLargeFileUploadTaskUtil_1 = require("./OneDriveLargeFileUploadTaskUtil");
;
/**
* @class
* Class representing OneDriveLargeFileUploadTask
*/
var OneDriveLargeFileUploadTask = /** @class */ (function (_super) {
__extends(OneDriveLargeFileUploadTask, _super);
tslib_1.__extends(OneDriveLargeFileUploadTask, _super);
/**
* @public
* @constructor
* Constructs a OneDriveLargeFileUploadTask

@@ -65,2 +26,3 @@ * @param {Client} client - The GraphClient instance

* @param {LargeFileUploadTaskOptions} options - The upload task options
* @returns An instance of OneDriveLargeFileUploadTask
*/

@@ -71,2 +33,3 @@ function OneDriveLargeFileUploadTask(client, file, uploadSession, options) {

/**
* @public
* @static

@@ -78,26 +41,24 @@ * @async

* @param {OneDriveLargeFileUploadOptions} options - The options for upload task
* @return The promise that will be resolves to OneDriveLargeFileUploadTask instance
* @returns The promise that will be resolves to OneDriveLargeFileUploadTask instance
*/
OneDriveLargeFileUploadTask.create = function (client, file, options) {
return __awaiter(this, void 0, void 0, function () {
var fileObj, _file, b, requestUrl, session, rangeSize, err_1;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var name, content, size, b, requestUrl, session, rangeSize, fileObj, err_1;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
fileObj = {};
fileObj.name = options.fileName;
name = options.fileName;
switch (file.constructor.name) {
case "Blob":
fileObj.content = new File([file], fileObj.name);
fileObj.size = fileObj.content.size;
content = new File([file], name);
size = content.size;
break;
case "File":
_file = file;
fileObj.content = _file;
fileObj.size = _file.size;
content = file;
size = content.size;
break;
case "Buffer":
b = file;
fileObj.size = b.byteLength - b.byteOffset;
fileObj.content = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
size = b.byteLength - b.byteOffset;
content = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);
break;

@@ -113,3 +74,10 @@ }

rangeSize = OneDriveLargeFileUploadTaskUtil_1.getValidRangeSize(options.rangeSize);
return [2 /*return*/, new OneDriveLargeFileUploadTask(client, fileObj, session, { rangeSize: rangeSize })];
fileObj = {
name: name,
content: content,
size: size,
};
return [2 /*return*/, new OneDriveLargeFileUploadTask(client, fileObj, session, {
rangeSize: rangeSize,
})];
case 3:

@@ -124,2 +92,3 @@ err_1 = _a.sent();

/**
* @public
* @static

@@ -129,3 +98,3 @@ * Constructs the create session url for Onedrive

* @param {path} [path = OneDriveLargeFileUploadTask.DEFAULT_UPLOAD_PATH] - The path for the upload
* @return The constructed create session url
* @returns The constructed create session url
*/

@@ -148,2 +117,3 @@ OneDriveLargeFileUploadTask.constructCreateSessionUrl = function (fileName, path) {

/**
* @public
* @static

@@ -155,8 +125,8 @@ * @async

* @param {string} fileName - The name of a file to upload, (with extension)
* @return The promise that resolves to LargeFileUploadSession
* @returns The promise that resolves to LargeFileUploadSession
*/
OneDriveLargeFileUploadTask.createUploadSession = function (client, requestUrl, fileName) {
return __awaiter(this, void 0, void 0, function () {
var payload, session, err_2;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var payload, session, largeFileUploadSession, err_2;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {

@@ -167,4 +137,4 @@ case 0:

"@microsoft.graph.conflictBehavior": "rename",
name: fileName
}
name: fileName,
},
};

@@ -177,6 +147,7 @@ _a.label = 1;

session = _a.sent();
return [2 /*return*/, {
url: session.uploadUrl,
expiry: new Date(session.expirationDateTime)
}];
largeFileUploadSession = {
url: session.uploadUrl,
expiry: new Date(session.expirationDateTime),
};
return [2 /*return*/, largeFileUploadSession];
case 3:

@@ -191,29 +162,25 @@ err_2 = _a.sent();

/**
* @public
* Commits upload session to end uploading
* @param {string} requestUrl - The URL to commit the upload session
* @return The promise resolves to committed response
* @returns The promise resolves to committed response
*/
OneDriveLargeFileUploadTask.prototype.commit = function (requestUrl) {
return __awaiter(this, void 0, void 0, function () {
var self, payload, err_3;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var payload, err_3;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
self = this;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
_a.trys.push([0, 2, , 3]);
payload = {
name: self.file.name,
name: this.file.name,
"@microsoft.graph.conflictBehavior": "rename",
"@microsoft.graph.sourceUrl": self.uploadSession.url
"@microsoft.graph.sourceUrl": this.uploadSession.url,
};
return [4 /*yield*/, self.client
.api(requestUrl)
.put(payload)];
case 2: return [2 /*return*/, _a.sent()];
case 3:
return [4 /*yield*/, this.client.api(requestUrl).put(payload)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
err_3 = _a.sent();
throw err_3;
case 4: return [2 /*return*/];
case 3: return [2 /*return*/];
}

@@ -224,2 +191,4 @@ });

/**
* @private
* @static
* Default path for the file being uploaded

@@ -226,0 +195,0 @@ */

/**
* @module OneDriveLargeFileUploadTaskUtil
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* Get the valid rangeSize for a file slicing (validity is based on the constrains mentioned in here {@link https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession#upload-bytes-to-the-upload-session})
* @constant
* Get the valid rangeSize for a file slicing (validity is based on the constrains mentioned in here
* {@link https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession#upload-bytes-to-the-upload-session})
*
* @param {number} [rangeSize = DEFAULT_FILE_SIZE] - The rangeSize value.
* @return The valid rangeSize
* @returns The valid rangeSize
*/
export declare const getValidRangeSize: (rangeSize?: number) => number;
"use strict";
/**
* @module OneDriveLargeFileUploadTaskUtil
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @module OneDriveLargeFileUploadTaskUtil
*/
/**
* @constant
* Default value for the rangeSize

@@ -12,8 +19,9 @@ * Recommended size is between 5 - 10 MB {@link https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession#best-practices}

/**
* @constant
* Rounds off the given value to a multiple of 320 KB
* @param {number} value - The value
* @return The rounded off value
* @returns The rounded off value
*/
var roundTo320KB = function (value) {
if (value > (320 * 1024)) {
if (value > 320 * 1024) {
value = Math.floor(value / (320 * 1024)) * 320 * 1024;

@@ -24,6 +32,8 @@ }

/**
* Get the valid rangeSize for a file slicing (validity is based on the constrains mentioned in here {@link https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession#upload-bytes-to-the-upload-session})
* @constant
* Get the valid rangeSize for a file slicing (validity is based on the constrains mentioned in here
* {@link https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession#upload-bytes-to-the-upload-session})
*
* @param {number} [rangeSize = DEFAULT_FILE_SIZE] - The rangeSize value.
* @return The valid rangeSize
* @returns The valid rangeSize
*/

@@ -30,0 +40,0 @@ exports.getValidRangeSize = function (rangeSize) {

/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module PageIterator

@@ -21,6 +27,5 @@ */

*/
export interface PageIteratorCallback {
(any: any): boolean;
}
export declare type PageIteratorCallback = (data: any) => boolean;
/**
* @class
* Class for PageIterator

@@ -55,2 +60,9 @@ */

/**
* @private
* Member holding a complete/incomplete status of an iterator
*/
private complete;
/**
* @public
* @constructor
* Creates new instance for PageIterator

@@ -60,2 +72,3 @@ * @param {Client} client - The graph client instance

* @param {PageIteratorCallback} callBack - The callback function
* @returns An instance of a PageIterator
*/

@@ -66,3 +79,3 @@ constructor(client: Client, pageCollection: PageCollection, callback: PageIteratorCallback);

* Iterates over a collection by enqueuing entries one by one and kicking the callback with the enqueued entry
* @return A boolean indicating the continue flag to process next page
* @returns A boolean indicating the continue flag to process next page
*/

@@ -74,23 +87,33 @@ private iterationHelper;

* Helper to make a get request to fetch next page with nextLink url and update the page iterator instance with the returned response
* @return A promise that resolves to a response data with next page collection
* @returns A promise that resolves to a response data with next page collection
*/
private fetchAndUpdateNextPageData;
/**
* @public
* Getter to get the deltaLink in the current response
* @return A deltaLink which is being used to make delta requests in future
* @returns A deltaLink which is being used to make delta requests in future
*/
getDeltaLink(): string | undefined;
/**
* @public
* @async
* Iterates over the collection and kicks callback for each item on iteration. Fetches next set of data through nextLink and iterates over again
* This happens until the nextLink is drained out or the user responds with a red flag to continue from callback
* @return A Promise that resolves to nothing on completion and throws error incase of any discrepancy.
* @returns A Promise that resolves to nothing on completion and throws error incase of any discrepancy.
*/
iterate(): Promise<any>;
/**
* @public
* @async
* This internally calls the iterate method, It's just for more readability.
* @return A Promise that resolves to nothing on completion and throws error incase of any discrepancy
* To resume the iteration
* Note: This internally calls the iterate method, It's just for more readability.
* @returns A Promise that resolves to nothing on completion and throws error incase of any discrepancy
*/
resume(): Promise<any>;
/**
* @public
* To get the completeness status of the iterator
* @returns Boolean indicating the completeness
*/
isComplete(): boolean;
}
"use strict";
/**
* @module PageIterator
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
/**
* @class
* Class for PageIterator

@@ -46,2 +16,4 @@ */

/**
* @public
* @constructor
* Creates new instance for PageIterator

@@ -51,10 +23,11 @@ * @param {Client} client - The graph client instance

* @param {PageIteratorCallback} callBack - The callback function
* @returns An instance of a PageIterator
*/
function PageIterator(client, pageCollection, callback) {
var self = this;
self.client = client;
self.collection = pageCollection.value;
self.nextLink = pageCollection["@odata.nextLink"];
self.deltaLink = pageCollection["@odata.deltaLink"];
self.callback = callback;
this.client = client;
this.collection = pageCollection.value;
this.nextLink = pageCollection["@odata.nextLink"];
this.deltaLink = pageCollection["@odata.deltaLink"];
this.callback = callback;
this.complete = false;
}

@@ -64,13 +37,12 @@ /**

* Iterates over a collection by enqueuing entries one by one and kicking the callback with the enqueued entry
* @return A boolean indicating the continue flag to process next page
* @returns A boolean indicating the continue flag to process next page
*/
PageIterator.prototype.iterationHelper = function () {
var self = this;
if (self.collection === undefined || self.collection.length === 0) {
if (this.collection === undefined) {
return false;
}
var advance = true;
while (advance && self.collection.length !== 0) {
var item = self.collection.shift();
advance = self.callback(item);
while (advance && this.collection.length !== 0) {
var item = this.collection.shift();
advance = this.callback(item);
}

@@ -83,18 +55,17 @@ return advance;

* Helper to make a get request to fetch next page with nextLink url and update the page iterator instance with the returned response
* @return A promise that resolves to a response data with next page collection
* @returns A promise that resolves to a response data with next page collection
*/
PageIterator.prototype.fetchAndUpdateNextPageData = function () {
return __awaiter(this, void 0, void 0, function () {
var self_1, response, error_1;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var response, error_1;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
self_1 = this;
return [4 /*yield*/, self_1.client.api(self_1.nextLink).get()];
return [4 /*yield*/, this.client.api(this.nextLink).get()];
case 1:
response = _a.sent();
self_1.collection = response.value;
self_1.nextLink = response["@odata.nextLink"];
self_1.deltaLink = response["@odata.deltaLink"];
this.collection = response.value;
this.nextLink = response["@odata.nextLink"];
this.deltaLink = response["@odata.deltaLink"];
return [3 /*break*/, 3];

@@ -110,4 +81,5 @@ case 2:

/**
* @public
* Getter to get the deltaLink in the current response
* @return A deltaLink which is being used to make delta requests in future
* @returns A deltaLink which is being used to make delta requests in future
*/

@@ -118,23 +90,24 @@ PageIterator.prototype.getDeltaLink = function () {

/**
* @public
* @async
* Iterates over the collection and kicks callback for each item on iteration. Fetches next set of data through nextLink and iterates over again
* This happens until the nextLink is drained out or the user responds with a red flag to continue from callback
* @return A Promise that resolves to nothing on completion and throws error incase of any discrepancy.
* @returns A Promise that resolves to nothing on completion and throws error incase of any discrepancy.
*/
PageIterator.prototype.iterate = function () {
return __awaiter(this, void 0, void 0, function () {
var self_2, advance, error_2;
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var advance, error_2;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 6, , 7]);
self_2 = this, advance = self_2.iterationHelper();
advance = this.iterationHelper();
_a.label = 1;
case 1:
if (!advance) return [3 /*break*/, 5];
if (!(self_2.nextLink !== undefined)) return [3 /*break*/, 3];
return [4 /*yield*/, self_2.fetchAndUpdateNextPageData()];
if (!(this.nextLink !== undefined)) return [3 /*break*/, 3];
return [4 /*yield*/, this.fetchAndUpdateNextPageData()];
case 2:
_a.sent();
advance = self_2.iterationHelper();
advance = this.iterationHelper();
return [3 /*break*/, 4];

@@ -145,3 +118,7 @@ case 3:

case 4: return [3 /*break*/, 1];
case 5: return [3 /*break*/, 7];
case 5:
if (this.nextLink === undefined && this.collection.length === 0) {
this.complete = true;
}
return [3 /*break*/, 7];
case 6:

@@ -156,9 +133,11 @@ error_2 = _a.sent();

/**
* @public
* @async
* This internally calls the iterate method, It's just for more readability.
* @return A Promise that resolves to nothing on completion and throws error incase of any discrepancy
* To resume the iteration
* Note: This internally calls the iterate method, It's just for more readability.
* @returns A Promise that resolves to nothing on completion and throws error incase of any discrepancy
*/
PageIterator.prototype.resume = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
try {

@@ -174,2 +153,10 @@ return [2 /*return*/, this.iterate()];

};
/**
* @public
* To get the completeness status of the iterator
* @returns Boolean indicating the completeness
*/
PageIterator.prototype.isComplete = function () {
return this.complete;
};
return PageIterator;

@@ -176,0 +163,0 @@ }());

{
"name": "@microsoft/microsoft-graph-client",
"//": "NOTE: The version here should match exactly the exported const PACKAGE_VERSION in common.ts. If you change it here, also change it there.",
"version": "1.4.0",
"description": "Microsoft Graph Client Library",
"main": "lib/src/index.js",
"typings": "lib/src/index",
"files": [
"lib/"
],
"types": "./lib/src/index.d.ts",
"devDependencies": {
"@types/mocha": "^5.2.4",
"@types/node": "^9.4.0",
"browserify": "^13.1.0",
"mocha": "^5.2.0",
"typescript": "^2.2.1",
"uglify-js": "^3.4.5"
},
"scripts": {
"compile": "tsc",
"rollup-core": "node core-browserify.js > lib/graph-js-sdk-core.js && uglifyjs lib/graph-js-sdk-core.js --output lib/graph-js-sdk-core.js",
"rollup-with-vendor": "node node-browserify.js > lib/graph-js-sdk-web.js && uglifyjs ./lib/graph-js-sdk-web.js --output ./lib/graph-js-sdk-web.js",
"build-core": "npm run compile && npm run rollup-core",
"build-with-vendor": "npm run compile && npm run rollup-with-vendor",
"build": "npm run compile && npm run rollup-core && npm run rollup-with-vendor",
"test": "mocha lib/spec/core",
"test:types": "tsc -p spec && mocha spec/types",
"test:tasks": "tsc -p spec && mocha spec/tasks",
"test:content": "tsc -p spec && mocha spec/content"
},
"dependencies": {
"es6-promise": "^4.1.0",
"isomorphic-fetch": "^2.2.1"
},
"repository": {
"type": "git",
"url": "https://github.com/microsoftgraph/msgraph-sdk-javascript.git"
}
"name": "@microsoft/microsoft-graph-client",
"//": "NOTE: The version here should match exactly the exported const PACKAGE_VERSION in Constants.ts. If you change it here, also change it there.",
"version": "1.5.2",
"description": "Microsoft Graph Client Library",
"main": "lib/src/index.js",
"typings": "lib/src/index",
"files": [
"lib/"
],
"types": "./lib/src/index.d.ts",
"dependencies": {
"es6-promise": "^4.2.6",
"isomorphic-fetch": "^2.2.1",
"tslib": "^1.9.3"
},
"devDependencies": {
"@types/isomorphic-fetch": "0.0.35",
"@types/mocha": "^5.2.6",
"@types/node": "^11.9.5",
"browserify": "^16.2.3",
"chai": "^4.2.0",
"husky": "^1.3.1",
"lint-staged": "^8.1.4",
"mocha": "^6.0.2",
"msal": "^0.2.4",
"prettier": "^1.16.4",
"tslint": "^5.13.0",
"tslint-config-prettier": "^1.18.0",
"typescript": "^3.3.3333",
"uglify-es": "^3.3.9"
},
"scripts": {
"compile": "tsc",
"web:js": "node browserify-with-dependencies.js > lib/graph-js-sdk-web.js && uglifyjs ./lib/graph-js-sdk-web.js --output ./lib/graph-js-sdk-web.js",
"core:js": "node browserify.js > lib/graph-js-sdk-core.js && uglifyjs ./lib/graph-js-sdk-core.js --output ./lib/graph-js-sdk-core.js",
"build": "npm run compile && npm run web:js && npm run core:js",
"test": "npm run compile && mocha lib/spec/content && mocha lib/spec/core && mocha lib/spec/middleware && mocha lib/spec/tasks",
"test:content": "tsc -p spec && mocha spec/content",
"test:core": "tsc -p spec && mocha spec/core",
"test:middleware": "tsc -p spec && mocha spec/middleware",
"test:tasks": "tsc -p spec && mocha spec/tasks",
"test:development": "tsc -p spec && mocha spec/development/workload",
"test:workload": "tsc -p spec && mocha spec/development/workload",
"lint": "tslint --project ./tsconfig.json -c tslint.json",
"format:css": "prettier --write \"**/*.css\"",
"format:html": "prettier --write \"**/*.html\"",
"format:js": "prettier --write \"**/*.js\"",
"format:json": "prettier --write \"**/*.json\"",
"format:md": "prettier --write \"**/*.md\"",
"format:rc": "prettier --write --parser json \"**/.*rc\"",
"format:ts": "prettier --write \"**/*.ts\"",
"format": "npm run format:css && npm run format:html && npm run format:js && npm run format:json && npm run format:md && npm run format:rc && npm run format:ts",
"prepack": "npm install && npm run build && npm run test"
},
"repository": {
"type": "git",
"url": "https://github.com/microsoftgraph/msgraph-sdk-javascript.git"
}
}
# Microsoft Graph JavaScript Client Library
[![npm version badge](https://img.shields.io/npm/v/@microsoft/microsoft-graph-client.svg?maxAge=86400)](https://www.npmjs.com/package/@microsoft/microsoft-graph-client)
[![Travis](https://travis-ci.org/microsoftgraph/msgraph-sdk-javascript.svg?branch=master&style=flat-square)](https://travis-ci.org/microsoftgraph/msgraph-sdk-javascript)
The Microsoft Graph JavaScript client library is a lightweight wrapper around the Microsoft Graph API that can be used server-side and in the browser. See the [samples](samples) folder for code examples. You can also use our [TypeScript graph types](https://github.com/microsoftgraph/msgraph-typescript-typings) with this library. We love your feedback! You can file an issue in this repository or write on our [UserVoice page](https://officespdev.uservoice.com/).
[![npm version badge](https://img.shields.io/npm/v/@microsoft/microsoft-graph-client.svg?maxAge=86400)](https://www.npmjs.com/package/@microsoft/microsoft-graph-client) [![Travis](https://travis-ci.org/microsoftgraph/msgraph-sdk-javascript.svg?maxAge=86400)](https://travis-ci.org/microsoftgraph/msgraph-sdk-javascript) [![Known Vulnerabilities](https://snyk.io/test/github/microsoftgraph/msgraph-sdk-javascript/badge.svg?maxAge=86400)](https://snyk.io/test/github/microsoftgraph/msgraph-sdk-javascript) [![Licence](https://img.shields.io/github/license/microsoftgraph/msgraph-sdk-javascript.svg)](https://github.com/microsoftgraph/msgraph-sdk-javascript) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/microsoftgraph/msgraph-sdk-javascript) [![Downloads](https://img.shields.io/npm/dm/@microsoft/microsoft-graph-client.svg?maxAge=86400)](https://www.npmjs.com/package/@microsoft/microsoft-graph-client)
The Microsoft Graph JavaScript client library is a lightweight wrapper around the Microsoft Graph API that can be used server-side and in the browser.
**Looking for IntelliSense on models (Users, Groups, etc.)? Check out the [Microsoft Graph Types](https://github.com/microsoftgraph/msgraph-typescript-typings) repository!**

@@ -12,364 +12,194 @@

## Installation
### Node
1) Install [Node.js and npm](https://nodejs.org/).
2) ```npm install @microsoft/microsoft-graph-client```
### Via npm
3) Include the library in your JavaScript file with `const MicrosoftGraph = require("@microsoft/microsoft-graph-client");`
### Browser
The library comes with two varieties of options, you can pick one based on your use case
1. If your application has polyfills for **Fetch-API** and **ES6-Promise**, then can just include [lib/graph-js-sdk-core.js](./lib/graph-js-sdk-core.js) in your page.
```html
<script type="text/javascript" src="graph-js-sdk-core.js"></script>
```cmd
npm install @microsoft/microsoft-graph-client
```
2. If your application does not have polyfills for **Fetch-API** and **ES6-Promise**, then you have to include [lib/graph-js-sdk-web.js](./lib/graph-js-sdk-web.js) in your page.
```html
<script type="text/javascript" src="graph-js-sdk-web.js"></script>
```
import `@microsoft/microsoft-graph-client` into your module.
## Usage
### Initialize client with access token provider
This client library only handles authentication in the most basic way possible. The application is responsible for refreshing tokens and returning an immediately valid access token in the authentication provider.
```javascript
var client = MicrosoftGraph.Client.init({
authProvider: (done) => {
done(null, "PassInAccessTokenHere"); //first parameter takes an error if you can't get an access token
}
});
```typescript
import { Client } from "@microsoft/microsoft-graph-client";
```
### Calling pattern
### Via Script Tag
All calls to Microsoft Graph are chained together starting with `client.api(path)`. Path supports the following formats:
Include `lib/graph-js-sdk-web.js` in your page.
* me
* /me
* https://graph.microsoft.com/v1.0/me
* https://graph.microsoft.com/beta/me
* me/events?$filter=startswith(subject, 'ship')
```javascript
// Example calling /me with no parameters
client
.api('/me')
.get((err, res) => {
console.log(res); // prints info about authenticated user
});
```HTML
<script type="text/javascript" src="graph-js-sdk-web.js"></script>
```
Calls should start with `.api()`, then chain query parameters and end with an action.
```javascript
// get the names of my top 5 contacts on the beta endpoint
client
.api('me/people')
.version("beta") //optional, but recommeded to have before query params
.top(5)
.select("displayName")
.get((err, res) => {
const topContacts = res.value.map((u) => {return u.displayName});
console.log("Your top contacts are", topContacts.join(", "));
});
```
Incase if your application ships with [es6-promise](https://www.npmjs.com/package/es6-promise) and [isomorphic-fetch](https://www.npmjs.com/package/isomorphic-fetch) just use `lib/graph-js-sdk-core.js`
The actions(.get(), .put(), etc.) accept a callback or don't pass in a function to get back a Promise.
```javascript
client
.api('/me')
.select("displayName")
.get()
.then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
```HTML
<script type="text/javascript" src="graph-js-sdk-core.js"></script>
```
## Actions
## Getting started
### .post() and .patch()
The first parameter of `.post()` and `.patch()` takes an object that will be sent as the content of the request.
### 1. Register your application
````javascript
// construct the email object
const mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "example@example.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
}
Register your application to use Microsoft Graph API using one of the following supported authentication portals:
client
.api('/users/me/sendMail')
.post({message: mail}, (err, res) => {
console.log(res)
})
````
- [Microsoft Application Registration Portal](https://apps.dev.microsoft.com): Register a new application that works with Microsoft Accounts and/or organizational accounts using the unified V2 Authentication Endpoint.
- [Microsoft Azure Active Directory](https://manage.windowsazure.com): Register a new application in your tenant's Active Directory to support work or school users for your tenant or multiple tenants.
### `.del()` and `.delete()`
### 2. Authenticate for the Microsoft Graph service
````javascript
// delete a OneDrive item
client
.api(`/me/drive/items/${ONE_DRIVE_FILE_ID_TO_DELETE}`)
.delete((err, res) => {
if (err) {
console.log(err)
return;
}
console.log(res)
})
The Microsoft Graph JavaScript Client Library has an adapter implementation ([MSALAuthenticationProvider](src/MSALAuthenticationProvider.ts)) for [MSAL](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-core) (Microsoft Authentication Library) which takes care of getting the `accessToken`. MSAL library does not ship with this library, user has to include it externally (For including MSAL, refer [this](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-core#installation)).
````
### `.put()` and `.putStream()`
> **Note:** MSAL is supported only for frontend applications, for server-side authentication you have to implement your own AuthenticationProvider. Refer implementing [Custom Authentication Provider](./docs/CustomAuthenticationProvider.md).
You can upload files to the graph using `.put()`. For example, this can be used to update a profile picture from an HTML input form. See the [browser sample](samples/browser) for complete code.
#### Creating an instance of MSALAuthenticationProvider in browser environment
```javascript
var file = document.querySelector('input[type=file]').files[0];
Refer devDependencies in [package.json](./package.json) for the compatible msal version and update that version in below.
client
.api('/me/photo/$value')
.put(file, (err, res) => {
if (err) {
console.log(err);
return;
}
console.log("We've updated your picture!");
});
```html
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/<version>/js/msal.min.js"></script>
```
```typescript
const clientID = "your_client_id"; // Client Id of the registered application
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
const options = {
// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
redirectUri: "Your redirect URI",
};
const authProvider = new MicrosoftGraph.MSALAuthenticationProvider(clientId, graphScopes, options);
```
Use `.putStream()` to upload files to Microsoft Graph with Node.js streams.
````javascript
#### Creating an instance of MSALAuthenticationProvider in node environment
// Upload a file to OneDrive
let fs = require('fs'); // requires filesystem module
let stream = fs.createReadStream('./logo.png'); //path to local file
client
.api('/me/drive/root/children/logo.png/content') // path to the destination in OneDrive
.putStream(stream, (err) => {
console.log(err);
});
````
Refer devDependencies in [package.json](./package.json) for the compatible msal version and update that version in below.
### `.getStream()`
Use `.getStream()` to stream a download from Microsoft Graph.
````javascript
const fs = require('fs'); // requires filesystem module
client
.api('/me/drive/root/children/Book.xlsx/content') // path of source file in OneDrive
.getStream((err, downloadStream) => {
let writeStream = fs.createWriteStream('Book.xlsx'); // path to save file to
downloadStream.pipe(writeStream).on('error', console.log);
});
````
```cmd
npm install msal@<version>
```
```typescript
import { MSALAuthenticationProvider } from "./node_modules/@microsoft/microsoft-graph-client/lib/src/MSALAuthenticationProvider";
## Query Parameters
### $select, $expand and $orderby
These methods can take a string property, an array of strings or you can pass in each value as a separate argument.
````js
.select("birthday")
.select("department")
// same as
.select("birthday", "department")
// same as
.select(["birthday", "department"])
````
```javascript
client
.api('/me/people')
.select(["displayName", "department", "title"])
.get((err, res) => {
console.log(res)
})
const clientId = "your_client_id"; // Client Id of the registered application
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
const options = {
// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
redirectUri: "Your redirect URI",
};
const authProvider = new MSALAuthenticationProvider(clientId, scopes, options);
```
### $top and $skip
These parameters only take a number. Calling them multiple times is not supported.
User can integrate own preferred authentication library by implementing `IAuthenticationProvider` interface. Refer implementing [Custom Authentication Provider](./docs/CustomAuthenticationProvider.md).
````js
.top(5)
.skip(10)
````
### 3. Initialize a Microsoft Graph Client object with an authentication provider
### $count
Set .count() to true to also return the number of objects in the collection.
An instance of the **Client** class handles requests to Microsoft Graph API and processing the responses. To create a new instance of this class, you need to provide an instance of [`IAuthenticationProvider`](src/IAuthenticationProvider.ts) which needs to be passed as a value for `authProvider` key in [`ClientOptions`](src/IClientOptions.ts) to a static initializer method `Client.initWithMiddleware`.
````js
.count(true)
````
#### For browser environment
### $filter
Pass a filter string to `.filter()` for filtering result collections. Calling filter multiple times will override previous filter strings.
````js
client
.api("/users")
.filter("startswith(displayName, 'david')")
.get((err, res) => {
console.log(res)
})
````
### $search
Pass a search query string to `.search()` for searching in collections. Calling search multiple times will override previous search query. Refer graph [documentation](https://developer.microsoft.com/en-us/graph/docs/concepts/query_parameters#search-parameter) for more.
```js
client
.api("/me/messages")
.search("from:admin")
.get((err, res) => {
console.log(res);
});
```typescript
const options = {
authProvider, // An instance created from previous step
};
const Client = MicrosoftGraph.Client;
const client = Client.initWithMiddleware(options);
```
## Other API methods
#### For node environment
### .version()
Passing in a version through `.version()` has the highest priority. It overrides the Microsoft Graph client default version from `.init()` and the global library default (currently v1.0).
```typescript
import { Client } from "@microsoft/microsoft-graph-client";
### .query()
You can pass in any URL query parameters as a dictionary or string.
````javascript
.query({"$select":"displayName"})
// same as
.query("$select=displayName")
// same as
.select("displayName")
````
### .header() and .headers()
You can pass in additional request headers, either individually or in a dictionary.
````javascript
.header("someHeaderName", "someHeaderValue")
// or
.headers({"someHeaderName":"someHeaderValue"})
````
### .option() and .options()
You can pass in additional request options, either individually or in a dictionay. Options can be [node specific](https://github.com/bitinn/node-fetch#options) or [from fetch standard](https://fetch.spec.whatwg.org/#requestinit)
```js
.option("someOptionName", "someOptionValue")
// or
.options({"someOptionName":"someOptionValue"})
const options = {
authProvider, // An instance created from previous step
};
const client = Client.initWithMiddleware(options);
```
### .responseType()
To set a custom response type, use the `.responseType(<ResponseType>)` method. Refer [ResponseType.ts](./src/ResponseType.ts) for available options.
````js
client
.api(`/me/drive/root/children/${fileName}/content`)
.responseType(MicrosoftGraph.ResponseType.BLOB)
.get()
.then((res) => {
console.log("Downloaded..!!");
})
.catch((err) => {
throw err;
});
````
For more information on initializing client, refer [this document](./docs/CreatingClientInstance.md).
## Usage Resources
* [Large File Upload Task](/docs/tasks/LargeFileUploadTask.md)
* [Batching](/docs/content/Batching.md)
### 4. Make requests to the graph
## Running node samples
You can run and debug the node samples found under [./samples/node/node-sample.js](./samples/node/node-sample.js) by running the *Run node samples* configuration from the **Debug** (Ctrl + Shift + D) menu in Visual Studio Code. Alternately, you can run the node samples from the CLI by entering `node ./samples/node/node-sample.js` (assuming you are at the root of this repo). You'll need to rename the *secrets.example.json* file to *secrets.json* and add a valid access token to it. You can get an access token by doing the following:
1. Go to [Graph Explorer](https://developer.microsoft.com/en-us/graph/graph-explorer).
2. Login with the account you want to use to run the node samples.
3. Open the F12 dev tools.
4. Type `tokenPlease()` into the console to get an access token.
5. Copy the access token and put it into the *secrets.json* file and save the file.
Once you have authentication setup and an instance of Client, you can begin to make calls to the service. All requests should be start with `client.api(path)` and end with an [action](./docs/Actions.md).
We suggest that you become acquainted with these samples as they show some of the main use scenarios for this client library.
Getting user details
## Additional information
### Options in `MicrosoftGraph.Client.init()`
```typescript
try {
let userDetails = await client.api("/me").get();
console.log(userDetails);
} catch (error) {
throw error;
}
```
The following are optional parameters to pass to MicrosoftGraph.Client.init(), except for the authProvider:
* defaultVersion - When .version() isn't called, this version is used. (defaults to v1.0)
* debugLogging - Set to true to see the URL of the request printed.
* authProvider - See the [usage](#usage) section for info.
* baseUrl - If you need to call a different URL instead of graph.microsoft.io, specify it as a string here.
Sending an email to the recipients
### Full service response
The full response containing the headers, status code, and body can be obtained by passing a third parameter to the callback.
````javascript
client
.api('/me')
.select("displayName")
.get((err, res, rawResponse) => {
console.log(rawResponse.statusCode);
console.log(rawResponse.header);
});
````
```typescript
// Construct email object
const mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [
{
emailAddress: {
address: "example@example.com",
},
},
],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html",
},
};
try {
let response = await client.api("/me/sendMail").post({ message: mail });
console.log(response);
} catch (error) {
throw error;
}
```
### Native date objects can be passed in as parameters
```javascript
var date = new Date();
date.setDate(date.getDate()-365); // ~ 1 year ago
For more information, refer: [Calling Pattern](docs/CallingPattern.md), [Actions](docs/Actions.md), [Query Params](docs/QueryParameters.md), [API Methods](docs/APIMethods.md) and [more](docs/).
client
.api('/me')
.body({"birthday": date})
.update((err, res) => {
console.log("Updated my birthday")
})
```
## Documentation
## Development
These steps are not required to use this library.
- [Batching](docs/content/Batching.md)
- [Large File Upload Task](docs/tasks/LargeFileUploadTask.md)
- [Page Iterator](docs/tasks/PageIterator.md)
- [Actions](docs/Actions.md)
- [Query Parameters](docs/QueryParameters.md)
- [Other APIs](docs/OtherAPIs.md)
- [Getting Raw Response](docs/GettingRawResponse.md)
```npm install``` installs development dependencies (TypeScript, Mocha, etc.).
> **Note:** If you want to run ```tsc``` from the command line, install TypeScript globally with ```npm install -g typescript``` or reference `./node_modules/.bin/tsc`
## Questions and comments
```npm run build``` generates lib/ files for node and browser versions.
We'd love to get your feedback about the Microsoft Graph JavaScript client library. You can send your questions and suggestions to us in the [Issues](https://github.com/microsoftgraph/msgraph-sdk-javascript/issues) section of this repository.
```npm pack``` bundles the npm module.
## Contributing
```npm test``` runs tests of the core library (URL parsing, mock responses, etc). You can also set breakpoints and run this from within Visual Studio Code by selecting the *Run core test* configuration from the Debug view.
Please see the [contributing guidelines](CONTRIBUTING.md).
```npm run test:types``` to run tests against the Graph API for users, groups, Excel, OneNote, etc.
## Additional resources
To build only browser version:
```
node node-browserify.js > lib/graph-js-sdk-web.js
```
- [Microsoft Graph website](https://graph.microsoft.io)
- [Microsoft Graph TypeScript types](https://github.com/microsoftgraph/msgraph-typescript-typings/)
- [Angular.js sample using the JavaScript client library](https://github.com/microsoftgraph/angular-connect-sample)
- [Node.js sample using the JavaScript client library](https://github.com/microsoftgraph/nodejs-connect-sample)
- [Office Dev Center](http://dev.office.com/)
## Questions and comments
## Third Party Notices
We'd love to get your feedback about the Microsoft Graph JavaScript client library. You can send your questions and suggestions to us in the [Issues](https://github.com/microsoftgraph/msgraph-sdk-javascript/issues) section of this repository.
See [Third Party Notices](./THIRD%20PARTY%20NOTICES) for information on the packages that are included in the [package.json](./package.json)
## Security Reporting
## Contributing
Please see the [contributing guidelines](CONTRIBUTING.md).
If you find a security issue with our libraries or services please report it to [secure@microsoft.com](mailto:secure@microsoft.com) with as much detail as possible. Your submission may be eligible for a bounty through the [Microsoft Bounty](http://aka.ms/bugbounty) program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting [this page](https://technet.microsoft.com/en-us/security/dd252948) and subscribing to Security Advisory Alerts.
## License
## Additional resources
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "[License](./LICENSE)");
* [Microsoft Graph website](https://graph.microsoft.io)
* [Microsoft Graph TypeScript types](https://github.com/microsoftgraph/msgraph-typescript-typings/)
* [Angular.js sample using the JavaScript client library](https://github.com/microsoftgraph/angular-connect-sample)
* [Node.js sample using the JavaScript client library](https://github.com/microsoftgraph/nodejs-connect-sample)
* [Office Dev Center](http://dev.office.com/)
## We Value and Adhere to the Microsoft Open Source Code of Conduct
## Copyright
Copyright (c) Microsoft Corporation. All rights reserved.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
## Third Party Notices
See [Third Party Notices](https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/master/THIRD%20PARTY%20NOTICES) for information on the packages that are included in the [package.json](https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/master/package.json)

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc