@grammyjs/storage-prisma
v2.5.1
Published
Prisma storage for grammY
Downloads
2,175
Readme
Prisma storage adapter for grammY
Storage adapter that can be used to store your session data with Prisma when using sessions.
Installation
npm install @grammyjs/storage-prisma --saveUsage
You can check the examples folder, or simply use followed code:
Implement the Session model in your Prisma schema:
model Session {
id Int @id @default(autoincrement())
key String @unique
value String
}The
idfield is not needed for this adapter to work.The only restriction is that
keymust be aStringindex, either by adding the@uniquekeyword or the@idkeyword, andvaluemust be aString.
Generate Prisma client using the terminal:
npx prisma generateMigrate the schema changes to your database:
npx prisma db push
# or
npx prisma migrate devCreate bot and pass adapter as storage:
import { Bot, Context, session, SessionFlavor } from "grammy";
import { PrismaAdapter } from "@grammyjs/storage-prisma";
import { PrismaClient } from "@prisma/client";
// Create Prisma client
const prisma = new PrismaClient();
// write session types
interface SessionData {
counter: number;
}
// create context for grammy instance
type MyContext = Context & SessionFlavor<SessionData>;
// Create bot and register session middleware
async function bootstrap() {
const bot = new Bot<MyContext>("");
bot.use(
session({
initial: () => ({ counter: 0 }),
storage: new PrismaAdapter(prisma.session),
})
);
// Register your usual middleware, and start the bot
bot.command("stats", (ctx) =>
ctx.reply(`Already got ${ctx.session.counter} photos!`)
);
bot.on(":photo", (ctx) => ctx.session.counter++);
bot.start();
}