-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcron.service.ts
194 lines (182 loc) · 6.7 KB
/
cron.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { HttpService } from '@nestjs/axios';
import { forwardRef, HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { SchedulerRegistry } from '@nestjs/schedule';
import { AxiosError } from 'axios';
import { catchError, firstValueFrom } from 'rxjs';
import { ActionService } from 'src/action/action.service';
import { CredentialsService } from 'src/credentials/credentials.service';
import { MyActionService } from 'src/myAction/myAction.service';
import { UserService } from 'src/user/user.service';
import { ServiceList, ServiceType } from '../service/entity/service.entity';
import { CreateCronDto } from './dto/add-cron.dto';
import { CronJob } from 'cron';
import { Params } from './type/param.type';
import { ServiceService } from 'src/service/service.service';
import { ActionResult } from './interfaces/actionResult.interface';
import { ActionParam } from './interfaces/actionParam.interface';
import { ReturnValues } from './type/returnValue.type';
import { ActionRecord } from './entity/actionRecord.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { NotFoundException } from 'src/utils/exceptions/not-found.exception';
@Injectable()
export class CronService {
constructor(
private readonly credentialsService: CredentialsService,
private readonly actionService: ActionService,
@Inject(forwardRef(() => MyActionService))
private readonly myActionService: MyActionService,
private readonly httpService: HttpService,
private readonly userService: UserService,
private schedulerRegistry: SchedulerRegistry,
private readonly serviceService: ServiceService,
@InjectRepository(ActionRecord)
private readonly actionRecordRepository: Repository<ActionRecord>,
) {}
public async findByActionId(myActionId: string, category: string): Promise<ActionRecord> {
try {
return await this.actionRecordRepository.findOneBy({
myActionId: myActionId,
category: category,
});
} catch (error) {
return undefined;
}
}
public async findOrUpdateLastRecord(actionRecord: ActionRecord): Promise<boolean> {
const record = await this.findByActionId(actionRecord.myActionId, actionRecord.category);
if (!record) {
try {
await this.actionRecordRepository.save(actionRecord);
return false;
} catch (err) {
throw new HttpException(() => err.message, HttpStatus.BAD_REQUEST, { cause: err });
}
}
if (record.content !== actionRecord.content) {
try {
const newRecord = await this.actionRecordRepository.update(
{
myActionId: actionRecord.myActionId,
category: record.category,
content: record.content,
},
{ ...actionRecord },
);
if (!newRecord) {
throw NotFoundException(`Record does not exist`);
}
return true;
} catch (err) {
throw new HttpException(() => err.message, HttpStatus.BAD_REQUEST, { cause: err });
}
}
return false;
}
public createRecord(myActionId: string, category: string, content: string): ActionRecord {
const record = new ActionRecord();
record.myActionId = myActionId;
record.category = category;
record.content = content;
return record;
}
public async removeRecord(myActionId: string): Promise<void> {
await this.actionRecordRepository.delete({ myActionId: myActionId }).catch(() => {
throw NotFoundException('area');
});
}
async handleCronAddition(
userId: string,
myActionId: string,
actionLink: string,
service: ServiceList,
actionHandling: (actionParam: ActionParam) => ActionResult,
params: Params,
) {
if (!actionHandling) {
return;
}
this.userService.existByUserId(userId).then((exist) => {
if (!exist) {
return;
}
});
try {
let credential = '';
if (await this.serviceService.isType(service, ServiceType.EXTERNAL)) {
credential = (await this.credentialsService.findById(userId, service)).accessToken;
}
const argToSend = params
? [{ name: 'userId', content: userId, isActionResult: false }, ...params]
: [{ name: 'userId', content: userId, isActionResult: false }];
const conditionChecked = await actionHandling({
accessToken: credential,
params: argToSend,
myActionId: myActionId,
});
if (conditionChecked.isTriggered) {
console.log('action is triggered');
await this.handleCronReaction(userId, actionLink, conditionChecked.returnValues);
}
} catch (error: any) {
return;
}
}
addCron(
body: CreateCronDto,
availableActions: Map<string, (actionParam: ActionParam) => Promise<ActionResult>>,
) {
if (!availableActions.has(body.link)) {
console.log('No such function');
return;
}
const job = new CronJob(
body.second + ` ` + body.minute + ` ` + body.hour + ` * * *`,
this.handleCronAddition.bind(
this,
body.userId,
body.myActionId,
body.link,
body.service,
availableActions.get(body.link),
body.params,
),
);
console.log('cron has been added');
this.schedulerRegistry.addCronJob(body.name, job);
job.start();
}
async handleCronReaction(userId: string, actionLink: string, returnValues: ReturnValues) {
const action = await this.actionService.findByLink(actionLink);
const relatedActions = await this.myActionService.findByActionAndUserId(action.uuid, userId);
for (const relatedAction of relatedActions) {
const linkedReaction = await this.myActionService.findByLinkedFromId(relatedAction.uuid);
for (const linked of linkedReaction) {
const reaction = await this.actionService.findOne(linked.actionId);
let newAccessToken = 'undefined';
if (await this.serviceService.isType(reaction.service, ServiceType.EXTERNAL)) {
newAccessToken = (await this.credentialsService.findById(userId, reaction.service))
.accessToken;
}
console.log('calling reaction:', reaction.link);
await firstValueFrom(
this.httpService
.post<any>(
`http://${process.env.APP_HOST}:${process.env.API_PORT}${process.env.APP_ENDPOINT}/actions/` +
reaction.link,
{
accessToken: newAccessToken,
params: linked.params,
returnValues: returnValues,
},
)
.pipe(
catchError((error: AxiosError) => {
throw new HttpException(error.message, HttpStatus.BAD_REQUEST, { cause: error });
}),
),
);
}
}
}
}