修复sqlite数据操作类型

This commit is contained in:
whyour
2022-01-08 01:09:38 +08:00
parent 89ed8527d6
commit e75a683173
21 changed files with 199 additions and 217 deletions
+46 -47
View File
@@ -31,25 +31,19 @@ export default class CronService {
}
public async insert(payload: Crontab): Promise<Crontab> {
return await CrontabModel.create(payload);
return await CrontabModel.create(payload, { returning: true });
}
public async update(payload: Crontab): Promise<Crontab> {
const { id, ...other } = payload;
const doc = await this.get(id as number);
const tab = new Crontab({ ...doc, ...other });
tab.saved = false;
const newDoc = await this.updateDb(tab);
payload.saved = false;
const newDoc = await this.updateDb(payload);
await this.set_crontab(this.isSixCron(newDoc));
return newDoc;
}
public async updateDb(payload: Crontab): Promise<Crontab> {
const result = await CrontabModel.update(
{ ...payload },
{ where: { id: payload.id } },
);
return result[1][0];
await CrontabModel.update(payload, { where: { id: payload.id } });
return await this.getDb({ id: payload.id });
}
public async status({
@@ -93,43 +87,56 @@ export default class CronService {
await CrontabModel.update({ isPinned: 0 }, { where: { id: ids } });
}
public async addLabels(ids: string[],labels: string[]){
const docs = await CrontabModel.findAll({ where: { id:ids }});
public async addLabels(ids: string[], labels: string[]) {
const docs = await CrontabModel.findAll({ where: { id: ids } });
for (const doc of docs) {
await CrontabModel.update({
labels: Array.from(new Set(doc.labels.concat(labels)))
},{ where: {id:doc.id}});
await CrontabModel.update(
{
labels: Array.from(new Set((doc.labels || []).concat(labels))),
},
{ where: { id: doc.id } },
);
}
}
public async removeLabels(ids: string[],labels: string[]){
const docs = await CrontabModel.findAll({ where: { id:ids }});
public async removeLabels(ids: string[], labels: string[]) {
const docs = await CrontabModel.findAll({ where: { id: ids } });
for (const doc of docs) {
await CrontabModel.update({
labels: doc.labels.filter( label => !labels.includes(label) )
},{ where: {id:doc.id}});
await CrontabModel.update(
{
labels: (doc.labels || []).filter((label) => !labels.includes(label)),
},
{ where: { id: doc.id } },
);
}
}
public async crontabs(searchText?: string): Promise<Crontab[]> {
let query = {};
if (searchText) {
const textArray = searchText.split(":");
const textArray = searchText.split(':');
switch (textArray[0]) {
case "name":
query = {name:{[Op.or]:createRegexp(textArray[1])}};
break;
case "command":
query = {command:{[Op.or]:createRegexp(textArray[1])}};
break;
case "schedule":
query = {schedule:{[Op.or]:createRegexp(textArray[1])}};
break;
case "label":
query = {labels:{[Op.or]:createRegexp(textArray[1])}};
case 'name':
case 'command':
case 'schedule':
case 'label':
const column = textArray[0] === 'label' ? 'labels' : textArray[0];
query = {
[column]: {
[Op.or]: [
{ [Op.like]: `%${textArray[1]}%` },
{ [Op.like]: `%${encodeURIComponent(textArray[1])}%` },
],
},
};
break;
default:
const reg = createRegexp(searchText);
const reg = {
[Op.or]: [
{ [Op.like]: `%${searchText}%` },
{ [Op.like]: `%${encodeURIComponent(searchText)}%` },
],
};
query = {
[Op.or]: [
{
@@ -155,19 +162,11 @@ export default class CronService {
} catch (error) {
throw error;
}
function createRegexp(text:string) {
return {
[Op.or]: [
{ [Op.like]: `%${text}%` },
{ [Op.like]: `%${encodeURIComponent(text)}%` },
],
};
}
}
public async get(id: number): Promise<Crontab> {
const result = await CrontabModel.findAll({ where: { id } });
return result[0] as any;
public async getDb(query: any): Promise<Crontab> {
const doc: any = await CrontabModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as Crontab);
}
public async run(ids: number[]) {
@@ -243,7 +242,7 @@ export default class CronService {
private async runSingle(cronId: number): Promise<number> {
return new Promise(async (resolve: any) => {
const cron = await this.get(cronId);
const cron = await this.getDb({ id: cronId });
if (cron.status !== CrontabStatus.queued) {
resolve();
return;
@@ -312,7 +311,7 @@ export default class CronService {
}
public async log(id: number) {
const doc = await this.get(id);
const doc = await this.getDb({ id });
if (!doc) {
return '';
}
+24 -28
View File
@@ -41,7 +41,7 @@ export default class DependenceService {
payload: Dependence & { id: string },
): Promise<Dependence> {
const { id, ...other } = payload;
const doc = await this.get(id);
const doc = await this.getDb({ id });
const tab = new Dependence({
...doc,
...other,
@@ -53,18 +53,16 @@ export default class DependenceService {
}
private async updateDb(payload: Dependence): Promise<Dependence> {
const [, docs] = await DependenceModel.update(
{ ...payload },
{ where: { id: payload.id } },
);
return docs[0];
await DependenceModel.update(payload, { where: { id: payload.id } });
return await this.getDb({ id: payload.id });
}
public async remove(ids: number[]) {
const [, docs] = await DependenceModel.update(
await DependenceModel.update(
{ status: DependenceStatus.removing, log: [] },
{ where: { id: ids } },
);
const docs = await DependenceModel.findAll({ where: { id: ids } });
this.installOrUninstallDependencies(docs, false);
}
@@ -82,7 +80,7 @@ export default class DependenceService {
const encodeText = encodeURIComponent(searchValue);
const reg = {
[Op.or]: [
{ [Op.like]: `%${encodeText}&` },
{ [Op.like]: `%${searchValue}&` },
{ [Op.like]: `%${encodeText}%` },
],
};
@@ -101,10 +99,12 @@ export default class DependenceService {
}
public async reInstall(ids: number[]): Promise<Dependence[]> {
const [, docs] = await DependenceModel.update(
await DependenceModel.update(
{ status: DependenceStatus.installing, log: [] },
{ where: { id: ids } },
);
const docs = await DependenceModel.findAll({ where: { id: ids } });
await this.installOrUninstallDependencies(docs);
return docs;
}
@@ -114,25 +114,22 @@ export default class DependenceService {
return docs;
}
public async get(id: number): Promise<Dependence> {
const docs = await DependenceModel.findAll({ where: { id } });
return docs[0];
public async getDb(query: any): Promise<Dependence> {
const doc: any = await DependenceModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as Dependence);
}
private async updateLog(ids: number[], log: string): Promise<void> {
const doc = await DependenceModel.findOne({ where: { id: ids } });
const newLog = doc?.log ? [...doc.log, log] : [log];
const [, docs] = await DependenceModel.update(
{ status: DependenceStatus.installing, log: newLog },
{ where: { id: ids } },
);
await DependenceModel.update({ log: newLog }, { where: { id: ids } });
}
public installOrUninstallDependencies(
dependencies: Dependence[],
isInstall: boolean = true,
) {
return new Promise((resolve) => {
return new Promise(async (resolve) => {
if (dependencies.length === 0) {
resolve(null);
return;
@@ -154,41 +151,41 @@ export default class DependenceService {
).toLocaleString()}`,
references: depIds,
});
this.updateLog(
await this.updateLog(
depIds,
`开始${actionText}依赖 ${depNames},开始时间 ${new Date(
startTime,
).toLocaleString()}\n`,
);
cp.stdout.on('data', (data) => {
cp.stdout.on('data', async (data) => {
this.sockService.sendMessage({
type: 'installDependence',
message: data.toString(),
references: depIds,
});
this.updateLog(depIds, data.toString());
await this.updateLog(depIds, data.toString());
});
cp.stderr.on('data', (data) => {
cp.stderr.on('data', async (data) => {
this.sockService.sendMessage({
type: 'installDependence',
message: data.toString(),
references: depIds,
});
this.updateLog(depIds, data.toString());
await this.updateLog(depIds, data.toString());
});
cp.on('error', (err) => {
cp.on('error', async (err) => {
this.sockService.sendMessage({
type: 'installDependence',
message: JSON.stringify(err),
references: depIds,
});
this.updateLog(depIds, JSON.stringify(err));
await this.updateLog(depIds, JSON.stringify(err));
resolve(null);
});
cp.on('close', (code) => {
cp.on('close', async (code) => {
const endTime = Date.now();
const isSucceed = code === 0;
const resultText = isSucceed ? '成功' : '失败';
@@ -200,7 +197,7 @@ export default class DependenceService {
).toLocaleString()},耗时 ${(endTime - startTime) / 1000}`,
references: depIds,
});
this.updateLog(
await this.updateLog(
depIds,
`依赖${actionText}${resultText},结束时间 ${new Date(
endTime,
@@ -217,8 +214,7 @@ export default class DependenceService {
? DependenceStatus.installFailed
: DependenceStatus.removeFailed;
}
DependenceModel.update({ status }, { where: { id: depIds } });
await DependenceModel.update({ status }, { where: { id: depIds } });
// 如果删除依赖成功,3秒后删除数据库记录
if (isSucceed && !isInstall) {
+9 -18
View File
@@ -34,20 +34,14 @@ export default class EnvService {
}
public async update(payload: Env): Promise<Env> {
const { id, ...other } = payload;
const doc = await this.get(id as number);
const tab = new Env({ ...doc, ...other });
const newDoc = await this.updateDb(tab);
const newDoc = await this.updateDb(payload);
await this.set_envs();
return newDoc;
}
private async updateDb(payload: Env): Promise<Env> {
const [, docs] = await EnvModel.update(
{ ...payload },
{ where: { id: payload.id } },
);
return docs[0];
await EnvModel.update({ ...payload }, { where: { id: payload.id } });
return await this.getDb({ id: payload.id });
}
public async remove(ids: string[]) {
@@ -126,13 +120,13 @@ export default class EnvService {
return docs;
}
public async get(id: number): Promise<Env> {
const docs = await EnvModel.findAll({ where: { id } });
return docs[0];
public async getDb(query: any): Promise<Env> {
const doc: any = await EnvModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as Env);
}
public async disabled(ids: string[]) {
const [, docs] = await EnvModel.update(
await EnvModel.update(
{ status: EnvStatus.disabled },
{ where: { id: ids } },
);
@@ -140,15 +134,12 @@ export default class EnvService {
}
public async enabled(ids: string[]) {
const [, docs] = await EnvModel.update(
{ status: EnvStatus.normal },
{ where: { id: ids } },
);
await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } });
await this.set_envs();
}
public async updateNames({ ids, name }: { ids: string[]; name: string }) {
const [, docs] = await EnvModel.update({ name }, { where: { id: ids } });
await EnvModel.update({ name }, { where: { id: ids } });
await this.set_envs();
}
+22 -27
View File
@@ -12,7 +12,7 @@ export default class OpenService {
constructor(@Inject('logger') private logger: winston.Logger) {}
public async findTokenByValue(token: string): Promise<App | null> {
const doc = await AppModel.findOne({
const doc = await this.getDb({
where: sequelize.fn(
'JSON_CONTAINS',
sequelize.col('tokens'),
@@ -23,32 +23,35 @@ export default class OpenService {
}
public async create(payload: App): Promise<App> {
const tab = new App({ ...payload });
const tab = { ...payload };
tab.client_id = createRandomString(12, 12);
tab.client_secret = createRandomString(24, 24);
const docs = await this.insert([tab]);
return { ...docs[0], tokens: [] };
const doc = await this.insert(tab);
return { ...doc, tokens: [] };
}
public async insert(payloads: App[]): Promise<App[]> {
const docs = await AppModel.bulkCreate(payloads);
return docs;
public async insert(payloads: App): Promise<App> {
const doc = await AppModel.create(payloads, { returning: true });
return doc.get({ plain: true }) as App;
}
public async update(payload: App): Promise<App> {
const { id, client_id, client_secret, tokens, ...other } = payload;
const doc = await this.get(id);
const tab = new App({ ...doc, ...other });
const newDoc = await this.updateDb(tab);
const newDoc = await this.updateDb({
name: payload.name,
scopes: payload.scopes,
id: payload.id,
} as any);
return { ...newDoc, tokens: [] };
}
private async updateDb(payload: App): Promise<App> {
const [, docs] = await AppModel.update(
{ ...payload },
{ where: { id: payload.id } },
);
return docs[0];
await AppModel.update(payload, { where: { id: payload.id } });
return await this.getDb({ id: payload.id });
}
public async getDb(query: any): Promise<App> {
const doc: any = await AppModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as App);
}
public async remove(ids: number[]) {
@@ -56,10 +59,7 @@ export default class OpenService {
}
public async resetSecret(id: number): Promise<App> {
const doc = await this.get(id);
const tab = new App({ ...doc });
tab.client_secret = createRandomString(24, 24);
tab.tokens = [];
const tab: any = { client_secret: createRandomString(24, 24), tokens: [] };
const newDoc = await this.updateDb(tab);
return newDoc;
}
@@ -104,12 +104,7 @@ export default class OpenService {
private async find(query: any, sort?: any): Promise<App[]> {
const docs = await AppModel.findAll({ where: { ...query } });
return docs;
}
public async get(id: number): Promise<App> {
const docs = await AppModel.findAll({ where: { id } });
return docs[0];
return docs.map((x) => x.get({ plain: true }));
}
public async authToken({
@@ -123,7 +118,7 @@ export default class OpenService {
const expiration = Math.round(Date.now() / 1000) + 2592000; // 2592000 30天
const doc = await AppModel.findOne({ where: { client_id, client_secret } });
if (doc) {
const [, docs] = await AppModel.update(
await AppModel.update(
{ tokens: [...(doc.tokens || []), { value: token, expiration }] },
{ where: { client_id, client_secret } },
);
+7 -4
View File
@@ -24,18 +24,21 @@ export default class SystemService {
) {}
public async getLogRemoveFrequency() {
const doc = await AuthModel.findOne({
where: { type: AuthDataType.removeLogFrequency },
});
const doc = await this.getDb({ type: AuthDataType.removeLogFrequency });
return (doc && doc.info) || {};
}
private async updateAuthDb(payload: AuthInfo): Promise<any> {
await AuthModel.upsert({ ...payload });
const doc = await AuthModel.findOne({ where: { type: payload.type } });
const doc = await this.getDb({ type: payload.type });
return doc;
}
public async getDb(query: any): Promise<any> {
const doc: any = await AuthModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as any);
}
public async updateNotificationMode(notificationInfo: NotificationInfo) {
const code = Math.random().toString().slice(-6);
const isSuccess = await this.notificationService.testNotify(
+8 -7
View File
@@ -303,25 +303,26 @@ export default class UserService {
}
public async getNotificationMode(): Promise<NotificationInfo> {
const doc = await AuthModel.findOne({
where: { type: AuthDataType.notification },
});
const doc = await this.getDb({ type: AuthDataType.notification });
return (doc && doc.info) || {};
}
public async getLogRemoveFrequency() {
const doc = await AuthModel.findOne({
where: { type: AuthDataType.removeLogFrequency },
});
const doc = await this.getDb({ type: AuthDataType.removeLogFrequency });
return (doc && doc.info) || {};
}
private async updateAuthDb(payload: AuthInfo): Promise<any> {
await AuthModel.upsert({ ...payload });
const doc = await AuthModel.findOne({ where: { type: payload.type } });
const doc = await this.getDb({ type: payload.type });
return doc;
}
public async getDb(query: any): Promise<any> {
const doc: any = await AuthModel.findOne({ where: { ...query } });
return doc && (doc.get({ plain: true }) as any);
}
public async updateNotificationMode(notificationInfo: NotificationInfo) {
const code = Math.random().toString().slice(-6);
const isSuccess = await this.notificationService.testNotify(