filter rule event type in rule engine

This commit is contained in:
Hongbo Wu 2023-07-20 18:47:17 +08:00
parent 9a224d2324
commit 71487e14c3
2 changed files with 19 additions and 21 deletions

View file

@ -1,9 +1,9 @@
import * as Sentry from '@sentry/serverless'
import express, { Request, Response } from 'express'
import * as dotenv from 'dotenv'
import { getEnabledRules, triggerActions } from './rule'
import { promisify } from 'util'
import express, { Request, Response } from 'express'
import * as jwt from 'jsonwebtoken'
import { promisify } from 'util'
import { getEnabledRules, RuleEventType, triggerActions } from './rule'
const signToken = promisify(jwt.sign)
@ -76,6 +76,10 @@ export const getAuthToken = async (
return auth as string
}
const ruleEventType = (eventType: string) => {
return `PAGE_${eventType.toUpperCase()}` as RuleEventType
}
export const ruleHandler = Sentry.GCPFunction.wrapHttpFunction(
async (req: Request, res: Response) => {
const apiEndpoint = process.env.REST_BACKEND_ENDPOINT
@ -134,7 +138,7 @@ export const ruleHandler = Sentry.GCPFunction.wrapHttpFunction(
data,
apiEndpoint,
jwtSecret,
eventType
ruleEventType(eventType)
)
if (triggeredActions.length === 0) {
console.log('No actions triggered')

View file

@ -17,6 +17,11 @@ export interface RuleAction {
params: string[]
}
export enum RuleEventType {
PageCreated = 'PAGE_CREATED',
PageUpdated = 'PAGE_UPDATED',
}
export interface Rule {
id: string
userId: string
@ -27,10 +32,9 @@ export interface Rule {
enabled: boolean
createdAt: Date
updatedAt: Date
eventTypes: RuleEventType[]
}
const EVENT_FILTERS = ['event:created', 'event:updated']
export const getEnabledRules = async (
userId: string,
apiEndpoint: string,
@ -53,6 +57,7 @@ export const getEnabledRules = async (
type
params
}
eventTypes
}
}
}
@ -76,33 +81,22 @@ export const triggerActions = async (
data: PubSubData,
apiEndpoint: string,
jwtSecret: string,
eventType: string
eventType: RuleEventType
) => {
const authToken = await getAuthToken(userId, jwtSecret)
const actionPromises: Promise<AxiosResponse<any, any> | undefined>[] = []
for (const rule of rules) {
let filter = rule.filter
const filters = filter.split(' ')
// Check if the rule is enabled for the event type
const eventFilterIndex = filters.findIndex((f) => EVENT_FILTERS.includes(f))
if (eventFilterIndex !== -1) {
const eventFilter = filters[eventFilterIndex]
if (eventFilter !== `event:${eventType}`.toLowerCase()) {
continue
}
// Remove the event filter from the filter string
filters.splice(eventFilterIndex, 1)
filter = filters.join(' ')
if (!rule.eventTypes.includes(eventType)) {
continue
}
const filteredPage = await filterPage(
userId,
apiEndpoint,
authToken,
filter,
rule.filter,
data.id
)
if (!filteredPage) {