/
Items.ts
268 lines (247 loc) · 10.5 KB
/
Items.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import uuid from "uuid/v4";
import { ChangeFeedIterator } from "../../ChangeFeedIterator";
import { ChangeFeedOptions } from "../../ChangeFeedOptions";
import { ClientContext } from "../../ClientContext";
import { getIdFromLink, getPathFromLink, isResourceValid, ResourceType } from "../../common";
import { extractPartitionKey } from "../../extractPartitionKey";
import { FetchFunctionCallback, SqlQuerySpec } from "../../queryExecutionContext";
import { QueryIterator } from "../../queryIterator";
import { FeedOptions, RequestOptions } from "../../request";
import { Container } from "../Container";
import { Item } from "./Item";
import { ItemDefinition } from "./ItemDefinition";
import { ItemResponse } from "./ItemResponse";
function isChangeFeedOptions(options: unknown): options is ChangeFeedOptions {
const optionsType = typeof options;
return options && !(optionsType === "string" || optionsType === "boolean" || optionsType === "number");
}
/**
* Operations for creating new items, and reading/querying all items
*
* @see {@link Item} for reading, replacing, or deleting an existing container; use `.item(id)`.
*/
export class Items {
/**
* Create an instance of {@link Items} linked to the parent {@link Container}.
* @param container The parent container.
* @hidden
*/
constructor(public readonly container: Container, private readonly clientContext: ClientContext) {}
/**
* Queries all items.
* @param query Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.
* @param options Used for modifying the request (for instance, specifying the partition key).
* @example Read all items to array.
* ```typescript
* const querySpec: SqlQuerySpec = {
* query: "SELECT * FROM Families f WHERE f.lastName = @lastName",
* parameters: [
* {name: "@lastName", value: "Hendricks"}
* ]
* };
* const {result: items} = await items.query(querySpec).toArray();
* ```
*/
public query(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>;
/**
* Queries all items.
* @param query Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query.
* @param options Used for modifying the request (for instance, specifying the partition key).
* @example Read all items to array.
* ```typescript
* const querySpec: SqlQuerySpec = {
* query: "SELECT firstname FROM Families f WHERE f.lastName = @lastName",
* parameters: [
* {name: "@lastName", value: "Hendricks"}
* ]
* };
* const {result: items} = await items.query<{firstName: string}>(querySpec).toArray();
* ```
*/
public query<T>(query: string | SqlQuerySpec, options: FeedOptions): QueryIterator<T>;
public query<T>(query: string | SqlQuerySpec, options: FeedOptions = {}): QueryIterator<T> {
const path = getPathFromLink(this.container.url, ResourceType.item);
const id = getIdFromLink(this.container.url);
const fetchFunction: FetchFunctionCallback = (innerOptions: FeedOptions) => {
return this.clientContext.queryFeed({
path,
resourceType: ResourceType.item,
resourceId: id,
resultFn: result => (result ? result.Documents : []),
query,
options: innerOptions
});
};
return new QueryIterator(this.clientContext, query, options, fetchFunction, this.container.url, ResourceType.item);
}
/**
* Create a `ChangeFeedIterator` to iterate over pages of changes
*
* @param partitionKey
* @param changeFeedOptions
*
* @example Read from the beginning of the change feed.
* ```javascript
* const iterator = items.readChangeFeed({ startFromBeginning: true });
* const firstPage = await iterator.executeNext();
* const firstPageResults = firstPage.result
* const secondPage = await iterator.executeNext();
* ```
*/
public readChangeFeed(
partitionKey: string | number | boolean,
changeFeedOptions: ChangeFeedOptions
): ChangeFeedIterator<any>;
/**
* Create a `ChangeFeedIterator` to iterate over pages of changes
*
* @param changeFeedOptions
*/
public readChangeFeed(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<any>;
/**
* Create a `ChangeFeedIterator` to iterate over pages of changes
*
* @param partitionKey
* @param changeFeedOptions
*/
public readChangeFeed<T>(
partitionKey: string | number | boolean,
changeFeedOptions: ChangeFeedOptions
): ChangeFeedIterator<T>;
/**
* Create a `ChangeFeedIterator` to iterate over pages of changes
*
* @param changeFeedOptions
*/
public readChangeFeed<T>(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<T>;
public readChangeFeed<T>(
partitionKeyOrChangeFeedOptions?: string | number | boolean | ChangeFeedOptions,
changeFeedOptions?: ChangeFeedOptions
): ChangeFeedIterator<T> {
let partitionKey: string | number | boolean;
if (!changeFeedOptions && isChangeFeedOptions(partitionKeyOrChangeFeedOptions)) {
partitionKey = undefined;
changeFeedOptions = partitionKeyOrChangeFeedOptions;
} else if (partitionKeyOrChangeFeedOptions !== undefined && !isChangeFeedOptions(partitionKeyOrChangeFeedOptions)) {
partitionKey = partitionKeyOrChangeFeedOptions;
}
if (!changeFeedOptions) {
throw new Error("changeFeedOptions must be a valid object");
}
const path = getPathFromLink(this.container.url, ResourceType.item);
const id = getIdFromLink(this.container.url);
return new ChangeFeedIterator<T>(this.clientContext, id, path, partitionKey, changeFeedOptions);
}
/**
* Read all items.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param options Used for modifying the request (for instance, specifying the partition key).
* @example Read all items to array.
* ```typescript
* const {body: containerList} = await items.readAll().toArray();
* ```
*/
public readAll(options?: FeedOptions): QueryIterator<ItemDefinition>;
/**
* Read all items.
*
* Any provided type, T, is not necessarily enforced by the SDK.
* You may get more or less properties and it's up to your logic to enforce it.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param options Used for modifying the request (for instance, specifying the partition key).
* @example Read all items to array.
* ```typescript
* const {body: containerList} = await items.readAll().toArray();
* ```
*/
public readAll<T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T>;
public readAll<T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T> {
return this.query<T>("SELECT * from c", options);
}
/**
* Create a item.
*
* Any provided type, T, is not necessarily enforced by the SDK.
* You may get more or less properties and it's up to your logic to enforce it.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param body Represents the body of the item. Can contain any number of user defined properties.
* @param options Used for modifying the request (for instance, specifying the partition key).
*/
public async create<T extends ItemDefinition = any>(body: T, options: RequestOptions = {}): Promise<ItemResponse<T>> {
const { resource: partitionKeyDefinition } = await this.container.getPartitionKeyDefinition();
const partitionKey = extractPartitionKey(body, partitionKeyDefinition);
// Generate random document id if the id is missing in the payload and
// options.disableAutomaticIdGeneration != true
if ((body.id === undefined || body.id === "") && !options.disableAutomaticIdGeneration) {
body.id = uuid();
}
const err = {};
if (!isResourceValid(body, err)) {
throw err;
}
const path = getPathFromLink(this.container.url, ResourceType.item);
const id = getIdFromLink(this.container.url);
const response = await this.clientContext.create<T>({
body,
path,
resourceType: ResourceType.item,
resourceId: id,
options,
partitionKey
});
const ref = new Item(this.container, (response.result as any).id, partitionKey, this.clientContext);
return new ItemResponse(response.result, response.headers, response.code, response.substatus, ref);
}
/**
* Upsert an item.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param body Represents the body of the item. Can contain any number of user defined properties.
* @param options Used for modifying the request (for instance, specifying the partition key).
*/
public async upsert(body: any, options?: RequestOptions): Promise<ItemResponse<ItemDefinition>>;
/**
* Upsert an item.
*
* Any provided type, T, is not necessarily enforced by the SDK.
* You may get more or less properties and it's up to your logic to enforce it.
*
* There is no set schema for JSON items. They may contain any number of custom properties.
*
* @param body Represents the body of the item. Can contain any number of user defined properties.
* @param options Used for modifying the request (for instance, specifying the partition key).
*/
public async upsert<T extends ItemDefinition>(body: T, options?: RequestOptions): Promise<ItemResponse<T>>;
public async upsert<T extends ItemDefinition>(body: T, options: RequestOptions = {}): Promise<ItemResponse<T>> {
const { resource: partitionKeyDefinition } = await this.container.getPartitionKeyDefinition();
const partitionKey = extractPartitionKey(body, partitionKeyDefinition);
// Generate random document id if the id is missing in the payload and
// options.disableAutomaticIdGeneration != true
if ((body.id === undefined || body.id === "") && !options.disableAutomaticIdGeneration) {
body.id = uuid();
}
const err = {};
if (!isResourceValid(body, err)) {
throw err;
}
const path = getPathFromLink(this.container.url, ResourceType.item);
const id = getIdFromLink(this.container.url);
const response = await this.clientContext.upsert<T>({
body,
path,
resourceType: ResourceType.item,
resourceId: id,
options,
partitionKey
});
const ref = new Item(this.container, (response.result as any).id, partitionKey, this.clientContext);
return new ItemResponse(response.result, response.headers, response.code, response.substatus, ref);
}
}