@rws-framework/db 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,253 @@
1
+ import { PrismaClient } from '@prisma/client';
2
+ import { Collection, Db, MongoClient } from 'mongodb';
3
+ import {ITimeSeries} from '../types/ITimeSeries';
4
+ import { IModel } from '../models/_model';
5
+ import chalk from 'chalk';
6
+ import { IDbConfigHandler } from '../types/DbConfigHandler';
7
+
8
+ interface IDBClientCreate {
9
+ dbUrl?: string;
10
+ dbName?: string;
11
+ }
12
+
13
+ class DBService {
14
+ private client: PrismaClient;
15
+ private opts: IDBClientCreate = null;
16
+ private connected = false;
17
+
18
+ constructor(private configService: IDbConfigHandler){}
19
+
20
+ private connectToDB(opts: IDBClientCreate = null) {
21
+ if(opts){
22
+ this.opts = opts;
23
+ }else{
24
+ this.opts = {
25
+ dbUrl: this.configService.get('mongo_url'),
26
+ dbName: this.configService.get('mongo_db'),
27
+ };
28
+ }
29
+
30
+ if(!this.opts.dbUrl){
31
+ console.log(chalk.red('No database config set in @rws-framework/db'));
32
+
33
+ return;
34
+ }
35
+
36
+ try{
37
+ this.client = new PrismaClient({
38
+ datasources: {
39
+ db: {
40
+ url: this.opts.dbUrl
41
+ },
42
+ },
43
+ });
44
+
45
+ this.connected = true;
46
+ } catch (e: Error | any){
47
+ console.error(e);
48
+
49
+ throw new Error('PRISMA CONNECTION ERROR');
50
+ }
51
+ }
52
+
53
+ private async createBaseMongoClient(): Promise<MongoClient>
54
+ {
55
+ const dbUrl = this.opts?.dbUrl || this.configService.get('mongo_url');
56
+ const client = new MongoClient(dbUrl);
57
+
58
+ await client.connect();
59
+
60
+ return client;
61
+
62
+ }
63
+
64
+ private async createBaseMongoClientDB(): Promise<Db>
65
+ {
66
+ const dbName = this.opts?.dbName || this.configService.get('mongo_db');
67
+ const client = await this. createBaseMongoClient();
68
+ return client.db(dbName);
69
+ }
70
+
71
+ public async cloneDatabase(source: string, target: string): Promise<void> {
72
+ const client = await this.createBaseMongoClient();
73
+
74
+ // Source and target DB
75
+ const sourceDb = client.db(source);
76
+ const targetDb = client.db(target);
77
+
78
+ // Get all collections from source DB
79
+ const collections = await sourceDb.listCollections().toArray();
80
+
81
+ // Loop over all collections and copy them to the target DB
82
+ for (const collection of collections) {
83
+ const docs = await sourceDb.collection(collection.name).find({}).toArray();
84
+ await targetDb.collection(collection.name).insertMany(docs);
85
+ }
86
+
87
+ await client.close();
88
+ }
89
+
90
+ async watchCollection(collectionName: string, preRun: () => void): Promise<any>
91
+ {
92
+ const db = await this.createBaseMongoClientDB();
93
+ const collection = db.collection(collectionName);
94
+
95
+ const changeStream = collection.watch();
96
+ return new Promise((resolve) => {
97
+ changeStream.on('change', (change) => {
98
+ resolve(change);
99
+ });
100
+
101
+ preRun();
102
+ });
103
+ }
104
+
105
+ async insert(data: any, collection: string, isTimeSeries: boolean = false) {
106
+
107
+ let result: any = data;
108
+ // Insert time-series data outside of the transaction
109
+
110
+ if(isTimeSeries){
111
+ const db = await this.createBaseMongoClientDB();
112
+ const collectionHandler = db.collection(collection);
113
+
114
+ const insert = await collectionHandler.insertOne(data);
115
+
116
+ result = await this.findOneBy(collection, { id: insert.insertedId.toString() });
117
+ return result;
118
+ }
119
+
120
+ const prismaCollection = this.getCollectionHandler(collection);
121
+
122
+ result = await prismaCollection.create({ data });
123
+
124
+ return await this.findOneBy(collection, { id: result.id });
125
+ }
126
+
127
+ async update(data: any, collection: string): Promise<IModel>
128
+ {
129
+ const model_id: string = data.id;
130
+ delete data['id'];
131
+
132
+ const prismaCollection = this.getCollectionHandler(collection);
133
+
134
+ await prismaCollection.update({
135
+ where: {
136
+ id: model_id,
137
+ },
138
+ data: data,
139
+ });
140
+
141
+
142
+ return await this.findOneBy(collection, { id: model_id });
143
+ }
144
+
145
+
146
+ async findOneBy(collection: string, conditions: any, fields: string[] | null = null, ordering: { [fieldName: string]: string } = null, allowRelations: boolean = true): Promise<IModel|null>
147
+ {
148
+ const params: any = { where: conditions };
149
+
150
+ if(fields){
151
+ params.select = {};
152
+ fields.forEach((fieldName: string) => {
153
+ params.select[fieldName] = true;
154
+ });
155
+ }
156
+
157
+ if(ordering){
158
+ params.orderBy = ordering;
159
+ }
160
+
161
+ const retData = await this.getCollectionHandler(collection).findFirst(params);
162
+
163
+ return retData;
164
+ }
165
+
166
+ async delete(collection: string, conditions: any): Promise<void>
167
+ {
168
+ await this.getCollectionHandler(collection).deleteMany({ where: conditions });
169
+ return;
170
+ }
171
+
172
+ async findBy(collection: string, conditions: any, fields: string[] | null = null, ordering: { [fieldName: string]: string } = null, allowRelations: boolean = true): Promise<IModel[]>
173
+ {
174
+ const params: any ={ where: conditions };
175
+
176
+ if(fields){
177
+ params.select = {};
178
+ fields.forEach((fieldName: string) => {
179
+ params.select[fieldName] = true;
180
+ });
181
+ }
182
+
183
+ if(ordering){
184
+ params.orderBy = ordering;
185
+ }
186
+
187
+ const retData = await this.getCollectionHandler(collection).findMany(params);
188
+
189
+ return retData;
190
+ }
191
+
192
+ async collectionExists(collection_name: string): Promise<boolean>
193
+ {
194
+ const dbUrl = this.opts?.dbUrl || this.configService.get('mongo_url');
195
+ const client = new MongoClient(dbUrl);
196
+
197
+ try {
198
+ await client.connect();
199
+
200
+ const db = client.db(this.configService.get('mongo_db'));
201
+
202
+ const collections = await db.listCollections().toArray();
203
+ const existingCollectionNames = collections.map((collection) => collection.name);
204
+
205
+ return existingCollectionNames.includes(collection_name);
206
+ } catch (error) {
207
+ console.error('Error connecting to MongoDB:', error);
208
+
209
+ throw error;
210
+ }
211
+ }
212
+
213
+ async createTimeSeriesCollection(collection_name: string): Promise<Collection<ITimeSeries>>
214
+ {
215
+ try {
216
+ const db = await this.createBaseMongoClientDB();
217
+
218
+ // Create a time series collection
219
+ const options = {
220
+ timeseries: {
221
+ timeField: 'timestamp', // Replace with your timestamp field
222
+ metaField: 'params' // Replace with your metadata field
223
+ }
224
+ };
225
+
226
+ await db.createCollection(collection_name, options); // Replace with your collection name
227
+
228
+ return db.collection(collection_name);
229
+
230
+ } catch (error) {
231
+ console.error('Error connecting to MongoDB:', error);
232
+
233
+ throw error;
234
+ }
235
+ }
236
+
237
+ private getCollectionHandler(collection: string): any
238
+ {
239
+ if(!this.client || !this.connected){
240
+ this.connectToDB();
241
+ }
242
+
243
+ return (this.client[collection as keyof PrismaClient] as any);
244
+ }
245
+
246
+ private setOpts(opts: IDBClientCreate = null): this
247
+ {
248
+ this.opts = opts;
249
+ return this;
250
+ }
251
+ }
252
+
253
+ export { DBService, IDBClientCreate };
@@ -0,0 +1,11 @@
1
+ import { OpModelType } from "../models/_model";
2
+
3
+ export interface IDbConfigParams {
4
+ mongo_url?: string;
5
+ mongo_db?: string;
6
+ db_models?: OpModelType<any>[]
7
+ }
8
+
9
+ export interface IDbConfigHandler {
10
+ get<K extends keyof IDbConfigParams>(key: K): IDbConfigParams[K];
11
+ }
@@ -0,0 +1,7 @@
1
+ export type FindByType = {
2
+ conditions?: any,
3
+ ordering?: { [fieldName: string]: string },
4
+ fields?: string[],
5
+ allowRelations?: boolean,
6
+ fullData?: boolean
7
+ }
@@ -0,0 +1,3 @@
1
+ export interface IRWSModel {
2
+ id?: string
3
+ }
@@ -0,0 +1,6 @@
1
+ export interface ITimeSeries {
2
+ value: number,
3
+ timestamp?: Date;
4
+ params?: any;
5
+ time_tracker_id?: string
6
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "compilerOptions": {
3
+ "baseUrl": "./",
4
+ "experimentalDecorators": true,
5
+ "emitDecoratorMetadata": true,
6
+ "target": "ES2018",
7
+ "module": "commonjs",
8
+ "moduleResolution": "node",
9
+ "strict": true,
10
+ "skipLibCheck": true,
11
+ "esModuleInterop": true,
12
+ "resolveJsonModule": true,
13
+ "strictNullChecks": false,
14
+ "allowSyntheticDefaultImports": true,
15
+ "sourceMap": true,
16
+ "declaration": true,
17
+ },
18
+ "include": [
19
+ "src"
20
+ ],
21
+ "exclude": [
22
+ "node_modules"
23
+ ]
24
+ }