link
Updates
Getting updates is one of the most important parts of a Telegram application. Updates contain notifications about data changes. You can use middleware to get them, as in the example below:
// ctx is UpdateContext | ApiResponse
airgram.use((ctx, next) => {
// Checks if this operation is UpdateContext
if ('update' in ctx) {
console.log(`[all updates][${ctx._}]`, JSON.stringify(ctx.update))
}
return next()
})
In common case, middleware's context can be represented by UpdateContext
type or ApiResponse
type, so you need to check that this is an update.
Updates context implements the following interface:
interface UpdateContext {
_: string
update: Record<string, any>
airgram: Airgram
setState: Function
getState: Function
}
If you need to subscribe to certain updates, we recommend using the on
method because it gives you full type checking support.
The first argument specifies the type of updates you want to receive. The second one sets a callback function, which will be called each time for corresponding update type.
interface UpdateContext {
_: 'updateNewMessage' // recognized
update: UpdateNewMessage // recognized
airgram: Airgram
setState: Function
getState: Function
}
airgram.on('updateNewMessage', async ({ update }) => {
// `update` resolved as `UpdateNewMessage`
const { message } = update
console.log('[new message]', message)
})
link
Emit updates
If you need to fire some update, use emit
method on Airgram instance:
airgram.on('foo', (ctx, next) => {
console.log(ctx.update.bar) // output: baz
return next()
})
airgram.emit({
_: 'foo',
bar: 'baz'
})