Advertisement
MaxSMoke

Test code

Jul 14th, 2023 (edited)
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 1.74 KB | Source Code | 0 0
  1. import { Collection, Filter, FindCursor, MongoClient, OptionalId, WithId } from 'mongodb';
  2. const uri = 'mongodb://127.1:27017/';
  3. const client = new MongoClient(uri);
  4. client.connect();
  5. const db = client.db('SMokeBot');
  6.  
  7. export class DB {
  8.  
  9.   collection: Collection<Document>
  10.   constructor(collName: string) {
  11.     this.collection = db.collection(collName);
  12.   }
  13.  
  14.   async addOne(obj: OptionalId<Document>): Promise<void> {
  15.     await this.collection.insertOne(obj);
  16.   };
  17.  
  18.   async deleteOne(findParams: Filter<Document>): Promise<void> {
  19.     const find: WithId<Document> = (await this.collection.findOne(findParams))!;
  20.     await this.collection.deleteOne(find);
  21.   };
  22.  
  23.   async editOne(findParam: Filter<Document>, pValue: any, pName: string): Promise<void>  {
  24.     const user: WithId<Document> | null = await this.collection.findOne(findParam);
  25.     const param = {};
  26.     param[pName] = pValue;
  27.     await this.collection.updateOne({ _id: user!._id }, { $set: param });
  28.   };
  29.  
  30.   async find(findParams: Filter<Document>): Promise<WithId<Document>> {
  31.     return new Promise(async(resolve: (value: WithId<Document> | PromiseLike<WithId<Document>>) => void , reject: (reason?: any) => void): Promise<void> => {
  32.       const find: WithId<Document> | null = await this.collection.findOne(findParams);
  33.       resolve(JSON.parse(String(find)));
  34.     });
  35.   };
  36.  
  37.   async getAll(): Promise<WithId<Document>>  {
  38.     return new Promise(async (resolve: (value: WithId<Document> | PromiseLike<WithId<Document>>) => void, reject: (reason?: any) => void): Promise<void> => {
  39.       const cursor: FindCursor<WithId<Document>> = await this.collection.find();
  40.       const find: WithId<Document>[] = await cursor.toArray();
  41.       resolve(JSON.parse(String(find)));
  42.     });
  43.   };
  44. }
  45.  
Tags: typescript
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement