oak-general-business/es/triggers/oauthProvider.js

145 lines
5.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import assert from 'assert';
import { generateNewIdAsync } from 'oak-domain/lib/utils/uuid';
import { cloneDeep, pull } from 'oak-domain/lib/utils/lodash';
const triggers = [
{
name: "创建provider时填充数据",
action: "create",
when: "before",
entity: "oauthProvider",
fn: async ({ operation }, context) => {
assert(operation.data && !Array.isArray(operation.data), "oauthProvider create data 必须存在且为单条记录");
const { data } = operation;
const systemId = context.getSystemId();
data.systemId = systemId;
return 0;
}
},
{
name: "创建provider时新增passport",
action: "create",
when: "after",
entity: "oauthProvider",
asRoot: true,
fn: async ({ operation }, context, option) => {
const { data } = operation;
let count = 0;
if (data?.systemId) {
const [passport] = await context.select('passport', {
data: {
id: 1,
systemId: 1,
type: 1,
},
filter: {
systemId: data?.systemId,
type: 'oauth',
},
indexFrom: 0,
count: 1,
}, { forUpdate: true });
if (!passport) {
await context.operate('passport', {
id: await generateNewIdAsync(),
action: 'create',
data: {
id: await generateNewIdAsync(),
type: 'oauth',
enabled: false,
systemId: data?.systemId,
config: {
oauthIds: [data?.id],
}
}
}, option);
count++;
}
}
return count;
}
},
{
name: "删除provider时删除passport",
action: "remove",
when: "before",
entity: "oauthProvider",
asRoot: true,
fn: async ({ operation }, context, option) => {
const { filter } = operation;
const [oauthProvider] = await context.select('oauthProvider', {
data: {
id: 1,
systemId: 1,
},
filter: filter,
}, { forUpdate: true });
let count = 0;
if (oauthProvider) {
const { id, systemId } = oauthProvider;
const [other] = await context.select('oauthProvider', {
data: {
id: 1,
systemId: 1,
},
filter: {
systemId,
id: {
$ne: id,
}
},
indexFrom: 0,
count: 1,
}, { forUpdate: true });
if (!other) {
await context.operate('passport', {
id: await generateNewIdAsync(),
action: 'remove',
data: {},
filter: {
systemId,
type: 'oauth'
}
}, option);
count++;
}
else {
const [passport] = await context.select('passport', {
data: {
id: 1,
type: 1,
config: 1,
systemId: 1,
},
filter: {
type: 'oauth',
systemId,
config: {
oauthIds: {
$contains: [id],
}
}
}
}, { forUpdate: true });
if (passport) {
const { id: passportId, config } = passport;
let newConfig = cloneDeep(config);
pull(newConfig?.oauthIds, id);
await context.operate('passport', {
id: await generateNewIdAsync(),
action: 'update',
data: {
config: newConfig,
},
filter: {
id: passportId,
}
}, option);
}
}
}
return count;
}
},
];
export default triggers;