airgram-use-models
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

Using models in Airgram

This small utility converts plain JSON objects to class instances.

Usage

For example, lets add some features to the Chat:

import { Airgram } from 'airgram'
import { ApiMethods, CHAT_TYPE, UPDATE } from 'airgram-api'
import { ChatBaseModel, useModels } from 'airgram-use-models'

class ChatModel extends ChatBaseModel {
  get isBasicGroup (): boolean {
    return this.type._ === CHAT_TYPE.chatTypeBasicGroup
  }

  get isSupergroup (): boolean {
    return this.type._ === CHAT_TYPE.chatTypeSupergroup
  }

  get isPrivateChat (): boolean {
    return this.type._ === CHAT_TYPE.chatTypePrivate
  }

  get isSecretChat (): boolean {
    return this.type._ === CHAT_TYPE.chatTypeSecret
  }

  public async isMe (api: ApiMethods): Promise<boolean> {
    if ('userId' in this.type) {
      return (await api.getMe()).id === this.type.userId
    }
    return false
  }
}

// This is important for correct typings
declare module 'airgram-api/outputs/Chat' {
  export interface Chat extends ChatModel {}
}

const airgram = new Airgram({
  models: useModels({
    chat: ChatModel
  })
})

airgram.updates.on(UPDATE.updateNewChat, async ({ update }) => {
  const { chat } = update
  console.info('isBasicGroup: ', chat.isBasicGroup)
  console.info('isSupergroup: ', chat.isSupergroup)
  console.info('isPrivateChat: ', chat.isPrivateChat)
  console.info('isSecretChat: ', chat.isSecretChat)
  console.info('isMe: ', await chat.isMe(airgram.api))
})

License

The source code is licensed under GPL v3. License is available here.

Readme

Keywords

Package Sidebar

Install

npm i airgram-use-models

Homepage

airgram.io

Weekly Downloads

1

Version

1.1.0

License

GPL-3.0

Unpacked Size

925 kB

Total Files

2409

Last publish

Collaborators

  • esindger