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

101 lines
3.4 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 { generateNewIdAsync } from 'oak-domain/lib/utils/uuid';
import { assert } from 'oak-domain/lib/utils/assert';
const triggers = [
{
name: '当创建userEntityGrant时尝试为之创建一个wechatQrCode',
entity: 'userEntityGrant',
action: 'create',
when: 'before',
fn: async ({ operation }, context, params) => {
const { data, filter } = operation;
const fn = async (userEntityGrantData) => {
const { userId } = context.getToken();
assert(userId);
const { id, claimUrl } = userEntityGrantData;
Object.assign(userEntityGrantData, {
granterId: userId,
expired: false,
});
if (!userEntityGrantData.expiresAt) {
Object.assign(userEntityGrantData, {
expiresAt: Date.now() + 300 * 1000,
});
}
userEntityGrantData.wechatQrCode$entity = [
{
id: await generateNewIdAsync(),
action: 'create',
data: {
id: await generateNewIdAsync(),
props: {
pathname: claimUrl || '/userEntityGrant/claim',
props: {
oakId: id,
},
},
type: userEntityGrantData.qrCodeType,
},
}
];
};
if (data instanceof Array) {
assert('授权不存在一对多的情况');
}
else {
await fn(data);
}
return 0;
},
},
{
name: '当userEntityGrant过期时使其相关的wechatQrCode也过期',
entity: 'userEntityGrant',
action: ['update', 'claim'],
check: (operation) => {
const { data } = operation;
return !!data.expired;
},
priority: 32,
when: 'before',
fn: async ({ operation }, context) => {
const { data, filter } = operation;
data.wechatQrCode$entity = [
{
id: await generateNewIdAsync(),
action: 'update',
data: {
expired: true,
expiresAt: Date.now(),
},
}
];
return 1;
},
},
{
name: '当claim一个userEntityGrant时如果是单次的则将之过期',
entity: 'userEntityGrant',
action: 'claim',
when: 'before',
priority: 13,
fn: async ({ operation }, context) => {
const { data, filter } = operation;
assert(typeof filter.id === 'string');
const [userEntityGrant] = await context.select('userEntityGrant', {
data: {
id: 1,
multiple: 1,
},
filter
}, { dontCollect: true });
if (!userEntityGrant.multiple) {
data.expired = true;
data.expiresAt = Date.now();
return 1;
}
return 0;
}
}
];
export default triggers;