1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48import type { CollectionBeforeOperationHook, Plugin } from 'payload'
import { APIError } from 'payload'
type Args = {
max?: number
warnAt?: number
}
export const opsCounterPlugin =
(args?: Args): Plugin =>
(config) => {
const max = args?.max || 50
const warnAt = args?.warnAt || 10
const beforeOperationHook: CollectionBeforeOperationHook = ({ collection, operation, req }) => {
const currentCount = req.context.opsCount
if (typeof currentCount === 'number') {
req.context.opsCount = currentCount + 1
if (warnAt && currentCount >= warnAt) {
req.payload.logger.error(
`Detected a ${operation} in the "${collection.slug}" collection which has run ${warnAt} times or more.`,
)
}
if (currentCount > max) {
throw new APIError(`Maximum operations of ${max} detected.`)
}
} else {
req.context.opsCount = 1
}
}
;(config.collections || []).forEach((collection) => {
if (!collection.hooks) {
collection.hooks = {}
}
if (!collection.hooks.beforeOperation) {
collection.hooks.beforeOperation = []
}
collection.hooks.beforeOperation.push(beforeOperationHook)
})
return config
}