Skip to content

Commit

Permalink
feat: exposes findMany argument to afterRead hooks to discern between…
Browse files Browse the repository at this point in the history
… find and findByID
  • Loading branch information
jmikrut committed May 2, 2022
1 parent 18489fa commit b3832e2
Show file tree
Hide file tree
Showing 14 changed files with 46 additions and 17 deletions.
5 changes: 3 additions & 2 deletions demo/collections/Hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ const Hooks: CollectionConfig = {
],
afterRead: [
((operation) => {
const { doc } = operation;
const { doc, findMany } = operation;
doc.afterReadHook = true;
doc.findMany = findMany;

return doc;
}) as AfterReadHook<Hook & { afterReadHook: boolean }>,
}) as AfterReadHook<Hook & { afterReadHook: boolean, findMany: boolean }>,
],
afterChange: [
((operation) => {
Expand Down
1 change: 1 addition & 0 deletions docs/hooks/collections.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ const afterReadHook = async ({
doc, // full document data
req, // full express request
query, // JSON formatted query
findMany, // boolean to denote if this hook is running against finding one, or finding many
}) => {
return doc;
}
Expand Down
7 changes: 4 additions & 3 deletions docs/hooks/fields.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,13 @@ Field Hooks receive one `args` argument that contains the following properties:

| Option | Description |
| ----------------- | -------------|
| **`value`** | The value of the field. |
| **`data`** | The data passed to update the document within `create` and `update` operations, and the full document itself in the `afterRead` hook. |
| **`siblingData`** | The sibling data passed to a field that the hook is running against. |
| **`originalDoc`** | The full original document in `update` operations. |
| **`findMany`** | Boolean to denote if this hook is running against finding one, or finding many within the `afterRead` hook. |
| **`operation`** | A string relating to which operation the field type is currently executing within. Useful within `beforeValidate`, `beforeChange`, and `afterChange` hooks to differentiate between `create` and `update` operations. |
| **`originalDoc`** | The full original document in `update` operations. |
| **`req`** | The Express `request` object. It is mocked for Local API operations. |
| **`siblingData`** | The sibling data passed to a field that the hook is running against. |
| **`value`** | The value of the field. |

#### Return value

Expand Down
1 change: 1 addition & 0 deletions docs/hooks/globals.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ Runs as the last step before a global is returned. Flattens locales, hides prote
const afterReadHook = async ({
doc, // full document data
req, // full express request
findMany, // boolean to denote if this hook is running against finding one, or finding many (useful in versions)
}) => {...}
```

Expand Down
1 change: 1 addition & 0 deletions src/collections/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export type AfterReadHook<T extends TypeWithID = any> = (args: {
doc: T;
req: PayloadRequest;
query?: { [key: string]: any };
findMany?: boolean
}) => any;

export type BeforeDeleteHook = (args: {
Expand Down
3 changes: 2 additions & 1 deletion src/collections/operations/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ async function find<T extends TypeWithID = any>(incomingArgs: Arguments): Promis
overrideAccess,
req,
showHiddenFields,
findMany: true,
}))),
};

Expand All @@ -192,7 +193,7 @@ async function find<T extends TypeWithID = any>(incomingArgs: Arguments): Promis
await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {
await priorHook;

docRef = await hook({ req, query, doc }) || doc;
docRef = await hook({ req, query, doc, findMany: true }) || doc;
}, Promise.resolve());

return docRef;
Expand Down
3 changes: 2 additions & 1 deletion src/collections/operations/findVersions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ async function findVersions<T extends TypeWithVersion<T> = any>(this: Payload, a
overrideAccess,
req,
showHiddenFields,
findMany: true,
}),
}))),
};
Expand All @@ -155,7 +156,7 @@ async function findVersions<T extends TypeWithVersion<T> = any>(this: Payload, a
await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {
await priorHook;

docRef.version = await hook({ req, query, doc: doc.version }) || doc.version;
docRef.version = await hook({ req, query, doc: doc.version, findMany: true }) || doc.version;
}, Promise.resolve());

return docRef;
Expand Down
6 changes: 6 additions & 0 deletions src/collections/tests/hooks.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ describe('Collections - REST', () => {
const getResponseData = await getResponse.json();
expect(getResponse.status).toBe(200);
expect(getResponseData.afterReadHook).toStrictEqual(true);
expect(getResponseData.findMany).toBeUndefined();

const getManyResponse = await fetch(`${url}/api/hooks`);
const getManyResponseData = await getManyResponse.json();

expect(getManyResponseData.docs[0].findMany).toStrictEqual(true);
});

it('afterChange', async () => {
Expand Down
7 changes: 4 additions & 3 deletions src/fields/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import { User } from '../../auth';
import { Payload } from '../..';

export type FieldHookArgs<T extends TypeWithID = any, P = any, S = any> = {
value?: P,
originalDoc?: T,
data?: Partial<T>,
siblingData: Partial<S>
findMany?: boolean
originalDoc?: T,
operation?: 'create' | 'read' | 'update' | 'delete',
req: PayloadRequest
siblingData: Partial<S>
value?: P,
}

export type FieldHook<T extends TypeWithID = any, P = any, S = any> = (args: FieldHookArgs<T, P, S>) => Promise<P> | P;
Expand Down
3 changes: 3 additions & 0 deletions src/fields/hooks/afterRead/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type Args = {
depth: number
doc: Record<string, unknown>
entityConfig: SanitizedCollectionConfig | SanitizedGlobalConfig
findMany?: boolean
flattenLocales?: boolean
req: PayloadRequest
overrideAccess: boolean
Expand All @@ -21,6 +22,7 @@ export async function afterRead<T = any>(args: Args): Promise<T> {
depth: incomingDepth,
doc: incomingDoc,
entityConfig,
findMany,
flattenLocales = true,
req,
overrideAccess,
Expand All @@ -47,6 +49,7 @@ export async function afterRead<T = any>(args: Args): Promise<T> {
doc,
fields: entityConfig.fields,
fieldPromises,
findMany,
flattenLocales,
overrideAccess,
populationPromises,
Expand Down
13 changes: 10 additions & 3 deletions src/fields/hooks/afterRead/promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ type Args = {
doc: Record<string, unknown>
field: Field
fieldPromises: Promise<void>[]
findMany: boolean
flattenLocales: boolean
populationPromises: Promise<void>[]
req: PayloadRequest
Expand All @@ -33,6 +34,7 @@ export const promise = async ({
doc,
field,
fieldPromises,
findMany,
flattenLocales,
overrideAccess,
populationPromises,
Expand Down Expand Up @@ -130,12 +132,13 @@ export const promise = async ({
await Promise.all(hookPromises);
} else {
const hookedValue = await currentHook({
value: siblingDoc[field.name],
originalDoc: doc,
data: doc,
siblingData: siblingDoc[field.name],
findMany,
originalDoc: doc,
operation: 'read',
siblingData: siblingDoc[field.name],
req,
value: siblingDoc[field.name],
});

if (hookedValue !== undefined) {
Expand Down Expand Up @@ -178,6 +181,7 @@ export const promise = async ({
doc,
fieldPromises,
fields: field.fields,
findMany,
flattenLocales,
overrideAccess,
populationPromises,
Expand All @@ -200,6 +204,7 @@ export const promise = async ({
doc,
fields: field.fields,
fieldPromises,
findMany,
flattenLocales,
overrideAccess,
populationPromises,
Expand All @@ -226,6 +231,7 @@ export const promise = async ({
doc,
fields: block.fields,
fieldPromises,
findMany,
flattenLocales,
overrideAccess,
populationPromises,
Expand All @@ -247,6 +253,7 @@ export const promise = async ({
doc,
fieldPromises,
fields: field.fields,
findMany,
flattenLocales,
overrideAccess,
populationPromises,
Expand Down
3 changes: 3 additions & 0 deletions src/fields/hooks/afterRead/traverseFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type Args = {
doc: Record<string, unknown>
fieldPromises: Promise<void>[]
fields: Field[]
findMany: boolean
flattenLocales: boolean
populationPromises: Promise<void>[]
req: PayloadRequest
Expand All @@ -22,6 +23,7 @@ export const traverseFields = ({
doc,
fieldPromises,
fields,
findMany,
flattenLocales,
overrideAccess,
populationPromises,
Expand All @@ -36,6 +38,7 @@ export const traverseFields = ({
doc,
field,
fieldPromises,
findMany,
flattenLocales,
overrideAccess,
populationPromises,
Expand Down
7 changes: 4 additions & 3 deletions src/globals/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ export type BeforeReadHook = (args: {
}) => any;

export type AfterReadHook = (args: {
doc: any;
req: PayloadRequest;
query?: { [key: string]: any };
doc: any
req: PayloadRequest
query?: { [key: string]: any }
findMany?: boolean
}) => any;

export interface GlobalModel extends Model<Document> {
Expand Down
3 changes: 2 additions & 1 deletion src/globals/operations/findVersions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ async function findVersions<T extends TypeWithVersion<T> = any>(args: Arguments)
req,
overrideAccess,
showHiddenFields,
findMany: true,
}),
}))),
};
Expand All @@ -132,7 +133,7 @@ async function findVersions<T extends TypeWithVersion<T> = any>(args: Arguments)
await globalConfig.hooks.afterRead.reduce(async (priorHook, hook) => {
await priorHook;

docRef.version = await hook({ req, query, doc: doc.version }) || doc.version;
docRef.version = await hook({ req, query, doc: doc.version, findMany: true }) || doc.version;
}, Promise.resolve());

return docRef;
Expand Down

0 comments on commit b3832e2

Please sign in to comment.