Airgram

Guides

Custom context

The operation context is some metadata that is available in middleware and API responses.

By default, context implements ApiResponse or UpdateContext interface.

// Middleware context
airgram.use((ctx: ApiResponse | UpdateContext, next) => {
  // some code
})

// API response context
const me: ApiResponse = await airgram.api.getMe()

You can extend it with additional properties. In the following example we will add a simple store to the context:

import { UPDATE } from '@airgram-dev/constants'
import { Airgram, ChatUnion, UpdateChatLastMessage, UserUnion } from 'airgram'

// Simple chat store
class Store {
  public readonly chats: Map<number, ChatUnion> = new Map()
}

interface ExtraContext {
  $store: Store
}

// Create custom context
const context: ExtraContext = { $store: new Store() }

// Pass context to Airgram
const airgram = new Airgram<ExtraContext>({
  context
})

That's all.

Now you can use the $store property in your middleware as well as in the API responses. Lets look at the example:

airgram.on(UPDATE.updateNewChat, async ({ $store, update }, next) => {
  const { chat } = update
  // Add chats to the store
  $store.chats.set(chat.id, chat)
  return next()
})

airgram.api.getChats({
  limit: 10,
  offsetChatId: 0,
  offsetOrder: '9223372036854775807'
}).then(({ response, $store }) => {
  if (response._ === 'error') {
    throw new Error(`[TDLib][${response.code}] ${response.message}`)
  }
  // `chats` is ChatUnion[]
  const chats = response.chatIds.map((chatId) => $store.chats.get(chatId))
}).catch(console.error)