2.5.1 • Published 10 months ago

@grammyjs/storage-typeorm v2.5.1

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

TypeORM storage adapter for grammY

Storage adapter that can be used to store your session data with TypeORM when using sessions.

Installation

npm install @grammyjs/storage-typeorm typeorm --save

Usage

You can check examples folder, or simple use followed code:

Implement the Session entity:

import { Column, createConnection, Entity, PrimaryGeneratedColumn } from 'typeorm';
import { ISession } from "@grammyjs/storage-typeorm";

@Entity()
export class Session implements ISession {
  @PrimaryGeneratedColumn()
  id: string;

  @Column('varchar')
  key: string

  @Column('text')
  value: string
}

Create bot and pass adapter as storage:

import { Bot, Context, session, SessionFlavor } from "grammy";
import { TypeormAdapter } from "@grammyjs/storage-typeorm";
import { createConnection } from 'typeorm';

// that import for example class before
import Session from './session'

// 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() {
  // create typeorm connection
  await createConnection({
    name: 'default',
    type: 'better-sqlite3',
    database: ':memory:',
    entities: [Session],
    synchronize: true,
  });

  const bot = new Bot<MyContext>("");
  bot.use(
    session({
      initial: () => ({ counter: 0 }),
      storage: new TypeormAdapter({ repository: getRepository(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();

}
2.5.1

10 months ago

2.4.2

2 years ago

2.4.1

2 years ago

2.3.2

2 years ago

2.4.0

2 years ago

2.3.1

2 years ago

2.3.0

3 years ago

2.2.0

3 years ago

2.1.4

3 years ago

2.1.3

3 years ago

2.1.1

3 years ago

2.1.0

3 years ago

2.0.2

3 years ago

2.0.0

4 years ago