2.4.2 • Published 2 months ago

@grammyjs/storage-typeorm v2.4.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 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.4.2

2 months ago

2.4.1

5 months ago

2.3.2

8 months ago

2.4.0

7 months ago

2.3.1

8 months ago

2.3.0

11 months ago

2.2.0

1 year ago

2.1.4

1 year ago

2.1.3

1 year ago

2.1.1

1 year ago

2.1.0

1 year ago

2.0.2

1 year ago

2.0.0

2 years ago