Newer
Older
import { Client } from 'cozy-client'
import { KONNECTORS_DOCTYPE, Konnector } from 'doctypes'
export default class KonnectorService {
private _konnector: Konnector | null
constructor(private _client: Client, private _konnectorId: string) {
this._konnector = null
this._client = _client
this._konnectorId = _konnectorId
}
get konnector(): Konnector | null {
return this._konnector
}
fetchKonnector = async () => {
if (!(this._client && this._konnectorId)) {
throw new Error(
'KonnectorService : fetchKonnector - client or konnector id not found'
)
}
try {
const { data } = await this._client.query(
this._client.find(KONNECTORS_DOCTYPE).where({
_id: KONNECTORS_DOCTYPE + '/' + this._konnectorId,
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
})
)
const konnector: Konnector = data && data[0]
this._konnector = konnector
return konnector
} catch (error) {
throw error
}
}
async getKonnectorLastTrigger(slug: string) {
const query = this._client
.find('io.cozy.triggers')
.where({ 'message.konnector': slug })
.sortBy([{ 'cozyMetadata.updatedAt': 'desc' }])
.limitBy(1)
return await this._client.query(query)
}
async getKonnectorLastJob(slug: string) {
const query = this._client
.find('io.cozy.jobs')
.where({ 'message.konnector': slug })
// eslint-disable-next-line @typescript-eslint/camelcase
.sortBy([{ finished_at: 'desc' }])
.limitBy(1)
return await this._client.query(query)
}
async getKonnectorLastStatus(): Promise<string | null> {
if (!(this._client && this._konnectorId)) {
throw new Error(
'KonnectorService : findKonnector - client or konnector id not found'
)
}
try {
if (!this._konnector) {
await this.fetchKonnector()
}
if (this._konnector) {
const trigger = await this.getKonnectorLastTrigger(this._konnector.slug)
if (trigger && trigger.current_state && trigger.current_state) {
return trigger.current_state.status
}
}
return null
} catch (error) {
throw error
}
}
async isTriggerSetForKonnector(): Promise<boolean> {
if (!(this._client && this._konnectorId)) {
throw new Error(
'KonnectorService : findKonnector - client or konnector id not found'
)
}
try {
if (!this._konnector) {
await this.fetchKonnector()
}
if (this._konnector) {
const trigger = await this.getKonnectorLastTrigger(this._konnector.slug)
if (trigger) {
return true
}
} else {
return false
}
return false
} catch (error) {
throw error
}
}
static createIndexKonnector = async (client: Client) => {
const query = client
.find('io.cozy.konnectors')
// eslint-disable-next-line @typescript-eslint/camelcase
.where({ _id: 'index' })
.limitBy(1)
return await client.query(query)
}