aboutsummaryrefslogtreecommitdiff
path: root/src/server/database.ts
diff options
context:
space:
mode:
authorbobzel <zzzman@gmail.com>2024-05-14 23:15:24 -0400
committerbobzel <zzzman@gmail.com>2024-05-14 23:15:24 -0400
commit3534aaf88a3c30a474b3b5a5b7f04adfe6f15fac (patch)
tree47fb7a8671b209bd4d76e0f755a5b035c6936607 /src/server/database.ts
parent87bca251d87b5a95da06b2212400ce9427152193 (diff)
parent5cb7ad90e120123ca572e8ef5b1aa6ca41581134 (diff)
Merge branch 'restoringEslint' into sarah-ai-visualization
Diffstat (limited to 'src/server/database.ts')
-rw-r--r--src/server/database.ts166
1 files changed, 84 insertions, 82 deletions
diff --git a/src/server/database.ts b/src/server/database.ts
index 3a087ce38..ff8584cd7 100644
--- a/src/server/database.ts
+++ b/src/server/database.ts
@@ -30,7 +30,10 @@ export namespace Database {
export async function tryInitializeConnection() {
try {
const { connection } = mongoose;
- disconnect = async () => new Promise<any>(resolve => connection.close().then(resolve));
+ disconnect = async () =>
+ new Promise<any>(resolve => {
+ connection.close().then(resolve);
+ });
if (connection.readyState === ConnectionStates.disconnected) {
await new Promise<void>((resolve, reject) => {
connection.on('error', reject);
@@ -39,7 +42,7 @@ export namespace Database {
resolve();
});
mongoose.connect(url, {
- //useNewUrlParser: true,
+ // useNewUrlParser: true,
dbName: schema,
// reconnectTries: Number.MAX_VALUE,
// reconnectInterval: 1000,
@@ -54,6 +57,7 @@ export namespace Database {
}
}
+ // eslint-disable-next-line @typescript-eslint/no-shadow
export class Database implements IDatabase {
private MongoClient = mongodb.MongoClient;
private currentWrites: { [id: string]: Promise<void> } = {};
@@ -81,8 +85,8 @@ export namespace Database {
const collection = this.db.collection<DocSchema>(collectionName);
const prom = this.currentWrites[id];
let newProm: Promise<void>;
- const run = (): Promise<void> => {
- return new Promise<void>(resolve => {
+ const run = (): Promise<void> =>
+ new Promise<void>(resolve => {
collection
.updateOne({ _id: id }, value, { upsert })
.then(res => {
@@ -96,13 +100,12 @@ export namespace Database {
console.log('MOngo UPDATE ONE ERROR:', error);
});
});
- };
newProm = prom ? prom.then(run) : run();
this.currentWrites[id] = newProm;
return newProm;
- } else {
- this.onConnect.push(() => this.update(id, value, callback, upsert, collectionName));
}
+ this.onConnect.push(() => this.update(id, value, callback, upsert, collectionName));
+ return undefined;
}
public replace(id: string, value: any, callback: (err: mongodb.MongoError, res: mongodb.UpdateResult<mongodb.Document>) => void, upsert = true, collectionName = DocumentsCollection) {
@@ -110,8 +113,8 @@ export namespace Database {
const collection = this.db.collection<DocSchema>(collectionName);
const prom = this.currentWrites[id];
let newProm: Promise<void>;
- const run = (): Promise<void> => {
- return new Promise<void>(resolve => {
+ const run = (): Promise<void> =>
+ new Promise<void>(resolve => {
collection.replaceOne({ _id: id }, value, { upsert }).then(res => {
if (this.currentWrites[id] === newProm) {
delete this.currentWrites[id];
@@ -120,7 +123,6 @@ export namespace Database {
callback(undefined as any, res as any);
});
});
- };
newProm = prom ? prom.then(run) : run();
this.currentWrites[id] = newProm;
} else {
@@ -132,8 +134,10 @@ export namespace Database {
const cursor = this.db?.listCollections();
const collectionNames: string[] = [];
if (cursor) {
+ // eslint-disable-next-line no-await-in-loop
while (await cursor.hasNext()) {
- const collection: any = await cursor.next();
+ // eslint-disable-next-line no-await-in-loop
+ const collection = await cursor.next();
collection && collectionNames.push(collection.name);
}
}
@@ -141,26 +145,30 @@ export namespace Database {
}
public delete(query: any, collectionName?: string): Promise<mongodb.DeleteResult>;
+ // eslint-disable-next-line no-dupe-class-members
public delete(id: string, collectionName?: string): Promise<mongodb.DeleteResult>;
- public delete(id: any, collectionName = DocumentsCollection) {
+ // eslint-disable-next-line no-dupe-class-members
+ public delete(idIn: any, collectionName = DocumentsCollection) {
+ let id = idIn;
if (typeof id === 'string') {
id = { _id: id };
}
if (this.db) {
- const db = this.db;
- return new Promise(res =>
- db
- .collection(collectionName)
+ const { db } = this;
+ return new Promise(res => {
+ db.collection(collectionName)
.deleteMany(id)
- .then(result => res(result))
- );
- } else {
- return new Promise(res => this.onConnect.push(() => res(this.delete(id, collectionName))));
+ .then(result => res(result));
+ });
}
+ return new Promise(res => {
+ this.onConnect.push(() => res(this.delete(id, collectionName)));
+ });
}
public async dropSchema(...targetSchemas: string[]): Promise<any> {
const executor = async (database: mongodb.Db) => {
+ // eslint-disable-next-line no-use-before-define
const existing = await Instance.getCollectionNames();
let valid: string[];
if (targetSchemas.length) {
@@ -173,12 +181,13 @@ export namespace Database {
};
if (this.db) {
return executor(this.db);
- } else {
- this.onConnect.push(() => this.db && executor(this.db));
}
+ this.onConnect.push(() => this.db && executor(this.db));
+ return undefined;
}
- public async insert(value: any, collectionName = DocumentsCollection) {
+ public async insert(valueIn: any, collectionName = DocumentsCollection) {
+ const value = valueIn;
if (this.db && value !== null) {
if ('id' in value) {
value._id = value.id;
@@ -188,36 +197,36 @@ export namespace Database {
const collection = this.db.collection<DocSchema>(collectionName);
const prom = this.currentWrites[id];
let newProm: Promise<void>;
- const run = (): Promise<void> => {
- return new Promise<void>(resolve => {
+ const run = (): Promise<void> =>
+ new Promise<void>(resolve => {
collection
.insertOne(value)
- .then(res => {
+ .then(() => {
if (this.currentWrites[id] === newProm) {
delete this.currentWrites[id];
}
resolve();
})
- .catch(err => {
- console.log('Mongo INSERT ERROR: ', err);
- });
+ .catch(err => console.log('Mongo INSERT ERROR: ', err));
});
- };
newProm = prom ? prom.then(run) : run();
this.currentWrites[id] = newProm;
return newProm;
- } else if (value !== null) {
+ }
+ if (value !== null) {
this.onConnect.push(() => this.insert(value, collectionName));
}
+ return undefined;
}
public getDocument(id: string, fn: (result?: Transferable) => void, collectionName = DocumentsCollection) {
if (this.db) {
const collection = this.db.collection<DocSchema>(collectionName);
- collection.findOne({ _id: id }).then(result => {
+ collection.findOne({ _id: id }).then(resultIn => {
+ const result = resultIn;
if (result) {
result.id = result._id;
- //delete result._id;
+ // delete result._id;
fn(result as any);
} else {
fn(undefined);
@@ -235,7 +244,8 @@ export namespace Database {
.find({ _id: { $in: ids } })
.toArray();
fn(
- found.map((doc: any) => {
+ found.map((docIn: any) => {
+ const doc = docIn;
doc.id = doc._id;
delete doc._id;
return doc;
@@ -253,24 +263,26 @@ export namespace Database {
const count = Math.min(ids.length, 1000);
const index = ids.length - count;
const fetchIds = ids.splice(index, count).filter(id => !visited.has(id));
- if (!fetchIds.length) {
- continue;
- }
- const docs = await new Promise<{ [key: string]: any }[]>(res => this.getDocuments(fetchIds, res, collectionName));
- for (const doc of docs) {
- const id = doc.id;
- visited.add(id);
- ids.push(...(await fn(doc)));
+ if (fetchIds.length) {
+ // eslint-disable-next-line no-await-in-loop
+ const docs = await new Promise<{ [key: string]: any }[]>(res => {
+ this.getDocuments(fetchIds, res, collectionName);
+ });
+ docs.forEach(async doc => {
+ const { id } = doc;
+ visited.add(id);
+ ids.push(...(await fn(doc)));
+ });
}
}
- } else {
- return new Promise(res => {
- this.onConnect.push(() => {
- this.visit(ids, fn, collectionName);
- res();
- });
- });
+ return undefined;
}
+ return new Promise(res => {
+ this.onConnect.push(() => {
+ this.visit(ids, fn, collectionName);
+ res();
+ });
+ });
}
public query(query: { [key: string]: any }, projection?: { [key: string]: 0 | 1 }, collectionName = DocumentsCollection): Promise<mongodb.FindCursor> {
@@ -280,36 +292,31 @@ export namespace Database {
cursor = cursor.project(projection);
}
return Promise.resolve<mongodb.FindCursor>(cursor);
- } else {
- return new Promise<mongodb.FindCursor>(res => {
- this.onConnect.push(() => res(this.query(query, projection, collectionName)));
- });
}
+ return new Promise<mongodb.FindCursor>(res => {
+ this.onConnect.push(() => {
+ res(this.query(query, projection, collectionName));
+ });
+ });
}
public updateMany(query: any, update: any, collectionName = DocumentsCollection) {
if (this.db) {
- const db = this.db;
- return new Promise<mongodb.UpdateResult>(res =>
- db
- .collection(collectionName)
+ const { db } = this;
+ return new Promise<mongodb.UpdateResult>(res => {
+ db.collection(collectionName)
.updateMany(query, update)
.then(result => res(result))
- .catch(error => {
- console.log('Mongo INSERT MANY ERROR:', error);
- })
- );
- } else {
- return new Promise<mongodb.UpdateResult>(res => {
- this.onConnect.push(() =>
- this.updateMany(query, update, collectionName)
- .then(res)
- .catch(error => {
- console.log('Mongo UPDATAE MANY ERROR: ', error);
- })
- );
+ .catch(error => console.log('Mongo INSERT MANY ERROR:', error));
});
}
+ return new Promise<mongodb.UpdateResult>(res => {
+ this.onConnect.push(() =>
+ this.updateMany(query, update, collectionName)
+ .then(res)
+ .catch(error => console.log('Mongo UPDATAE MANY ERROR: ', error))
+ );
+ });
}
public print() {
@@ -375,9 +382,7 @@ export namespace Database {
* Checks to see if an image with the given @param contentSize
* already exists in the aux database, i.e. has already been downloaded from Google Photos.
*/
- export const QueryUploadHistory = async (contentSize: number) => {
- return SanitizedSingletonQuery<Upload.ImageInformation>({ contentSize }, AuxiliaryCollections.GooglePhotosUploadHistory);
- };
+ export const QueryUploadHistory = async (contentSize: number) => SanitizedSingletonQuery<Upload.ImageInformation>({ contentSize }, AuxiliaryCollections.GooglePhotosUploadHistory);
/**
* Records the uploading of the image with the given @param information,
@@ -405,28 +410,25 @@ export namespace Database {
* Retrieves the credentials associaed with @param userId
* and optionally removes their database id according to @param removeId.
*/
- export const Fetch = async (userId: string, removeId = true): Promise<Opt<StoredCredentials>> => {
- return SanitizedSingletonQuery<StoredCredentials>({ userId }, AuxiliaryCollections.GoogleAccess, removeId);
- };
+ export const Fetch = async (userId: string, removeId = true): Promise<Opt<StoredCredentials>> => SanitizedSingletonQuery<StoredCredentials>({ userId }, AuxiliaryCollections.GoogleAccess, removeId);
/**
* Writes the @param enrichedCredentials to the database, associated
* with @param userId for later retrieval and updating.
*/
- export const Write = async (userId: string, enrichedCredentials: GoogleApiServerUtils.EnrichedCredentials) => {
- return Instance.insert({ userId, canAccess: [], ...enrichedCredentials }, AuxiliaryCollections.GoogleAccess);
- };
+ export const Write = async (userId: string, enrichedCredentials: GoogleApiServerUtils.EnrichedCredentials) => Instance.insert({ userId, canAccess: [], ...enrichedCredentials }, AuxiliaryCollections.GoogleAccess);
/**
- * Updates the @param access_token and @param expiry_date fields
+ * Updates the @param accessToken and @param expiryDate fields
* in the stored credentials associated with @param userId.
*/
- export const Update = async (userId: string, access_token: string, expiry_date: number) => {
+ export const Update = async (userId: string, accessToken: string, expiryDate: number) => {
const entry = await Fetch(userId, false);
if (entry) {
- const parameters = { $set: { access_token, expiry_date } };
+ const parameters = { $set: { access_token: accessToken, expiry_date: expiryDate } };
return Instance.update(entry._id, parameters, emptyFunction, true, AuxiliaryCollections.GoogleAccess);
}
+ return undefined;
};
/**