implements new response type for Database, Container, and Item (#44)

This commit is contained in:
Christopher Anderson 2018-07-11 12:08:35 -07:00 коммит произвёл Steve Faulkner
Родитель 270f38312b
Коммит 0f253456a5
29 изменённых файлов: 352 добавлений и 296 удалений

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

@ -7,6 +7,7 @@ import { StoredProcedure, StoredProcedures } from "../StoredProcedure";
import { Trigger, Triggers } from "../Trigger";
import { UserDefinedFunction, UserDefinedFunctions } from "../UserDefinedFunction";
import { ContainerDefinition } from "./ContainerDefinition";
import { ContainerResponse } from "./ContainerResponse";
export class Container {
public readonly items: Items;
@ -45,15 +46,18 @@ export class Container {
return new Trigger(this, id);
}
public read(options?: RequestOptions): Promise<Response<ContainerDefinition>> {
return this.database.client.documentClient.readCollection(this.url, options);
public async read(options?: RequestOptions): Promise<ContainerResponse> {
const response = await this.database.client.documentClient.readCollection(this.url, options);
return {body: response.result, headers: response.headers, ref: this, container: this};
}
public replace(body: ContainerDefinition, options?: RequestOptions): Promise<Response<ContainerDefinition>> {
return this.database.client.documentClient.replaceCollection(this.url, body, options);
public async replace(body: ContainerDefinition, options?: RequestOptions): Promise<ContainerResponse> {
const response = await this.database.client.documentClient.replaceCollection(this.url, body, options);
return {body: response.result, headers: response.headers, ref: this, container: this};
}
public delete(options?: RequestOptions): Promise<Response<ContainerDefinition>> {
return this.database.client.documentClient.deleteCollection(this.url, options);
public async delete(options?: RequestOptions): Promise<ContainerResponse> {
const response = await this.database.client.documentClient.deleteCollection(this.url, options);
return {body: response.result, headers: response.headers, ref: this, container: this};
}
}

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

@ -0,0 +1,7 @@
import { Container } from ".";
import { CosmosResponse } from "../../request/CosmosResponse";
import { ContainerDefinition } from "./ContainerDefinition";
export interface ContainerResponse extends CosmosResponse<ContainerDefinition, Container> {
container: Container;
}

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

@ -4,6 +4,7 @@ import { FeedOptions, RequestOptions, Response } from "../../request";
import { Database } from "../Database";
import { Container } from "./Container";
import { ContainerDefinition } from "./ContainerDefinition";
import { ContainerResponse } from "./ContainerResponse";
export class Containers {
constructor(public readonly database: Database) { }
@ -24,8 +25,10 @@ export class Containers {
* </p>
* @param body - Represents the body of the container.
*/
public create(body: ContainerDefinition, options?: RequestOptions): Promise<Response<ContainerDefinition>> {
return this.database.client.documentClient.createCollection(this.database.url, body, options);
public async create(body: ContainerDefinition, options?: RequestOptions): Promise<ContainerResponse> {
const response = await this.database.client.documentClient.createCollection(this.database.url, body, options);
const ref = new Container(this.database, response.result.id);
return { body: response.result, headers: response.headers, ref, container: ref };
}
public readAll(options?: FeedOptions): QueryIterator<ContainerDefinition> {

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

@ -1,3 +1,4 @@
export { Container } from "./Container";
export { Containers } from "./Containers";
export { ContainerDefinition } from "./ContainerDefinition";
export { ContainerResponse } from "./ContainerResponse";

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

@ -1,6 +1,6 @@
import { Constants, UriFactory } from "../../common";
import { UriFactory } from "../../common";
import { CosmosClient } from "../../CosmosClient";
import { RequestOptions, Response } from "../../request";
import { RequestOptions } from "../../request";
import { Container, Containers } from "../Container";
import { User, Users } from "../User";
import { DatabaseDefinition } from "./DatabaseDefinition";
@ -26,11 +26,13 @@ export class Database {
return new User(this, id);
}
public read(options?: RequestOptions): Promise<Response<DatabaseDefinition>> {
return this.client.documentClient.readDatabase(this.url, options);
public async read(options?: RequestOptions): Promise<DatabaseResponse> {
const response = await this.client.documentClient.readDatabase(this.url, options);
return { body: response.result, headers: response.headers, ref: this, database: this };
}
public delete(options?: RequestOptions): Promise<Response<DatabaseDefinition>> {
return this.client.documentClient.deleteDatabase(this.url, options);
public async delete(options?: RequestOptions): Promise<DatabaseResponse> {
const response = await this.client.documentClient.deleteDatabase(this.url, options);
return { body: response.result, headers: response.headers, ref: this, database: this };
}
}

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

@ -0,0 +1,7 @@
import { CosmosResponse } from "../../request/CosmosResponse";
import { Database } from "./Database";
import { DatabaseDefinition } from "./DatabaseDefinition";
export interface DatabaseResponse extends CosmosResponse<DatabaseDefinition, Database> {
database: Database;
}

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

@ -4,10 +4,12 @@ import { QueryIterator } from "../../queryIterator";
import { FeedOptions, RequestOptions, Response } from "../../request";
import { Database } from "./Database";
import { DatabaseDefinition } from "./DatabaseDefinition";
import { DatabaseResponse } from "./DatabaseResponse";
export class Databases {
constructor(private readonly client: CosmosClient) {}
// TODO: DatabaseResponse for QueryIterator?
public query(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<DatabaseDefinition> {
return this.client.documentClient.queryDatabases(query, options);
}
@ -25,10 +27,13 @@ export class Databases {
*
* @param body - A json object that represents The database to be created.
*/
public create(body: DatabaseDefinition, options?: RequestOptions): Promise<Response<DatabaseDefinition>> {
return this.client.documentClient.createDatabase(body, options);
public async create(body: DatabaseDefinition, options?: RequestOptions): Promise<DatabaseResponse> {
const response = await this.client.documentClient.createDatabase(body, options);
const ref = new Database(this.client, body.id);
return { body: response.result, headers: response.headers, ref, database: ref };
}
// TODO: DatabaseResponse for QueryIterator?
public readAll(options?: FeedOptions): QueryIterator<DatabaseDefinition> {
return this.client.documentClient.readDatabases(options);
}

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

@ -1,3 +1,4 @@
export { Database } from "./Database";
export { Databases } from "./Databases";
export { DatabaseDefinition } from "./DatabaseDefinition";
export { DatabaseResponse } from "./DatabaseResponse";

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

@ -1,7 +1,8 @@
import { Constants, UriFactory } from "../../common";
import { UriFactory } from "../../common";
import { CosmosClient } from "../../CosmosClient";
import { RequestOptions, Response } from "../../request";
import { Container } from "../Container";
import { ItemResponse } from "./ItemResponse";
export class Item {
@ -17,33 +18,37 @@ export class Item {
this.client = this.container.database.client;
}
public read(options?: RequestOptions): Promise<Response<any>>;
public read<T>(options?: RequestOptions): Promise<Response<T>>;
public read<T>(options?: RequestOptions): Promise<Response<T>> {
public read(options?: RequestOptions): Promise<ItemResponse<any>>;
public read<T>(options?: RequestOptions): Promise<ItemResponse<T>>;
public async read<T>(options?: RequestOptions): Promise<ItemResponse<T>> {
options = options || {};
if ((!options || !options.partitionKey) && this.primaryKey) {
options.partitionKey = this.primaryKey;
}
return this.client.documentClient.readDocument(this.url, options) as Promise<Response<T>>;
const response = await (this.client.documentClient.readDocument(this.url, options) as Promise<Response<T>>);
return {body: response.result, headers: response.headers, ref: this, item: this};
}
public replace(body: any, options?: RequestOptions): Promise<Response<any>>;
public replace<T>(body: T, options?: RequestOptions): Promise<Response<T>>;
public replace<T>(body: T, options?: RequestOptions): Promise<Response<T>> {
public replace(body: any, options?: RequestOptions): Promise<ItemResponse<any>>;
public replace<T>(body: T, options?: RequestOptions): Promise<ItemResponse<T>>;
public async replace<T>(body: T, options?: RequestOptions): Promise<ItemResponse<T>> {
options = options || {};
if ((!options || !options.partitionKey) && this.primaryKey) {
options.partitionKey = this.primaryKey;
}
return this.client.documentClient.replaceDocument(this.url, body, options) as Promise<Response<T>>;
const response = await (this.client.documentClient
.replaceDocument(this.url, body, options) as Promise<Response<T>>);
return {body: response.result, headers: response.headers, ref: this, item: this};
}
public delete(options?: RequestOptions): Promise<Response<any>>;
public delete<T>(options?: RequestOptions): Promise<Response<T>>;
public delete<T>(options?: RequestOptions): Promise<Response<T>> {
public delete(options?: RequestOptions): Promise<ItemResponse<any>>;
public delete<T>(options?: RequestOptions): Promise<ItemResponse<T>>;
public async delete<T>(options?: RequestOptions): Promise<ItemResponse<T>> {
options = options || {};
if ((!options || !options.partitionKey) && this.primaryKey) {
options.partitionKey = this.primaryKey;
}
return this.client.documentClient.deleteDocument(this.url, options) as Promise<Response<T>>;
const response = await (this.client.documentClient.deleteDocument(this.url, options) as Promise<Response<T>>);
return {body: response.result, headers: response.headers, ref: this, item: this};
}
}

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

@ -0,0 +1,6 @@
import { CosmosResponse } from "../../request/CosmosResponse";
import { Item } from "./Item";
export interface ItemResponse<T> extends CosmosResponse<T, Item> {
item: Item;
}

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

@ -4,6 +4,7 @@ import { QueryIterator } from "../../queryIterator";
import { FeedOptions, RequestOptions, Response } from "../../request";
import { Container } from "../Container";
import { Item } from "./Item";
import { ItemResponse } from "./ItemResponse";
export class Items {
private client: DocumentClient;
@ -32,10 +33,12 @@ export class Items {
* </p>
* @param body - Represents the body of the item. Can contain any number of user defined properties.
*/
public async create(body: any, options?: RequestOptions): Promise<Response<any>>;
public async create<T>(body: T, options?: RequestOptions): Promise<Response<T>>;
public async create<T>(body: T, options?: RequestOptions): Promise<Response<T>> {
return this.client.createDocument(this.container.url, body, options) as Promise<Response<T>>;
public async create(body: any, options?: RequestOptions): Promise<ItemResponse<any>>;
public async create<T>(body: T, options?: RequestOptions): Promise<ItemResponse<T>>;
public async create<T>(body: T, options?: RequestOptions): Promise<ItemResponse<T>> {
const response = await (this.client.createDocument(this.container.url, body, options) as Promise<Response<T>>);
const ref = new Item(this.container, (response.result as any).id, options.partitionKey as string);
return {body: response.result, headers: response.headers, ref, item: ref};
}
/**
@ -45,9 +48,11 @@ export class Items {
* An Item is an application resource and can be authorized using the master key or resource keys
* </p>
*/
public async upsert(body: any, options?: RequestOptions): Promise<Response<any>>;
public async upsert<T>(body: T, options?: RequestOptions): Promise<Response<T>>;
public async upsert<T>(body: T, options?: RequestOptions): Promise<Response<T>> {
return this.client.upsertDocument(this.container.url, body, options);
public async upsert(body: any, options?: RequestOptions): Promise<ItemResponse<any>>;
public async upsert<T>(body: T, options?: RequestOptions): Promise<ItemResponse<T>>;
public async upsert<T>(body: T, options?: RequestOptions): Promise<ItemResponse<T>> {
const response = await this.client.upsertDocument(this.container.url, body, options);
const ref = new Item(this.container, (response.result as any).id, options.partitionKey as string);
return {body: response.result, headers: response.headers, ref, item: ref};
}
}

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

@ -1,2 +1,3 @@
export { Item } from "./Item";
export { Items } from "./Items";
export { ItemResponse } from "./ItemResponse";

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

@ -0,0 +1,7 @@
import { IHeaders } from "../queryExecutionContext";
export interface CosmosResponse<T, U> {
body: T;
headers: IHeaders;
ref: U;
}

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

@ -4,3 +4,4 @@ export { MediaOptions } from "./MediaOptions";
export { RequestHandler } from "./request";
export { RequestOptions } from "./RequestOptions";
export { Response } from "./Response";
export { CosmosResponse } from "./CosmosResponse";

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

@ -3,7 +3,7 @@ import {
Container, CosmosClient,
Database, DatabaseDefinition, Item, RequestOptions, Response,
} from "../../";
import { ContainerDefinition, PermissionDefinition, User, UserDefinition } from "../../client";
import { ContainerDefinition, ItemResponse, PermissionDefinition, User, UserDefinition } from "../../client";
/** @hidden */
export class TestHelpers {
@ -48,7 +48,7 @@ export class TestHelpers {
const returnedDocuments = [];
for (const doc of documents) {
try {
const { result: document } = await container.items.create(doc);
const { body: document } = await container.items.create(doc);
returnedDocuments.push(document);
} catch (err) {
throw err;
@ -66,7 +66,8 @@ export class TestHelpers {
: { partitionKey: {} };
// TODO: should we block or do all requests in parallel?
const { result: doc } = await container.item(document.id).read(options);
const { body: doc } = await container.item(document.id).read(options);
assert.equal(JSON.stringify(doc), JSON.stringify(document));
} catch (err) {
throw err;
@ -79,7 +80,7 @@ export class TestHelpers {
const returnedDocuments: any[] = [];
for (const document of documents) {
try {
const { result: doc } = await container.item(document.id).replace(document);
const { body: doc } = await container.item(document.id).replace(document);
const expectedModifiedDocument = JSON.parse(JSON.stringify(document));
delete expectedModifiedDocument._etag;
delete expectedModifiedDocument._ts;
@ -103,7 +104,7 @@ export class TestHelpers {
? { partitionKey: document[partitionKeyPropertyName] }
: { partitionKey: {} };
const { result } = await container.item(document.id).delete(options);
await container.item(document.id).delete(options);
} catch (err) {
throw err;
}
@ -139,7 +140,7 @@ export class TestHelpers {
// Item
public static async createOrUpsertItem(
container: Container, body: any, options: RequestOptions, isUpsertTest: boolean) {
container: Container, body: any, options: RequestOptions, isUpsertTest: boolean): Promise<ItemResponse<any>> {
if (isUpsertTest) {
return container.items.upsert(body, options);
} else {
@ -148,7 +149,7 @@ export class TestHelpers {
}
public static async replaceOrUpsertItem(
container: Container, body: any, options: RequestOptions, isUpsertTest: boolean) {
container: Container, body: any, options: RequestOptions, isUpsertTest: boolean): Promise<ItemResponse<any>> {
if (isUpsertTest) {
return container.items.upsert(body, options);
} else {

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

@ -18,21 +18,22 @@ describe("NodeJS CRUD Tests", function () {
describe("Validate Authorization", function () {
const setupEntities = async function (isUpsertTest: boolean, client: CosmosClient) {
// create database
const { result: db } = await client.databases.create({ id: "Validate Authorization database" });
const { body: db } = await client.databases.create({ id: "Validate Authorization database" });
// create container1
const { result: container1 } = await client.database(db.id)
const { body: container1 } = await client.database(db.id)
.containers.create({ id: "Validate Authorization container" });
// create document1
const { result: document1 } = await client.database(db.id)
const { body: document1 } = await client.database(db.id)
.container(container1.id)
.items.create({ id: "coll1doc1", foo: "bar", key: "value" });
// create document 2
const { result: document2 } = await client.database(db.id)
const { body: document2 } = await client.database(db.id)
.container(container1.id)
.items.create({ id: "coll1doc2", foo: "bar2", key: "value2" });
// create container 2
const { result: container2 } = await client.database(db.id)
const { body: container2 } = await client.database(db.id)
.containers.create({ id: "sample container2" });
// create user1
@ -107,7 +108,7 @@ describe("NodeJS CRUD Tests", function () {
const col1Client = new CosmosClient({ endpoint, auth: { resourceTokens } });
// 1. Success-- Use Col1 Permission to Read
const { result: successColl1 } = await col1Client.database(entities.db.id)
const { body: successColl1 } = await col1Client.database(entities.db.id)
.container(entities.coll1.id).read();
assert(successColl1 !== undefined, "error reading container");
@ -129,7 +130,7 @@ describe("NodeJS CRUD Tests", function () {
assert.equal(successDocuments.length, 2, "Expected 2 Documents to be succesfully read");
// 4. Success-- Use Col1 Permission to Read Col1Doc1
const { result: successDoc } = await col1Client.database(entities.db.id)
const { body: successDoc } = await col1Client.database(entities.db.id)
.container(entities.coll1.id)
.item(entities.doc1.id).read();
assert(successDoc !== undefined, "error reading document");

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

@ -39,7 +39,7 @@ describe("NodeJS CRUD Tests", function () {
containerDefinition.partitionKey = { paths: ["/id"], kind: DocumentBase.PartitionKind.Hash };
}
const { result: containerDef } = await database.containers.create(containerDefinition);
const { body: containerDef } = await database.containers.create(containerDefinition);
const container = database.container(containerDef.id);
assert.equal(containerDefinition.id, containerDef.id);
assert.equal("consistent", containerDef.indexingPolicy.indexingMode);
@ -64,7 +64,7 @@ describe("NodeJS CRUD Tests", function () {
// Replacing indexing policy is allowed.
containerDef.indexingPolicy.indexingMode = IndexingMode.Lazy;
const { result: replacedContainer } = await container.replace(containerDef);
const { body: replacedContainer } = await container.replace(containerDef);
assert.equal("lazy", replacedContainer.indexingPolicy.indexingMode);
// Replacing partition key is not allowed.
@ -91,7 +91,7 @@ describe("NodeJS CRUD Tests", function () {
// read container
containerDef.id = containerDefinition.id; // Resume Id.
const { result: readcontainer } = await container.read();
const { body: readcontainer } = await container.read();
assert.equal(containerDefinition.id, readcontainer.id);
// delete container
@ -174,13 +174,13 @@ describe("NodeJS CRUD Tests", function () {
const indexPolicyTest = async function () {
try {
// create database
const { result: dbdef } = await client.databases.create({ id: "container test database" });
const { body: dbdef } = await client.databases.create({ id: "container test database" });
const database = client.database(dbdef.id);
// create container
const { result: containerDef } = await database.containers.create({ id: "container test container" });
const { body: containerDef } = await database.containers.create({ id: "container test container" });
const container = database.container(containerDef.id);
assert.equal(containerDef.indexingPolicy.indexingMode,
DocumentBase.IndexingMode.Consistent, "default indexing mode should be consistent");
await container.delete();
@ -190,7 +190,7 @@ describe("NodeJS CRUD Tests", function () {
indexingPolicy: { indexingMode: DocumentBase.IndexingMode.Lazy },
};
const { result: lazyContainerDef } = await database.containers.create(lazyContainerDefinition);
const { body: lazyContainerDef } = await database.containers.create(lazyContainerDefinition);
const lazyContainer = database.container(lazyContainerDef.id);
assert.equal(lazyContainerDef.indexingPolicy.indexingMode,
@ -202,7 +202,7 @@ describe("NodeJS CRUD Tests", function () {
id: "lazy container",
indexingPolicy: { indexingMode: DocumentBase.IndexingMode.Consistent },
};
const { result: consistentContainerDef } =
const { body: consistentContainerDef } =
await database.containers.create(consistentcontainerDefinition);
const consistentContainer = database.container(consistentContainerDef.id);
assert.equal(containerDef.indexingPolicy.indexingMode,
@ -235,7 +235,7 @@ describe("NodeJS CRUD Tests", function () {
};
const { result: containerWithIndexingPolicyDef } =
const { body: containerWithIndexingPolicyDef } =
await database.containers.create(containerDefinition);
// Two included paths.
@ -304,12 +304,12 @@ describe("NodeJS CRUD Tests", function () {
const defaultIndexingPolicyTest = async function () {
try {
// create database
const { result: dbdef } = await client.databases.create({ id: "container test database" });
const { body: dbdef } = await client.databases.create({ id: "container test database" });
const database = client.database(dbdef.id);
// create container with no indexing policy specified.
const containerDefinition01: ContainerDefinition = { id: "TestCreateDefaultPolicy01" };
const { result: containerNoIndexPolicyDef } = await database.containers.create(containerDefinition01);
const { body: containerNoIndexPolicyDef } = await database.containers.create(containerDefinition01);
checkDefaultIndexingPolicyPaths(containerNoIndexPolicyDef["indexingPolicy"]);
// create container with partial policy specified.
@ -321,7 +321,7 @@ describe("NodeJS CRUD Tests", function () {
},
};
const { result: containerWithPartialPolicyDef } =
const { body: containerWithPartialPolicyDef } =
await database.containers.create(containerDefinition02);
checkDefaultIndexingPolicyPaths((containerWithPartialPolicyDef as any)["indexingPolicy"]);
@ -330,7 +330,7 @@ describe("NodeJS CRUD Tests", function () {
id: "TestCreateDefaultPolicy03",
indexingPolicy: {},
};
const { result: containerDefaultPolicy } = await database.containers.create(containerDefinition03);
const { body: containerDefaultPolicy } = await database.containers.create(containerDefinition03);
checkDefaultIndexingPolicyPaths((containerDefaultPolicy as any)["indexingPolicy"]);
// create container with indexing policy missing indexes.
@ -344,7 +344,7 @@ describe("NodeJS CRUD Tests", function () {
],
},
};
const { result: containerMissingIndexes } = await database.containers.create(containerDefinition04);
const { body: containerMissingIndexes } = await database.containers.create(containerDefinition04);
checkDefaultIndexingPolicyPaths((containerMissingIndexes as any)["indexingPolicy"]);
// create container with indexing policy missing precision.
@ -368,7 +368,7 @@ describe("NodeJS CRUD Tests", function () {
],
},
};
const { result: containerMissingPrecision } = await database.containers.create(containerDefinition05);
const { body: containerMissingPrecision } = await database.containers.create(containerDefinition05);
checkDefaultIndexingPolicyPaths((containerMissingPrecision as any)["indexingPolicy"]);
} catch (err) {
throw err;
@ -387,7 +387,7 @@ describe("NodeJS CRUD Tests", function () {
describe("Validate response headers", function () {
const createThenReadcontainer = async function (database: Database, body: ContainerDefinition) {
try {
const { result: createdcontainer, headers } = await database.containers.create(body);
const { body: createdcontainer, headers } = await database.containers.create(body);
const response = await database.container(createdcontainer.id).read();
return response;
} catch (err) {

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

@ -5,71 +5,59 @@ import { TestHelpers } from "./../common/TestHelpers";
const endpoint = testConfig.host;
const masterKey = testConfig.masterKey;
const client = new CosmosClient({endpoint, auth: { masterKey}});
const client = new CosmosClient({ endpoint, auth: { masterKey } });
describe("NodeJS CRUD Tests", function () {
this.timeout(process.env.MOCHA_TIMEOUT || 10000);
// remove all databases from the endpoint before each test
beforeEach(async function () {
this.timeout(10000);
try {
await TestHelpers.removeAllDatabases(client);
} catch (err) {
throw err;
}
await TestHelpers.removeAllDatabases(client);
});
describe("Validate Database CRUD", async function () {
const databaseCRUDTest = async function () {
// read databases
const { result: databases } = await client.databases.readAll().toArray();
assert.equal(databases.constructor, Array, "Value should be an array");
// create a database
const beforeCreateDatabasesCount = databases.length;
const databaseDefinition = { id: "database test database" };
const { body: db } = await client.databases.create(databaseDefinition);
assert.equal(db.id, databaseDefinition.id);
// read databases after creation
const { result: databases2 } = await client.databases.readAll().toArray();
assert.equal(databases2.length, beforeCreateDatabasesCount + 1,
"create should increase the number of databases");
// query databases
const querySpec = {
query: "SELECT * FROM root r WHERE r.id=@id",
parameters: [
{
name: "@id",
value: databaseDefinition.id,
},
],
};
const { result: results } = await client.databases.query(querySpec).toArray();
assert(results.length > 0, "number of results for the query should be > 0");
// delete database
await client.database(db.id).delete();
try {
// read databases
const { result: databases } = await client.databases.readAll().toArray();
assert.equal(databases.constructor, Array, "Value should be an array");
// create a database
const beforeCreateDatabasesCount = databases.length;
const databaseDefinition = { id: "database test database" };
const { result: db } = await client.databases.create(databaseDefinition);
assert.equal(db.id, databaseDefinition.id);
// read databases after creation
const { result: databases2 } = await client.databases.readAll().toArray();
assert.equal(databases2.length, beforeCreateDatabasesCount + 1,
"create should increase the number of databases");
// query databases
const querySpec = {
query: "SELECT * FROM root r WHERE r.id=@id",
parameters: [
{
name: "@id",
value: databaseDefinition.id,
},
],
};
const { result: results } = await client.databases.query(querySpec).toArray();
assert(results.length > 0, "number of results for the query should be > 0");
// delete database
await client.database(db.id).delete();
try {
// read database after deletion
await client.database(db.id).read();
assert.fail("Read database on non-existent database should fail");
} catch (err) {
const notFoundErrorCode = 404;
assert.equal(err.code, notFoundErrorCode, "response should return error code 404");
}
// read database after deletion
await client.database(db.id).read();
assert.fail("Read database on non-existent database should fail");
} catch (err) {
throw err;
const notFoundErrorCode = 404;
assert.equal(err.code, notFoundErrorCode, "response should return error code 404");
}
};
it("nativeApi Should do database CRUD operations successfully name based", async function () {
try {
await databaseCRUDTest();
} catch (err) {
throw err;
}
await databaseCRUDTest();
});
});
@ -78,48 +66,48 @@ describe("NodeJS CRUD Tests", function () {
it("nativeApi Should fail on ends with a space", async function () {
// Id shoudn't end with a space.
try {
const { result: db } = await client.databases.create({ id: "id_ends_with_space " });
await client.databases.create({ id: "id_ends_with_space " });
assert.fail("Must throw if id ends with a space");
} catch (err) {
assert.equal("Id ends with a space.", err.message);
}
});
it("nativeAPI Should fail on contains '/'", async function() {
it("nativeAPI Should fail on contains '/'", async function () {
// Id shoudn't contain "/".
try {
const { result: db } = await client.databases.create({ id: "id_with_illegal/_char" });
await client.databases.create({ id: "id_with_illegal/_char" });
assert.fail("Must throw if id has illegal characters");
} catch (err) {
assert.equal("Id contains illegal chars.", err.message);
}
});
it("nativeAPI Should fail on contains '\\'", async function() {
it("nativeAPI Should fail on contains '\\'", async function () {
// Id shoudn't contain "\\".
try {
const { result: db } = await client.databases.create({ id: "id_with_illegal\\_char" });
await client.databases.create({ id: "id_with_illegal\\_char" });
assert.fail("Must throw if id contains illegal characters");
} catch (err) {
assert.equal("Id contains illegal chars.", err.message);
}
});
it("nativeAPI Should fail on contains '?'", async function() {
it("nativeAPI Should fail on contains '?'", async function () {
// Id shoudn't contain "?".
try {
const { result: db } = await client.databases.create({ id: "id_with_illegal?_?char" });
await client.databases.create({ id: "id_with_illegal?_?char" });
assert.fail("Must throw if id contains illegal characters");
} catch (err) {
assert.equal("Id contains illegal chars.", err.message);
}
});
it("nativeAPI should fail on contains '#'", async function() {
it("nativeAPI should fail on contains '#'", async function () {
// Id shoudn't contain "#".
try {
const { result: db } = await client.databases.create({ id: "id_with_illegal#_char" });
await client.databases.create({ id: "id_with_illegal#_char" });
assert.fail("Must throw if id contains illegal characters");
} catch (err) {
assert.equal("Id contains illegal chars.", err.message);

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

@ -16,27 +16,45 @@ describe("NodeJS CRUD Tests", function () {
// remove all databases from the endpoint before each test
beforeEach(async function () {
this.timeout(10000);
try {
await TestHelpers.removeAllDatabases(new CosmosClient({ endpoint, auth: { masterKey } }));
} catch (err) {
throw err;
}
await TestHelpers.removeAllDatabases(new CosmosClient({ endpoint, auth: { masterKey } }));
});
describe("Validate Document CRUD", function () {
const documentCRUDTest = async function (isUpsertTest: boolean) {
const client = new CosmosClient({ endpoint, auth: { masterKey } });
// create database
const { body: dbdef } = await client.databases.create({ id: "sample 中文 database" });
const db: Database = client.databases.get(dbdef.id);
// create container
const { body: containerdef } =
await db.containers.create({ id: "sample container" });
const container: Container = db.containers.get(containerdef.id);
// read items
const { result: items } = await container.items.readAll().toArray();
assert(Array.isArray(items), "Value should be an array");
// create an item
const beforeCreateDocumentsCount = items.length;
const itemDefinition = {
name: "sample document",
foo: "bar",
key: "value",
replace: "new property",
};
try {
const client = new CosmosClient({ endpoint, auth: { masterKey } });
// create database
const { result: dbdef } = await client.databases.create({ id: "sample 中文 database" });
const { body: dbdef } = await client.databases.create({ id: "sample 中文 database" });
const db: Database = client.database(dbdef.id);
// create container
const { result: containerdef } =
const { body: containerdef } =
await db.containers.create({ id: "sample container" });
const container: Container = db.container(containerdef.id);
// read items
const { result: items } = await container.items.readAll().toArray();
const { body: items } = await container.items.readAll().toArray();
assert(Array.isArray(items), "Value should be an array");
// create an item
@ -54,7 +72,7 @@ describe("NodeJS CRUD Tests", function () {
} catch (err) {
assert(err !== undefined, "should throw an error because automatic id generation is disabled");
}
const { result: document } = await TestHelpers.createOrUpsertItem(
const { body: document } = await TestHelpers.createOrUpsertItem(
container, itemDefinition, undefined, isUpsertTest);
assert.equal(document.name, itemDefinition.name);
assert(document.id !== undefined);
@ -72,132 +90,121 @@ describe("NodeJS CRUD Tests", function () {
},
],
};
const { result: results } = await container.items.query(querySpec).toArray();
const { body: results } = await container.items.query(querySpec).toArray();
assert(results.length > 0, "number of results for the query should be > 0");
const { result: results2 } = await container.items.query(
const { body: results2 } = await container.items.query(
querySpec, { enableScanInQuery: true }).toArray();
assert(results2.length > 0, "number of results for the query should be > 0");
// replace document
document.name = "replaced document";
document.foo = "not bar";
const { result: replacedDocument } = await TestHelpers.replaceOrUpsertItem(
const { body: replacedDocument } = await TestHelpers.replaceOrUpsertItem(
container, document, undefined, isUpsertTest);
assert.equal(replacedDocument.name, "replaced document", "document name property should change");
assert.equal(replacedDocument.foo, "not bar", "property should have changed");
assert.equal(document.id, replacedDocument.id, "document id should stay the same");
// read document
const { result: document2 } = await container.item(replacedDocument.id).read();
const { body: document2 } = await container.item(replacedDocument.id).read();
assert.equal(replacedDocument.id, document.id);
// delete document
const { result: res } = await container.item(replacedDocument.id).delete();
const { body: res } = await container.item(replacedDocument.id).delete();
// read documents after deletion
try {
const { result: document3 } = await container.item(replacedDocument.id).read();
const { body: document3 } = await container.item(replacedDocument.id).read();
assert.fail("must throw if document doesn't exist");
} catch (err) {
const notFoundErrorCode = 404;
assert.equal(err.code, notFoundErrorCode, "response should return error code 404");
}
} catch (err) {
throw err;
const notFoundErrorCode = 404;
assert.equal(err.code, notFoundErrorCode, "response should return error code 404");
}
};
const documentCRUDMultiplePartitionsTest = async function () {
try {
const client = new CosmosClient({endpoint, auth: { masterKey }});
// create database
const { result: dbdef } = await client.databases.create({ id: "db1" });
const db = client.database(dbdef.id);
const partitionKey = "key";
const client = new CosmosClient({endpoint, auth: { masterKey }});
// create database
const { result: dbdef } = await client.databases.create({ id: "db1" });
const db = client.database(dbdef.id);
const partitionKey = "key";
// create container
const containerDefinition = {
id: "coll1",
partitionKey: { paths: ["/" + partitionKey], kind: DocumentBase.PartitionKind.Hash },
};
// create container
const containerDefinition = {
id: "coll1",
partitionKey: { paths: ["/" + partitionKey], kind: DocumentBase.PartitionKind.Hash },
};
const { result: containerdef } =
await db.containers.create(containerDefinition, { offerThroughput: 12000 });
const container = db.container(containerdef.id);
const { result: containerdef } =
await db.containers.create(containerDefinition, { offerThroughput: 12000 });
const container = db.container(containerdef.id);
const documents = [
{ id: "document1" },
{ id: "document2", key: null, prop: 1 },
{ id: "document3", key: false, prop: 1 },
{ id: "document4", key: true, prop: 1 },
{ id: "document5", key: 1, prop: 1 },
{ id: "document6", key: "A", prop: 1 },
];
const documents = [
{ id: "document1" },
{ id: "document2", key: null, prop: 1 },
{ id: "document3", key: false, prop: 1 },
{ id: "document4", key: true, prop: 1 },
{ id: "document5", key: 1, prop: 1 },
{ id: "document6", key: "A", prop: 1 },
];
let returnedDocuments =
await TestHelpers.bulkInsertItems(container, documents);
let returnedDocuments =
await TestHelpers.bulkInsertItems(container, documents);
assert.equal(returnedDocuments.length, documents.length);
returnedDocuments.sort(function (doc1, doc2) {
return doc1.id.localeCompare(doc2.id);
});
await TestHelpers.bulkReadItems(container, returnedDocuments, partitionKey);
const { result: successDocuments } = await container.items.readAll().toArray();
assert(successDocuments !== undefined, "error reading documents");
assert.equal(successDocuments.length, returnedDocuments.length,
"Expected " + returnedDocuments.length + " documents to be succesfully read");
successDocuments.sort(function (doc1, doc2) {
return doc1.id.localeCompare(doc2.id);
});
assert.equal(JSON.stringify(successDocuments), JSON.stringify(returnedDocuments),
"Unexpected documents are returned");
assert.equal(returnedDocuments.length, documents.length);
returnedDocuments.sort(function (doc1, doc2) {
return doc1.id.localeCompare(doc2.id);
});
await TestHelpers.bulkReadItems(container, returnedDocuments, partitionKey);
const { result: successDocuments } = await container.items.readAll().toArray();
assert(successDocuments !== undefined, "error reading documents");
assert.equal(successDocuments.length, returnedDocuments.length,
"Expected " + returnedDocuments.length + " documents to be succesfully read");
successDocuments.sort(function (doc1, doc2) {
return doc1.id.localeCompare(doc2.id);
});
assert.equal(JSON.stringify(successDocuments), JSON.stringify(returnedDocuments),
"Unexpected documents are returned");
returnedDocuments.forEach(function (document) { ++document.prop; });
const newReturnedDocuments =
await TestHelpers.bulkReplaceItems(container, returnedDocuments);
returnedDocuments = newReturnedDocuments;
await TestHelpers.bulkQueryItemsWithPartitionKey(container, returnedDocuments, partitionKey);
const querySpec = {
query: "SELECT * FROM Root",
};
try {
const { result: badUpdate } = await container.items.query(
querySpec, { enableScanInQuery: true }).toArray();
assert.fail("Must fail");
} catch (err) {
const badRequestErrorCode = 400;
assert.equal(err.code, badRequestErrorCode,
"response should return error code " + badRequestErrorCode);
}
const { result: results } = await container.items.query(
querySpec, { enableScanInQuery: true, enableCrossPartitionQuery: true }).toArray();
assert(results !== undefined, "error querying documents");
results.sort(function (doc1, doc2) {
return doc1.id.localeCompare(doc2.id);
});
assert.equal(results.length, returnedDocuments.length,
"Expected " + returnedDocuments.length + " documents to be succesfully queried");
assert.equal(JSON.stringify(results), JSON.stringify(returnedDocuments), "Unexpected query results");
returnedDocuments.forEach(function (document) { ++document.prop; });
const newReturnedDocuments =
await TestHelpers.bulkReplaceItems(container, returnedDocuments);
returnedDocuments = newReturnedDocuments;
await TestHelpers.bulkQueryItemsWithPartitionKey(container, returnedDocuments, partitionKey);
const querySpec = {
query: "SELECT * FROM Root",
};
try {
const { body: badUpdate } = await container.items.query(
querySpec, { enableScanInQuery: true }).toArray();
assert.fail("Must fail");
} catch (err) {
const badRequestErrorCode = 400;
assert.equal(err.code, badRequestErrorCode,
"response should return error code " + badRequestErrorCode);
}
const { body: results } = await container.items.query(
querySpec, { enableScanInQuery: true, enableCrossPartitionQuery: true }).toArray();
assert(results !== undefined, "error querying documents");
results.sort(function (doc1, doc2) {
return doc1.id.localeCompare(doc2.id);
});
assert.equal(results.length, returnedDocuments.length,
"Expected " + returnedDocuments.length + " documents to be succesfully queried");
assert.equal(JSON.stringify(results), JSON.stringify(returnedDocuments), "Unexpected query results");
await TestHelpers.bulkDeleteItems(
container, returnedDocuments, partitionKey);
} catch (err) {
throw err;
}
await TestHelpers.bulkDeleteItems(
container, returnedDocuments, partitionKey);
};
it("nativeApi Should do document CRUD operations successfully name based", async function () {
try {
await documentCRUDTest(false);
} catch (err) {
throw err;
}
await documentCRUDTest(false);
});
it("nativeApi Should do document CRUD operations successfully name based with upsert", async function () {
try {
await documentCRUDTest(true);
} catch (err) {
throw err;
}
await documentCRUDTest(true);
});
it("nativeApi Should do document CRUD operations over multiple partitions", async function () {

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

@ -29,7 +29,7 @@ describe("NodeJS CRUD Tests", function () {
try {
// create a database
const databaseDefinition = { id: "query test database" };
const { result: db } = await client.databases.create(databaseDefinition);
const { body: db } = await client.databases.create(databaseDefinition);
assert.equal(db.id, databaseDefinition.id);
// query databases
const querySpec0 = {
@ -112,9 +112,9 @@ describe("NodeJS CRUD Tests", function () {
let resources: { container: Container, doc1: any, doc2: any, doc3: any };
beforeEach(async function () {
const container = await TestHelpers.getTestContainer(client, "Validate QueryIterator Functionality");
const { result: doc1 } = await container.items.create({ id: "doc1", prop1: "value1" });
const { result: doc2 } = await container.items.create({ id: "doc2", prop1: "value2" });
const { result: doc3 } = await container.items.create({ id: "doc3", prop1: "value3" });
const { body: doc1 } = await container.items.create({ id: "doc1", prop1: "value1" });
const { body: doc2 } = await container.items.create({ id: "doc2", prop1: "value2" });
const { body: doc3 } = await container.items.create({ id: "doc3", prop1: "value3" });
resources = { container, doc1, doc2, doc3 };
});

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

@ -43,7 +43,7 @@ describe("NodeJS CRUD Tests", function () {
],
};
const entropy = Math.floor(Math.random() * 10000);
const { result: containerDef } = await database.containers.create(
const { body: containerDef } = await database.containers.create(
{ id: `sample container${entropy}`, indexingPolicy });
const container = database.container(containerDef.id);

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

@ -249,7 +249,7 @@ describe("NodeJS CRUD Tests", function () {
});
it("nativeApi Should execute stored procedure with partition key successfully name based", async function () {
const { result: db } = await client.databases.create({ id: "sproc test database" });
const { body: db } = await client.databases.create({ id: "sproc test database" });
// create container
const partitionKey = "key";
@ -258,7 +258,7 @@ describe("NodeJS CRUD Tests", function () {
partitionKey: { paths: ["/" + partitionKey], kind: DocumentBase.PartitionKind.Hash },
};
const { result: containerResult } = await client.database(db.id).containers.create(containerDefinition, { offerThroughput: 12000 });
const { body: containerResult } = await client.database(db.id).containers.create(containerDefinition, { offerThroughput: 12000 });
const container = await client.database(db.id).container(containerResult.id);
// tslint:disable:no-var-keyword
@ -315,9 +315,9 @@ describe("NodeJS CRUD Tests", function () {
it("nativeApi Should enable/disable script logging while executing stored procedure", async function () {
// create database
const { result: db } = await client.databases.create({ id: "sproc test database" });
const { body: db } = await client.databases.create({ id: "sproc test database" });
// create container
const { result: containerResult } = await client.database(db.id).containers.create({ id: "sample container" });
const { body: containerResult } = await client.database(db.id).containers.create({ id: "sample container" });
const container = await client.database(db.id).container(containerResult.id);

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

@ -236,15 +236,15 @@ describe("NodeJS CRUD Tests", function () {
await container.triggers.create(trigger);
}
// create document
const { result: document } = await container.items.create({ id: "doc1", key: "value" }, { preTriggerInclude: "t1" });
const { body: document } = await container.items.create({ id: "doc1", key: "value" }, { preTriggerInclude: "t1" });
assert.equal(document.id, "DOC1t1", "name should be capitalized");
const { result: document2 } = await container.items.create({ id: "doc2", key2: "value2" }, { preTriggerInclude: "t2" });
const { body: document2 } = await container.items.create({ id: "doc2", key2: "value2" }, { preTriggerInclude: "t2" });
assert.equal(document2.id, "doc2", "name shouldn't change");
const { result: document3 } = await container.items.create({ id: "Doc3", prop: "empty" }, { preTriggerInclude: "t3" });
const { body: document3 } = await container.items.create({ id: "Doc3", prop: "empty" }, { preTriggerInclude: "t3" });
assert.equal(document3.id, "doc3t3");
const { result: document4 } = await container.items.create({ id: "testing post trigger" }, { postTriggerInclude: "response1", preTriggerInclude: "t1" });
const { body: document4 } = await container.items.create({ id: "testing post trigger" }, { postTriggerInclude: "response1", preTriggerInclude: "t1" });
assert.equal(document4.id, "TESTING POST TRIGGERt1");
const { result: document5, headers } = await container.items.create({ id: "responseheaders" }, { preTriggerInclude: "t1" });
const { body: document5, headers } = await container.items.create({ id: "responseheaders" }, { preTriggerInclude: "t1" });
assert.equal(document5.id, "RESPONSEHEADERSt1");
try {
await container.items.create({ id: "Docoptype" }, { postTriggerInclude: "triggerOpType" });
@ -259,15 +259,15 @@ describe("NodeJS CRUD Tests", function () {
await container.triggers.upsert(trigger);
}
// create document
const { result: document } = await container.items.upsert({ id: "doc1", key: "value" }, { preTriggerInclude: "t1" });
const { body: document } = await container.items.upsert({ id: "doc1", key: "value" }, { preTriggerInclude: "t1" });
assert.equal(document.id, "DOC1t1", "name should be capitalized");
const { result: document2 } = await container.items.upsert({ id: "doc2", key2: "value2" }, { preTriggerInclude: "t2" });
const { body: document2 } = await container.items.upsert({ id: "doc2", key2: "value2" }, { preTriggerInclude: "t2" });
assert.equal(document2.id, "doc2", "name shouldn't change");
const { result: document3 } = await container.items.upsert({ id: "Doc3", prop: "empty" }, { preTriggerInclude: "t3" });
const { body: document3 } = await container.items.upsert({ id: "Doc3", prop: "empty" }, { preTriggerInclude: "t3" });
assert.equal(document3.id, "doc3t3");
const { result: document4 } = await container.items.upsert({ id: "testing post trigger" }, { postTriggerInclude: "response1", preTriggerInclude: "t1" });
const { body: document4 } = await container.items.upsert({ id: "testing post trigger" }, { postTriggerInclude: "response1", preTriggerInclude: "t1" });
assert.equal(document4.id, "TESTING POST TRIGGERt1");
const { result: document5, headers } = await container.items.upsert({ id: "responseheaders" }, { preTriggerInclude: "t1" });
const { body: document5, headers } = await container.items.upsert({ id: "responseheaders" }, { preTriggerInclude: "t1" });
assert.equal(document5.id, "RESPONSEHEADERSt1");
try {
await container.items.upsert({ id: "Docoptype" }, { postTriggerInclude: "triggerOpType" });

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

@ -58,14 +58,15 @@ describe("NodeJS CRUD Tests", function () {
it("nativeApi Validate container and Item TTL values.", async function () {
try {
const { result: db } = await client.databases.create({ id: "ttl test1 database" });
const { body: db } = await client.databases.create({ id: "ttl test1 database" });
const containerDefinition = {
id: "sample container1",
defaultTtl: 5,
};
const database = await client.database(db.id);
const { result: containerResult } = await database.containers.create(containerDefinition);
const { body: containerResult } = await database.containers.create(containerDefinition);
assert.equal(containerDefinition.defaultTtl, containerResult.defaultTtl);
const container = database.container(containerResult.id);
@ -101,7 +102,7 @@ describe("NodeJS CRUD Tests", function () {
}
async function checkItemExists(container: Container, createdItem: any) {
const { result: readItem } = await container.item(createdItem.id).read();
const { body: readItem } = await container.item(createdItem.id).read();
assert.equal(readItem.ttl, createdItem.ttl);
}
@ -118,7 +119,7 @@ describe("NodeJS CRUD Tests", function () {
itemDefinition.id = "doc4";
itemDefinition.ttl = 8;
const { result: doc } = await container.items.create(itemDefinition);
const { body: doc } = await container.items.create(itemDefinition);
await sleep(6000);
await positiveDefaultTtlStep4(container, doc);
@ -130,7 +131,7 @@ describe("NodeJS CRUD Tests", function () {
itemDefinition.id = "doc3";
itemDefinition.ttl = 2;
const { result: doc } = await container.items.create(itemDefinition);
const { body: doc } = await container.items.create(itemDefinition);
await sleep(4000);
await positiveDefaultTtlStep3(container, doc, itemDefinition);
}
@ -141,21 +142,21 @@ describe("NodeJS CRUD Tests", function () {
itemDefinition.id = "doc2";
itemDefinition.ttl = -1;
const { result: doc } = await container.items.create(itemDefinition);
const { body: doc } = await container.items.create(itemDefinition);
await sleep(5000);
await positiveDefaultTtlStep2(container, doc, itemDefinition);
}
it("nativeApi Validate Item TTL with positive defaultTtl.", async function () {
const { result: db } = await client.databases.create({ id: "ttl test2 database" });
const { body: db } = await client.databases.create({ id: "ttl test2 database" });
const containerDefinition = {
id: "sample container",
defaultTtl: 5,
};
const { result: containerResult } = await client.database(db.id).containers.create(containerDefinition);
const { body: containerResult } = await client.database(db.id).containers.create(containerDefinition);
const container = await client.database(db.id).container(containerResult.id);
@ -165,7 +166,7 @@ describe("NodeJS CRUD Tests", function () {
key: "value",
};
const { result: createdItem } = await container.items.create(itemDefinition);
const { body: createdItem } = await container.items.create(itemDefinition);
await sleep(7000);
await positiveDefaultTtlStep1(container, createdItem, itemDefinition);
});
@ -175,22 +176,22 @@ describe("NodeJS CRUD Tests", function () {
await checkItemGone(container, createdItem3);
// The Items with id doc1 and doc2 will never expire
const { result: readItem1 } = await container.item(createdItem1.id).read();
const { body: readItem1 } = await container.item(createdItem1.id).read();
assert.equal(readItem1.id, createdItem1.id);
const { result: readItem2 } = await container.item(createdItem2.id).read();
const { body: readItem2 } = await container.item(createdItem2.id).read();
assert.equal(readItem2.id, createdItem2.id);
}
it("nativeApi Validate Item TTL with -1 defaultTtl.", async function () {
const { result: db } = await client.databases.create({ id: "ttl test2 database" });
const { body: db } = await client.databases.create({ id: "ttl test2 database" });
const containerDefinition = {
id: "sample container",
defaultTtl: -1,
};
const { result: createdContainer } = await client.database(db.id).containers.create(containerDefinition);
const { body: createdContainer } = await client.database(db.id).containers.create(containerDefinition);
const container = await client.database(db.id).container(createdContainer.id);
@ -201,28 +202,28 @@ describe("NodeJS CRUD Tests", function () {
};
// the created Item 's ttl value would be -1 inherited from the container' s defaultTtl and this Item will never expire
const { result: createdItem1 } = await container.items.create(itemDefinition);
const { body: createdItem1 } = await container.items.create(itemDefinition);
// This Item is also set to never expire explicitly
itemDefinition.id = "doc2";
itemDefinition.ttl = -1;
const { result: createdItem2 } = await container.items.create(itemDefinition);
const { body: createdItem2 } = await container.items.create(itemDefinition);
itemDefinition.id = "doc3";
itemDefinition.ttl = 2;
const { result: createdItem3 } = await container.items.create(itemDefinition);
const { body: createdItem3 } = await container.items.create(itemDefinition);
await sleep(4000);
await minusOneDefaultTtlStep1(container, createdItem1, createdItem2, createdItem3);
});
it("nativeApi Validate Item TTL with no defaultTtl.", async function () {
const { result: db } = await client.databases.create({ id: "ttl test3 database" });
const { body: db } = await client.databases.create({ id: "ttl test3 database" });
const containerDefinition = { id: "sample container" };
const { result: createdContainer } = await client.database(db.id).containers.create(containerDefinition);
const { body: createdContainer } = await client.database(db.id).containers.create(containerDefinition);
const container = await client.database(db.id).container(createdContainer.id);
@ -233,7 +234,7 @@ describe("NodeJS CRUD Tests", function () {
ttl: 5,
};
const { result: createdItem } = await container.items.create(itemDefinition);
const { body: createdItem } = await container.items.create(itemDefinition);
// Created Item still exists even after ttl time has passed since the TTL is disabled at container level(no defaultTtl property defined)
await sleep(7000);
@ -260,7 +261,7 @@ describe("NodeJS CRUD Tests", function () {
itemDefinition.id = "doc2";
const { result: createdItem } = await container.items.create(itemDefinition);
const { body: createdItem } = await container.items.create(itemDefinition);
await sleep(5000);
await miscCasesStep4(container, createdItem, itemDefinition);
}
@ -268,7 +269,7 @@ describe("NodeJS CRUD Tests", function () {
async function miscCasesStep2(container: Container, itemDefinition: any) {
// Upsert the Item after 3 secs to reset the Item 's ttl
itemDefinition.key = "value2";
const { result: upsertedItem } = await container.items.upsert(itemDefinition);
const { body: upsertedItem } = await container.items.upsert(itemDefinition);
await sleep(7000);
// Upserted Item still exists after (3+7)10 secs from Item creation time( with container 's defaultTtl set to 8) since it' s ttl was reset after 3 secs by upserting it
await checkItemExists(container, upsertedItem);
@ -280,21 +281,21 @@ describe("NodeJS CRUD Tests", function () {
// the created Item should be gone now as the ttl time expired
await checkItemGone(container, createdItem);
// We can create a Item with the same id after the ttl time has expired
const { result: doc } = await container.items.create(itemDefinition);
const { body: doc } = await container.items.create(itemDefinition);
assert.equal(itemDefinition.id, doc.id);
await sleep(3000);
await miscCasesStep2(container, itemDefinition);
}
it("nativeApi Validate Item TTL Misc cases.", async function () {
const { result: db } = await client.databases.create({ id: "ttl test4 database" });
const { body: db } = await client.databases.create({ id: "ttl test4 database" });
const containerDefinition = {
id: "sample container",
defaultTtl: 8,
};
const { result: containerResult } = await client.database(db.id).containers.create(containerDefinition);
const { body: containerResult } = await client.database(db.id).containers.create(containerDefinition);
const container = await client.database(db.id).container(containerResult.id);
@ -304,7 +305,7 @@ describe("NodeJS CRUD Tests", function () {
key: "value",
};
const { result: createdItem } = await container.items.create(itemDefinition);
const { body: createdItem } = await container.items.create(itemDefinition);
await sleep(10000);
await miscCasesStep1(container, createdItem, itemDefinition);

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

@ -69,7 +69,7 @@ describe("Authorization", function () {
const clientReadPermission = new CosmosClient({ endpoint, auth: { resourceTokens: rTokens } });
const { result: coll } = await clientReadPermission.database(database.id)
const { body: coll } = await clientReadPermission.database(database.id)
.container(container.id)
.read();
assert.equal(coll.id, container.id, "invalid container");
@ -79,7 +79,7 @@ describe("Authorization", function () {
const clientReadPermission = new CosmosClient({ endpoint, auth: { permissionFeed: [collReadPermission] } });
// self link must be used to access a resource using permissionFeed
const { result: coll } = await clientReadPermission.database(database.id)
const { body: coll } = await clientReadPermission.database(database.id)
.container(container.id)
.read();
assert.equal(coll.id, container.id, "invalid container");
@ -99,11 +99,11 @@ describe("Authorization", function () {
});
it("Accessing document by permissionFeed of parent container", async function () {
const { result: createdDoc } = await container.items.create({ id: "document1" });
const { body: createdDoc } = await container.items.create({ id: "document1" });
const clientReadPermission = new CosmosClient({ endpoint, auth: { permissionFeed: [collReadPermission] } });
assert.equal("document1", createdDoc.id, "invalid documnet create");
const { result: readDoc } = await clientReadPermission.database(database.id)
const { body: readDoc } = await clientReadPermission.database(database.id)
.container(container.id)
.item(createdDoc.id)
.read<any>();

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

@ -33,16 +33,17 @@ describe("Create And Read Validation", function () {
};
// Create a container inside the database
const { result: containerDef } = await database.containers.create(containerBody);
const { body: containerDef } = await database.containers.create(containerBody);
const container = database.container(containerDef.id);
assert.equal(containerDef.id, containerBody.id, "invalid container Id");
// Add the document in the container
const { result: doc } = await container.items.create(testDoc);
const { body: doc } = await container.items.create(testDoc);
assert.equal(doc.id, testDoc.id, "invalid document Id");
// Read the container and see if it matches to the initial document
const { result: resultDoc } = await container.item(doc.id)
const { body: resultDoc } = await container.item(doc.id)
.read<{ id: string, content: string }>();
assert.equal(testDoc.content, resultDoc.content, "read document result is different from initial document");
} catch (err) {

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

@ -40,7 +40,8 @@ describe("NodeJS Incremental Feed Tests using 'a_im' and 'IfNoneMatch' options",
assert.equal(results.length, 2, "initial number of documents should be equal 2");
document.name = "xyz";
const { result: replaced } = await container.item(document.id).replace(document);
const { body: replaced } = await container.item(document.id).replace(document);
assert.deepEqual(replaced.name, "xyz", "replaced document should be valid");
options = {
@ -78,7 +79,7 @@ describe("NodeJS Incremental Feed Tests using 'a_im' and 'IfNoneMatch' options",
let { result, headers } = await query.current();
assert(headers.etag, "listDocuments response should have etag header");
const { result: document } = await container.items.create({ id: "doc2", prop: 1 });
const { body: document } = await container.items.create({ id: "doc2", prop: 1 });
options = {
a_im: "Incremental feed",

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

@ -48,14 +48,13 @@ describe("Test Query Metrics On Single Partition Collection", function () {
const testQueryMetricsOnSinglePartition = async function (document: any) {
try {
const databaseBody = { id: databaseId };
const { result: databaseDef } = await client.databases.create(databaseBody);
const { body: databaseDef } = await client.databases.create(databaseBody);
const database = client.database(databaseDef.id);
const collectionDefinition = { id: collectionId };
const collectionOptions = { offerThroughput: 4000 };
const { result: createdCollectionDef } =
const { body: createdCollectionDef } =
await database.containers.create(collectionDefinition, collectionOptions);
const createdContainer = database.container(createdCollectionDef.id);

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

@ -1,4 +1,4 @@
import * as assert from "assert";
import * as assert from "assert";
import * as sinon from "sinon";
import { Base, Constants, CosmosClient, IHeaders } from "../../";
import { ConsistencyLevel, PartitionKind } from "../../documents";
@ -56,17 +56,17 @@ describe("Session Token", function () {
let index1;
let index2;
const { result: databaseDef } = await client.databases.create(databaseBody);
await client.databases.create(databaseBody);
const database = client.database(databaseDef.id);
const { result: createdContainerDef } =
const { body: createdContainerDef } =
await database.containers.create(containerDefinition, containerOptions);
const container = database.container(createdContainerDef.id);
assert.equal(postSpy.lastCall.args[3][Constants.HttpHeaders.SessionToken], undefined);
// TODO: testing implementation detail by looking at containerResourceIdToSesssionTokens
assert.deepEqual(client.documentClient.sessionContainer.collectionResourceIdToSessionTokens, {});
const { result: document1 } = await container.items.create({ id: "1" });
const { body: document1 } = await container.items.create({ id: "1" });
assert.equal(postSpy.lastCall.args[3][Constants.HttpHeaders.SessionToken], undefined);
let tokens = getToken(client.documentClient.sessionContainer.collectionResourceIdToSessionTokens);
@ -74,7 +74,7 @@ describe("Session Token", function () {
assert.notEqual(tokens[index1], undefined);
let firstPartitionLSN = tokens[index1];
const { result: document2 } = await container.items.create({ id: "2" });
const { body: document2 } = await container.items.create({ id: "2" });
assert.equal(postSpy.lastCall.args[3][Constants.HttpHeaders.SessionToken],
client.documentClient.sessionContainer.getCombinedSessionToken(tokens));
@ -84,14 +84,15 @@ describe("Session Token", function () {
assert.notEqual(tokens[index2], undefined);
let secondPartitionLSN = tokens[index2];
const { result: document12 } = await container.item(document1.id, "1").read();
await container.item(document1.id, "1").read();
assert.equal(getSpy.lastCall.args[2][Constants.HttpHeaders.SessionToken],
client.documentClient.sessionContainer.getCombinedSessionToken(tokens));
tokens = getToken(client.documentClient.sessionContainer.collectionResourceIdToSessionTokens);
assert.equal(tokens[index1], firstPartitionLSN);
assert.equal(tokens[index2], secondPartitionLSN);
const { result: document13 } =
const { body: document13 } =
await container.items.upsert({ id: "1", operation: "upsert" }, { partitionKey: "1" });
assert.equal(postSpy.lastCall.args[3][Constants.HttpHeaders.SessionToken],
client.documentClient.sessionContainer.getCombinedSessionToken(tokens));
@ -100,7 +101,8 @@ describe("Session Token", function () {
assert.equal(tokens[index2], secondPartitionLSN);
firstPartitionLSN = tokens[index1];
const { result: document22 } = await container.item(document2.id, "2").delete();
await container.item(document2.id, "2").delete();
assert.equal(deleteSpy.lastCall.args[2][Constants.HttpHeaders.SessionToken],
client.documentClient.sessionContainer.getCombinedSessionToken(tokens));
tokens = getToken(client.documentClient.sessionContainer.collectionResourceIdToSessionTokens);
@ -108,9 +110,8 @@ describe("Session Token", function () {
assert.equal(tokens[index2], (Number(secondPartitionLSN) + 1).toString());
secondPartitionLSN = tokens[index2];
const { result: document14 } =
await container.item(document13.id)
.replace({ id: "1", operation: "replace" }, { partitionKey: "1" });
await container.item(document13.id)
.replace({ id: "1", operation: "replace" }, { partitionKey: "1" });
assert.equal(putSpy.lastCall.args[3][Constants.HttpHeaders.SessionToken],
client.documentClient.sessionContainer.getCombinedSessionToken(tokens));
tokens = getToken(client.documentClient.sessionContainer.collectionResourceIdToSessionTokens);
@ -122,7 +123,7 @@ describe("Session Token", function () {
const queryOptions = { partitionKey: "1" };
const queryIterator = container.items.query(query, queryOptions);
const { result } = await queryIterator.toArray();
await queryIterator.toArray();
assert.equal(postSpy.lastCall.args[3][Constants.HttpHeaders.SessionToken],
client.documentClient.sessionContainer.getCombinedSessionToken(tokens));
tokens = getToken(client.documentClient.sessionContainer.collectionResourceIdToSessionTokens);
@ -141,7 +142,7 @@ describe("Session Token", function () {
});
it("validate 'lsn not caught up' error for higher lsn and clearing session token", async function () {
const { result: databaseDef } = await client.databases.create(databaseBody);
const { body: databaseDef } = await client.databases.create(databaseBody);
const database = client.database(databaseDef.id);
const increaseLSN = function (oldTokens: any) {
for (const coll in oldTokens) {
@ -182,8 +183,9 @@ describe("Session Token", function () {
it.skip("client should not have session token of a container created by another client", async function () {
const client2 = new CosmosClient({ endpoint, auth: { masterKey }, consistencyLevel: ConsistencyLevel.Session });
const { result: databaseDef } = await client.databases.create(databaseBody);
const { body: databaseDef } = await client.databases.create(databaseBody);
const database = client.database(databaseDef.id);
await database.containers.create(containerDefinition, containerOptions);
const container = database.container(containerDefinition.id);
await container.read();
@ -191,11 +193,10 @@ describe("Session Token", function () {
.container(containerDefinition.id)
.delete();
const { result: createdCollection2 } =
await client2.database(databaseDef.id)
await client2.database(databaseDef.id)
.containers.create(containerDefinition, containerOptions);
const { result: collection2 } = await client2.database(databaseDef.id)
await client2.database(databaseDef.id)
.container(containerDefinition.id)
.read();
assert.equal(client.documentClient.getSessionToken(container.url), ""); // TODO: _self
@ -207,14 +208,15 @@ describe("Session Token", function () {
const client2 = new CosmosClient({
endpoint, auth: { masterKey }, consistencyLevel: ConsistencyLevel.Session,
});
const { result: databaseDef } = await client.databases.create(databaseBody);
const { body: databaseDef } = await client.databases.create(databaseBody);
const db = client.database(databaseDef.id);
const { result: createdContainerDef } =
const { body: createdContainerDef } =
await db.containers.create(containerDefinition, containerOptions);
const createdContainer = db.container(createdContainerDef.id);
const { result: createdDocument } = await createdContainer.items.create({ id: "1" });
const { body: createdDocument } = await createdContainer.items.create({ id: "1" });
const requestOptions = { partitionKey: "1" };
await client2.database(databaseDef.id)
.container(createdContainerDef.id)