Skip to content

Commit

Permalink
fix: use custom storage adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
roziscoding committed Oct 21, 2022
1 parent 4b04f95 commit 3041f11
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import { FileAdapter } from '@grammyjs/storage-file'
import { ISession, MongoDBAdapter } from '@grammyjs/storage-mongodb'
import { Bot, Context, session, SessionFlavor } from 'grammy'
import { MongoClient } from 'mongodb'

import * as commands from './commands'
import { AppConfig } from './config'
import * as conversations from './conversations'
import * as handlers from './handlers'
import { ISession, MongoDBAdapter } from './util/storage-adapter'

export type AppSession = {
pixKey: string
Expand Down
45 changes: 45 additions & 0 deletions src/util/storage-adapter.ts
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 })
}
}

0 comments on commit 3041f11

Please sign in to comment.