Skip to content

Commit

Permalink
refactor: create functions for handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
tfkhdyt committed Sep 27, 2023
1 parent 06162f6 commit 01e0860
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/db/postgres/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createClient } from '@libsql/client'
import { drizzle } from 'drizzle-orm/libsql'
import { migrate } from 'drizzle-orm/libsql/migrator'

import config from '../../config/config'

Expand All @@ -9,3 +10,9 @@ const client = createClient({
})
export const db = drizzle(client)
export type DB = typeof db

export async function startMigration() {
console.log('Running migration...')
await migrate(db, { migrationsFolder: 'drizzle' })
console.log('Migrations is done')
}
12 changes: 12 additions & 0 deletions src/handlers/saldoHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { MyContext } from '../interfaces/context'

export const saldoHandler = async (ctx: MyContext) => {
try {
const user = ctx.user

ctx.reply(`Jumlah saldo mu adalah: ${user.credits}`)
} catch (error) {
console.error(error)
ctx.reply(`Terjadi error yang tak terduga!, ${error}`)
}
}
23 changes: 23 additions & 0 deletions src/handlers/textHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { NarrowedContext } from 'telegraf'
import { Message, Update } from 'telegraf/typings/core/types/typegram'
import { MyContext } from '../interfaces/context'

export const textHandler = async (
ctx: NarrowedContext<
MyContext,
Update.MessageUpdate<Record<'text', unknown> & Message.TextMessage>
>,
) => {
try {
if (ctx.user.credits === 0) {
return ctx.reply(
'Maaf, saldo anda tidak cukup, silakan isi ulang atau tunggu besok hari',
)
}

const keyword = ctx.message.text
await app.main(ctx, keyword)
} catch (error) {
console.error(error)
}
}
26 changes: 26 additions & 0 deletions src/middlewares/user.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { MyContext } from '../interfaces/context'
import { addUser, findUserByID } from '../user.repository'

export const checkUserMiddleware = async (
ctx: MyContext,
next: () => Promise<void>,
) => {
try {
const userId = ctx.from?.id
const username = ctx.from?.username
if (!userId || !username)
throw new Error('User ID atau Username anda tidak valid')

const user = await findUserByID(userId)
if (user.length === 0) {
await addUser({ id: userId, username })
}

ctx.user = user[0]

await next()
} catch (error) {
console.error(error)
ctx.reply(`Terjadi error yang tak terduga!, ${error}`)
}
}

0 comments on commit 01e0860

Please sign in to comment.