tachybase_todo/packages/plugins/notifications/src/models/Notification.ts

86 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-12-07 19:24:26 +08:00
import Database, { Model } from '@nocobase/database';
import { NotificationService } from './NotificationService';
import _ from 'lodash';
export class Notification extends Model {
[key: string]: any;
get db(): Database {
return this.constructor['database'];
}
async getReceiversByOptions(): Promise<any[]> {
const { data, fromTable, filter, dataField } = this.receiver_options;
let receivers = [];
if (data) {
receivers = Array.isArray(data) ? data : [data];
} else if (fromTable) {
const collection = this.db.getCollection(fromTable);
const rows = await collection.repository.find({
filter,
});
receivers = rows.map((row) => row[dataField]);
2021-12-07 19:24:26 +08:00
}
return receivers;
}
async send(options: any = {}) {
const { transaction } = options;
2021-12-07 19:24:26 +08:00
if (!this.service) {
this.service = await this.getService();
}
const receivers = await this.getReceiversByOptions();
let { to } = options;
if (to) {
to = Array.isArray(to) ? to : [to];
receivers.push(...to);
}
console.log(receivers);
2021-12-07 19:24:26 +08:00
for (const receiver of receivers) {
try {
const response = await (this.service as NotificationService).send({
to: receiver,
subject: this.getSubject(),
html: this.getBody(options),
});
await this.createLog(
{
receiver,
state: 'success',
response,
},
{
transaction,
},
);
2021-12-07 19:24:26 +08:00
await new Promise((resolve) => {
setTimeout(resolve, 100);
});
} catch (error) {
console.error(error);
await this.createLog(
{
receiver,
state: 'fail',
response: {},
},
{
transaction,
},
);
2021-12-07 19:24:26 +08:00
}
}
}
getSubject() {
return this.subject;
}
getBody(data) {
const compiled = _.template(this.body);
2021-12-07 19:24:26 +08:00
const body = compiled(data);
return body;
}
}