-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathcommon_functions.ts
79 lines (73 loc) · 2.24 KB
/
common_functions.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
import type { Document } from '../bson';
import type { Collection } from '../collection';
import type { Db } from '../db';
import type { ReadPreference } from '../read_preference';
import type { ClientSession } from '../sessions';
/** @public */
export interface IndexInformationOptions {
full?: boolean;
readPreference?: ReadPreference;
session?: ClientSession;
}
/**
* Retrieves this collections index info.
*
* @param db - The Db instance on which to retrieve the index info.
* @param name - The name of the collection.
*/
export async function indexInformation(db: Db, name: string): Promise<any>;
export async function indexInformation(
db: Db,
name: string,
options?: IndexInformationOptions
): Promise<any>;
export async function indexInformation(
db: Db,
name: string,
options?: IndexInformationOptions
): Promise<any> {
if (options == null) {
options = {};
}
// If we specified full information
const full = options.full == null ? false : options.full;
// Get the list of indexes of the specified collection
const indexes = await db.collection(name).listIndexes(options).toArray();
if (full) return indexes;
const info: Record<string, Array<[string, unknown]>> = {};
for (const index of indexes) {
info[index.name] = Object.entries(index.key);
}
return info;
}
export function maybeAddIdToDocuments(
coll: Collection,
docs: Document[],
options: { forceServerObjectId?: boolean }
): Document[];
export function maybeAddIdToDocuments(
coll: Collection,
docs: Document,
options: { forceServerObjectId?: boolean }
): Document;
export function maybeAddIdToDocuments(
coll: Collection,
docOrDocs: Document[] | Document,
options: { forceServerObjectId?: boolean }
): Document[] | Document {
const forceServerObjectId =
typeof options.forceServerObjectId === 'boolean'
? options.forceServerObjectId
: coll.s.db.options?.forceServerObjectId;
// no need to modify the docs if server sets the ObjectId
if (forceServerObjectId === true) {
return docOrDocs;
}
const transform = (doc: Document): Document => {
if (doc._id == null) {
doc._id = coll.s.pkFactory.createPk();
}
return doc;
};
return Array.isArray(docOrDocs) ? docOrDocs.map(transform) : transform(docOrDocs);
}