airgram-use-models
v1.1.0
Published
This small utility converts plain JSON objects to class instances.
Downloads
16
Readme
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.