-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4b04f95
commit 3041f11
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import type { StorageAdapter } from 'grammy' | ||
import type { Collection } from 'mongodb' | ||
|
||
export interface ISession { | ||
_id: { $oid: string } | ||
key: string | ||
value: unknown | ||
} | ||
|
||
export class MongoDBAdapter<T> implements StorageAdapter<T> { | ||
private collection: Collection<ISession> | ||
|
||
constructor({ collection }: { collection: Collection<ISession> }) { | ||
this.collection = collection | ||
} | ||
|
||
async read(key: string) { | ||
const session = await this.collection.findOne({ key }) | ||
|
||
if (session === null || session === undefined) { | ||
return undefined | ||
} | ||
|
||
return session.value as T | ||
} | ||
|
||
async write(key: string, data: T) { | ||
await this.collection.updateOne( | ||
{ | ||
key | ||
}, | ||
{ | ||
$set: { | ||
key, | ||
value: data | ||
} | ||
}, | ||
{ upsert: true, ignoreUndefined: true } | ||
) | ||
} | ||
|
||
async delete(key: string) { | ||
await this.collection.deleteOne({ key }) | ||
} | ||
} |