forked from denodrivers/mongo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.ts
106 lines (97 loc) · 2.59 KB
/
database.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
import { Collection } from "./collection/mod.ts";
import { CommandCursor } from "./protocol/mod.ts";
import { CreateUserOptions } from "./types.ts";
import { Cluster } from "./cluster.ts";
import { Document } from "../deps.ts";
interface ListCollectionsReponse {
cursor: {
id: bigint;
ns: string;
firstBatch: [
{
name: string;
type: "collection";
},
];
};
ok: 1;
}
export interface ListCollectionsResult {
name: string;
type: "collection";
}
export class Database {
#cluster: Cluster;
constructor(cluster: Cluster, readonly name: string) {
this.#cluster = cluster;
}
collection<T = Document>(name: string): Collection<T> {
return new Collection<T>(this.#cluster.protocol, this.name, name);
}
listCollections(options: {
filter?: Document;
nameOnly?: boolean;
authorizedCollections?: boolean;
comment?: Document;
} = {}): CommandCursor<ListCollectionsResult> {
return new CommandCursor<ListCollectionsResult>(
this.#cluster.protocol,
async () => {
const { cursor } = await this.#cluster.protocol.commandSingle<
ListCollectionsReponse
>(this.name, {
listCollections: 1,
...options,
});
return {
id: cursor.id,
ns: cursor.ns,
firstBatch: cursor.firstBatch,
};
},
);
}
async listCollectionNames(options: {
filter?: Document;
authorizedCollections?: boolean;
comment?: Document;
} = {}): Promise<string[]> {
const cursor = this.listCollections({
...options,
nameOnly: true,
authorizedCollections: true,
});
const names: string[] = [];
for await (const item of cursor) {
names.push(item.name);
}
return names;
}
createUser(
username: string,
password: string,
options?: CreateUserOptions,
) {
return this.#cluster.protocol.commandSingle(this.name, {
createUser: options?.username ?? username,
pwd: options?.password ?? password,
customData: options?.customData,
roles: options?.roles ?? [],
writeConcern: options?.writeConcern,
authenticationRestrictions: options?.authenticationRestrictions,
mechanisms: options?.mechanisms,
digestPassword: options?.digestPassword,
comment: options?.comment,
});
}
dropUser(username: string, options: {
writeConcern?: Document;
comment?: Document;
} = {}) {
return this.#cluster.protocol.commandSingle(this.name, {
dropUser: username,
writeConcern: options?.writeConcern,
comment: options?.comment,
});
}
}