Skip to content

Commit a22e025

Browse files
committed
chore: add warnAt, readme
1 parent 46a6869 commit a22e025

File tree

3 files changed

+22
-7
lines changed

3 files changed

+22
-7
lines changed

README.md

+11-5
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1-
# blank
1+
# Recursion Prevention Plugin
22

3-
blank
3+
This repo contains a simple plugin to detect recursion caused by Payload hooks. For example, if you have a hook that updates a document, which in turn, fires another hook which again updates that same document, you could cause an infinite recursion.
44

5-
## Attributes
5+
This plugin detects those infinite recursions and will throw an error to short-circuit any faulty logic before the server crashes.
66

7-
- **Database**: mongodb
8-
- **Storage Adapter**: localDisk
7+
### Running locally
8+
9+
To run this repository locally, perform the following steps.
10+
11+
1. Clone the repo
12+
1. Run `cp .env.example .env` to create an environment variable file
13+
1. Run `pnpm i` to install dependencies
14+
1. Run `pnpm dev` and then create a post to watch the plugin detect and throw when the post is created

src/payload.config.ts

+1
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ export default buildConfig({
7070
// defaults to 50
7171
opsCounterPlugin({
7272
max: 25,
73+
warnAt: 10,
7374
}),
7475
],
7576
})

src/plugins/OpsCounter.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
11
import { APIError, CollectionBeforeOperationHook, Plugin } from 'payload'
22

33
type Args = {
4-
max: number
4+
max?: number
5+
warnAt?: number
56
}
67

78
export const opsCounterPlugin =
89
(args?: Args): Plugin =>
910
(config) => {
1011
const max = args?.max || 50
12+
const warnAt = args?.warnAt || 10
1113

12-
const beforeOperationHook: CollectionBeforeOperationHook = ({ req }) => {
14+
const beforeOperationHook: CollectionBeforeOperationHook = ({ req, collection, operation }) => {
1315
const currentCount = req.context.opsCount
1416

1517
if (typeof currentCount === 'number') {
1618
req.context.opsCount = currentCount + 1
1719

20+
if (warnAt && currentCount >= warnAt) {
21+
req.payload.logger.error(
22+
`Detected a ${operation} in the "${collection}" collection which has run ${warnAt} times or more.`,
23+
)
24+
}
25+
1826
if (currentCount > max) {
1927
throw new APIError(`Maximum operations of ${max} detected.`)
2028
}

0 commit comments

Comments
 (0)