-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.ts
More file actions
254 lines (225 loc) · 7.46 KB
/
Copy pathindex.ts
File metadata and controls
254 lines (225 loc) · 7.46 KB
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
import { tryit } from 'radash';
import { TypeDB, SessionType, TypeDBCredential } from 'typedb-driver';
import { defaultConfig } from './default.config';
import { bormDefine } from './define';
import { enrichSchema } from './helpers';
import type {
AllDbHandles,
BQLMutation,
BQLResponse,
BQLResponseMulti,
BormConfig,
BormSchema,
DBHandles,
EnrichedBormSchema,
MutationConfig,
QueryConfig,
RawBQLQuery,
} from './types';
import { enableMapSet } from 'immer';
import { runMutationMachine } from './stateMachine/mutation/mutationMachine';
import { runQueryMachine } from './stateMachine/query/queryMachine';
import { SimpleSurrealClient } from './adapters/surrealDB/client';
import { Client } from 'pg';
export * from './types';
type BormProps = {
schema: BormSchema;
config: BormConfig;
};
/// Global config
// immer
enableMapSet();
class BormClient {
private schema: BormSchema;
private config: BormConfig;
private dbHandles?: DBHandles;
constructor({ schema, config }: BormProps) {
this.schema = schema;
this.config = config;
}
getDbHandles = () => this.dbHandles;
init = async () => {
const dbHandles: AllDbHandles = { typeDB: new Map(), surrealDB: new Map(), postgresDB: new Map() };
await Promise.all(
this.config.dbConnectors.map(async (dbc) => {
if (dbc.provider === 'postgresDB') {
const client = new Client({
host: dbc.host,
port: dbc.port,
user: dbc.user,
password: dbc.password,
database: dbc.dbName,
});
await client.connect();
dbHandles.postgresDB.set(dbc.id, { client });
} else if (dbc.provider === 'surrealDB') {
const client = new SimpleSurrealClient({
url: dbc.url,
username: dbc.username,
password: dbc.password,
namespace: dbc.namespace,
database: dbc.dbName,
});
// const pool = new SurrealPool({
// url: dbc.url,
// username: dbc.username,
// password: dbc.password,
// namespace: dbc.namespace,
// database: dbc.dbName,
// totalConnections: 8,
// });
dbHandles.surrealDB.set(dbc.id, { client, providerConfig: dbc.providerConfig });
} else if (dbc.provider === 'typeDB' && dbc.dbName) {
// const client = await TypeDB.coreClient(dbc.url);
// const clientErr = undefined;
const [clientErr, client] = await tryit(TypeDB.coreDriver)(dbc.url);
if (clientErr) {
const message = `[BORM:${dbc.provider}:${dbc.dbName}:core] ${
// clientErr.messageTemplate?._messageBody() ?? "Can't create TypeDB Client"
clientErr.message ?? "Can't create TypeDB Client"
}`;
throw new Error(message);
}
try {
const session = await client.session(dbc.dbName, SessionType.DATA);
dbHandles.typeDB.set(dbc.id, { client, session });
} catch (sessionErr: any) {
const message = `[BORM:${dbc.provider}:${dbc.dbName}:session] ${
// eslint-disable-next-line no-underscore-dangle
(sessionErr.messageTemplate?._messageBody() || sessionErr.message) ?? "Can't create TypeDB Session"
}`;
throw new Error(message);
}
} else if (dbc.provider === 'typeDBCluster' && dbc.dbName) {
const credential = new TypeDBCredential(dbc.username, dbc.password, dbc.tlsRootCAPath);
const [clientErr, client] = await tryit(TypeDB.cloudDriver)(dbc.addresses, credential);
if (clientErr) {
const message = `[BORM:${dbc.provider}:${dbc.dbName}:core] ${
// clientErr.messageTemplate?._messageBody() ?? "Can't create TypeDB Client"
clientErr.message ?? "Can't create TypeDB Cluster Client"
}`;
throw new Error(message);
}
try {
const session = await client.session(dbc.dbName, SessionType.DATA);
dbHandles.typeDB.set(dbc.id, { client, session });
} catch (sessionErr: any) {
const message = `[BORM:${dbc.provider}:${dbc.dbName}:session] ${
// eslint-disable-next-line no-underscore-dangle
(sessionErr.messageTemplate?._messageBody() || sessionErr.message) ?? "Can't create TypeDB Session"
}`;
throw new Error(message);
}
}
}),
);
const enrichedSchema = enrichSchema(this.schema, dbHandles);
this.schema = enrichedSchema as EnrichedBormSchema;
this.dbHandles = dbHandles;
};
#enforceConnection = async () => {
if (!this.dbHandles) {
await this.init();
if (!this.dbHandles) {
throw new Error("Can't init BormClient");
}
}
};
introspect = async () => {
await this.#enforceConnection();
return this.schema;
};
define = async () => {
await this.#enforceConnection();
if (!this.dbHandles) {
throw new Error('dbHandles undefined');
}
const schemas = await bormDefine(this.config, this.schema as EnrichedBormSchema, this.dbHandles);
return schemas;
};
/// no types yet, but we can do "as ..." after getting the type fro the schema
// query = async (query: RawBQLQuery | RawBQLQuery[], queryConfig?: QueryConfig) => {
// const handles = this.dbHandles;
// if (!handles) {
// throw new Error('dbHandles undefined');
// }
// await this.#enforceConnection();
// const qConfig = {
// ...this.config,
// query: { ...defaultConfig.query, ...this.config.query, ...queryConfig },
// };
// // @ts-expect-error type of Query is incorrect
// return queryPipeline(query, qConfig, this.schema, handles);
// };
query = async (query: RawBQLQuery | RawBQLQuery[], queryConfig?: QueryConfig) => {
await this.#enforceConnection();
const qConfig = {
...this.config,
query: {
...defaultConfig.query,
...this.config.query,
...queryConfig,
},
};
const isBatched = Array.isArray(query);
const queries = isBatched ? query : [query];
const [errorRes, res] = await tryit(runQueryMachine)(
queries,
this.schema as EnrichedBormSchema,
qConfig,
this.dbHandles as DBHandles,
);
if (errorRes) {
//@ts-expect-error - errorRes has error. Also no idea where the error: comes from
const error = new Error(errorRes.error);
//@ts-expect-error - errorRes has error. Also no idea where the error: comes from
error.stack = errorRes.error.stack;
throw error;
}
const result = res.bql.res as BQLResponse[];
return isBatched ? result : result[0];
};
mutate = async (mutation: BQLMutation, mutationConfig?: MutationConfig) => {
await this.#enforceConnection();
const mConfig = {
...this.config,
mutation: {
...defaultConfig.mutation,
...this.config.mutation,
...mutationConfig,
},
};
const [errorRes, res] = await tryit(runMutationMachine)(
mutation,
this.schema as EnrichedBormSchema,
mConfig,
this.dbHandles as DBHandles,
);
if (errorRes) {
//console.error(errorRes.error.stack.split('\n').slice(0, 4).join('\n'));
//@ts-expect-error - errorRes has error. Also no idea where the error: comes from
const error = new Error(errorRes.error.message);
//@ts-expect-error - errorRes has error. Also no idea where the error: comes from
error.stack = errorRes.error.stack;
throw error;
}
const result = res.bql.res;
return result as BQLResponseMulti;
};
close = async () => {
if (!this.dbHandles) {
return;
}
//todo: probably migrate dbHandles to be an array, where each handle has .type="typeDB" for instance
this.dbHandles.typeDB?.forEach(async ({ client, session }) => {
if (session.isOpen()) {
await session.close();
}
await client.close();
});
// TODO: Close SurrealDB clients.
// Currently there's no `close()` method in the client.
// See https://github.com/surrealdb/surrealdb.node/issues/36
};
}
export default BormClient;