payload-smart-deletion 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hooks.js +2 -2
- package/dist/hooks.js.map +1 -1
- package/dist/internals/index.d.ts +22 -11
- package/dist/internals/index.d.ts.map +1 -1
- package/dist/internals/index.js +50 -4
- package/dist/internals/index.js.map +1 -1
- package/dist/internals/procedure.d.ts.map +1 -1
- package/dist/internals/procedure.js +1 -0
- package/dist/internals/procedure.js.map +1 -1
- package/package.json +4 -4
package/dist/hooks.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { resolveDocumentID } from '@repo/common';
|
|
2
2
|
/**
|
|
3
3
|
* Cascades hard-deletes to all documents referenced by a relationship field.
|
|
4
4
|
*/ export const createHardDeleteHook = ({ path, relationTo })=>async ({ doc, req })=>{
|
|
@@ -82,7 +82,7 @@ function getByPath(obj, path) {
|
|
|
82
82
|
const col = isPolymorphic ? ref.relationTo : relationTo;
|
|
83
83
|
const raw = isPolymorphic ? ref.value : entry;
|
|
84
84
|
if (!col || raw == null) continue;
|
|
85
|
-
const id =
|
|
85
|
+
const id = resolveDocumentID(raw);
|
|
86
86
|
const ids = grouped.get(col);
|
|
87
87
|
if (ids) {
|
|
88
88
|
ids.push(id);
|
package/dist/hooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../src/hooks.ts"],"sourcesContent":["import { resolveDocumentID } from '@repo/common';\nimport type { FieldWithPath } from '@repo/common/utils';\nimport type {\n CollectionAfterChangeHook,\n CollectionAfterDeleteHook,\n CollectionSlug,\n RelationshipField,\n} from 'payload';\n\n/**\n * Cascades hard-deletes to all documents referenced by a relationship field.\n */\nexport const createHardDeleteHook =\n ({\n path,\n relationTo,\n }: FieldWithPath<RelationshipField>): CollectionAfterDeleteHook =>\n async ({ doc, req }) => {\n const grouped = groupByCollection(getByPath(doc, path), relationTo);\n\n for (const [collection, ids] of grouped) {\n await req.payload.delete({\n collection: collection as CollectionSlug,\n where: { id: { in: ids } },\n req,\n });\n }\n };\n\n/**\n * Cascades soft-deletes (trash) to all documents referenced by a relationship field\n * when the parent transitions from live to trashed.\n */\nexport const createSoftDeleteHook =\n ({\n path,\n relationTo,\n }: FieldWithPath<RelationshipField>): CollectionAfterChangeHook =>\n async ({ doc, previousDoc, req, operation }) => {\n if (operation !== 'update') return doc;\n if (previousDoc.deletedAt || !doc.deletedAt) return doc;\n\n const grouped = groupByCollection(getByPath(doc, path), relationTo);\n\n for (const [collection, ids] of grouped) {\n await req.payload.update({\n collection: collection as CollectionSlug,\n where: { id: { in: ids } },\n data: { deletedAt: new Date().toISOString() },\n req,\n });\n }\n\n return doc;\n };\n\n/**\n * Cascades restores to all documents referenced by a relationship field\n * when the parent transitions from trashed to live.\n */\nexport const createRestoreHook =\n ({\n path,\n relationTo,\n }: FieldWithPath<RelationshipField>): CollectionAfterChangeHook =>\n async ({ doc, previousDoc, req, operation }) => {\n if (operation !== 'update') return doc;\n if (!previousDoc.deletedAt || doc.deletedAt) return doc;\n\n const grouped = groupByCollection(getByPath(doc, path), relationTo);\n\n for (const [collection, ids] of grouped) {\n await req.payload.update({\n collection: collection as CollectionSlug,\n where: { id: { in: ids } },\n data: { deletedAt: null },\n req,\n trash: true,\n });\n }\n\n return doc;\n };\n\n// MARK: Utilities\n\nfunction getByPath(obj: Record<string, unknown>, path: string[]) {\n return path.reduce<unknown>(\n (acc, key) => (acc as Record<string, unknown> | undefined)?.[key],\n obj,\n );\n}\n\n/**\n * Groups relationship values by target collection slug.\n * Handles both non-polymorphic (plain IDs / populated objects)\n * and polymorphic (`{ relationTo, value }`) shapes.\n */\nfunction groupByCollection(\n value: unknown,\n relationTo: CollectionSlug | CollectionSlug[],\n): Map<string, (string | number)[]> {\n const entries = Array.isArray(value) ? value : [value];\n const isPolymorphic = Array.isArray(relationTo);\n const grouped = new Map<string, (string | number)[]>();\n\n for (const entry of entries) {\n if (entry == null) continue;\n const ref = entry as Record<string, unknown>;\n const col = isPolymorphic ? (ref.relationTo as string) : relationTo;\n const raw = isPolymorphic ? ref.value : entry;\n if (!col || raw == null) continue;\n const id = resolveDocumentID(raw);\n const ids = grouped.get(col);\n if (ids) {\n ids.push(id);\n } else {\n grouped.set(col, [id]);\n }\n }\n\n return grouped;\n}\n"],"names":["resolveDocumentID","createHardDeleteHook","path","relationTo","doc","req","grouped","groupByCollection","getByPath","collection","ids","payload","delete","where","id","in","createSoftDeleteHook","previousDoc","operation","deletedAt","update","data","Date","toISOString","createRestoreHook","trash","obj","reduce","acc","key","value","entries","Array","isArray","isPolymorphic","Map","entry","ref","col","raw","get","push","set"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,eAAe;AASjD;;CAEC,GACD,OAAO,MAAMC,uBACX,CAAC,EACCC,IAAI,EACJC,UAAU,EACuB,GACnC,OAAO,EAAEC,GAAG,EAAEC,GAAG,EAAE;QACjB,MAAMC,UAAUC,kBAAkBC,UAAUJ,KAAKF,OAAOC;QAExD,KAAK,MAAM,CAACM,YAAYC,IAAI,IAAIJ,QAAS;YACvC,MAAMD,IAAIM,OAAO,CAACC,MAAM,CAAC;gBACvBH,YAAYA;gBACZI,OAAO;oBAAEC,IAAI;wBAAEC,IAAIL;oBAAI;gBAAE;gBACzBL;YACF;QACF;IACF,EAAE;AAEJ;;;CAGC,GACD,OAAO,MAAMW,uBACX,CAAC,EACCd,IAAI,EACJC,UAAU,EACuB,GACnC,OAAO,EAAEC,GAAG,EAAEa,WAAW,EAAEZ,GAAG,EAAEa,SAAS,EAAE;QACzC,IAAIA,cAAc,UAAU,OAAOd;QACnC,IAAIa,YAAYE,SAAS,IAAI,CAACf,IAAIe,SAAS,EAAE,OAAOf;QAEpD,MAAME,UAAUC,kBAAkBC,UAAUJ,KAAKF,OAAOC;QAExD,KAAK,MAAM,CAACM,YAAY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MAAME,MAAMJ,gBAAiBG,IAAIlC,UAAU,GAAcA;QACzD,MAAMoC,MAAML,gBAAgBG,IAAIP,KAAK,GAAGM;QACxC,IAAI,CAACE,OAAOC,OAAO,MAAM;QACzB,MAAMzB,KAAKd,kBAAkBuC;QAC7B,MAAM7B,MAAMJ,QAAQkC,GAAG,CAACF;QACxB,IAAI5B,KAAK;YACPA,IAAI+B,IAAI,CAAC3B;QACX,OAAO;YACLR,QAAQoC,GAAG,CAACJ,KAAK;gBAACxB;aAAG;QACvB;IACF;IAEA,OAAOR;AACT"}
|
|
@@ -1,18 +1,29 @@
|
|
|
1
|
-
import type { CollectionConfig,
|
|
1
|
+
import type { BasePayload, CollectionConfig, JsonObject, TypeWithID } from 'payload';
|
|
2
2
|
import z from 'zod';
|
|
3
|
-
export declare const
|
|
4
|
-
export type
|
|
5
|
-
export declare const
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
export declare const documentIdSchema: z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>;
|
|
4
|
+
export type DocumentID = TypeWithID['id'] & z.infer<typeof documentIdSchema>;
|
|
5
|
+
export declare const documentReferenceSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
6
|
+
entity: z.ZodLiteral<"collection">;
|
|
7
|
+
slug: z.ZodString;
|
|
8
|
+
id: z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>;
|
|
9
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
10
|
+
entity: z.ZodLiteral<"global">;
|
|
11
|
+
slug: z.ZodString;
|
|
12
|
+
}, z.core.$strip>], "entity">;
|
|
13
|
+
export type DocumentReference = z.infer<typeof documentReferenceSchema>;
|
|
14
|
+
export declare const isPopulated: <T extends TypeWithID>(relationship: T | DocumentID) => relationship is T;
|
|
15
|
+
export declare function assertPopulated<T extends TypeWithID | null>(docsOrIds: (T | DocumentID)[], errorMessage?: (id: DocumentID) => string): T[];
|
|
16
|
+
export declare function assertPopulated<T extends TypeWithID | null>(docOrId: T | DocumentID, errorMessage?: (id: DocumentID) => string): T;
|
|
8
17
|
export declare const createCollectionConfigFactory: <T extends Record<string, unknown>>(factory: Omit<CollectionConfig, "slug"> | ((options: T & {
|
|
9
|
-
slug:
|
|
18
|
+
slug: string;
|
|
10
19
|
}) => Omit<CollectionConfig, "slug">)) => (options: T & {
|
|
11
|
-
slug:
|
|
20
|
+
slug: string;
|
|
12
21
|
}) => CollectionConfig;
|
|
13
|
-
export type
|
|
14
|
-
export declare function
|
|
15
|
-
export declare const
|
|
22
|
+
export type IdentifiableDocument = TypeWithID['id'] | TypeWithID;
|
|
23
|
+
export declare function isIdentifiableDocument(value: unknown): value is IdentifiableDocument;
|
|
24
|
+
export declare const resolveDocumentID: (entity: IdentifiableDocument) => DocumentID;
|
|
25
|
+
export declare function fetchDocumentByReference(payload: BasePayload, ref: DocumentReference): Promise<JsonObject>;
|
|
26
|
+
export declare function updateDocumentByReference(payload: BasePayload, ref: DocumentReference, data: JsonObject): Promise<JsonObject>;
|
|
16
27
|
export { defineProcedure, type Procedure, type ProcedureBuilder, } from './procedure';
|
|
17
28
|
export { getAdminURL, getApiURL, getServerURL } from './urls';
|
|
18
29
|
export { findFields, uncaughtSwitchCase } from './utils';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/internals/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/internals/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAGhB,UAAU,EACV,UAAU,EACX,MAAM,SAAS,CAAC;AACjB,OAAO,CAAC,MAAM,KAAK,CAAC;AAKpB,eAAO,MAAM,gBAAgB,iDAAoC,CAAC;AAClE,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAE7E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AAC,UAAU,CAAC,CAgBrB;AAED,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,WAAW,EACpB,GAAG,EAAE,iBAAiB,EACtB,IAAI,EAAE,UAAU,uBAiBjB;AAED,OAAO,EACL,eAAe,EACf,KAAK,SAAS,EACd,KAAK,gBAAgB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC"}
|
package/dist/internals/index.js
CHANGED
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
import z from 'zod';
|
|
2
|
+
import { uncaughtSwitchCase } from './utils';
|
|
2
3
|
// MARK: Types
|
|
3
|
-
export const
|
|
4
|
+
export const documentIdSchema = z.union([
|
|
4
5
|
z.number(),
|
|
5
6
|
z.string()
|
|
6
7
|
]);
|
|
8
|
+
export const documentReferenceSchema = z.discriminatedUnion('entity', [
|
|
9
|
+
z.object({
|
|
10
|
+
entity: z.literal('collection'),
|
|
11
|
+
slug: z.string(),
|
|
12
|
+
id: documentIdSchema
|
|
13
|
+
}),
|
|
14
|
+
z.object({
|
|
15
|
+
entity: z.literal('global'),
|
|
16
|
+
slug: z.string()
|
|
17
|
+
})
|
|
18
|
+
]);
|
|
7
19
|
// MARK: Type Guards
|
|
8
20
|
export const isPopulated = (relationship)=>typeof relationship === 'object';
|
|
9
21
|
export function assertPopulated(value, errorMessage = (id)=>`Doc is not populated: [${id}]`) {
|
|
@@ -19,15 +31,49 @@ export const createCollectionConfigFactory = (factory)=>(options)=>({
|
|
|
19
31
|
slug: options.slug,
|
|
20
32
|
...typeof factory === 'function' ? factory(options) : factory
|
|
21
33
|
});
|
|
22
|
-
export function
|
|
34
|
+
export function isIdentifiableDocument(value) {
|
|
23
35
|
if (typeof value === 'string') return true;
|
|
24
36
|
if (typeof value === 'number') return true;
|
|
25
37
|
if (value === null) return false;
|
|
26
38
|
if (typeof value !== 'object') return true;
|
|
27
39
|
if (!('id' in value)) return false;
|
|
28
|
-
return
|
|
40
|
+
return isIdentifiableDocument(value.id);
|
|
41
|
+
}
|
|
42
|
+
export const resolveDocumentID = (entity)=>typeof entity === 'object' ? entity.id : entity;
|
|
43
|
+
export function fetchDocumentByReference(payload, ref) {
|
|
44
|
+
switch(ref.entity){
|
|
45
|
+
case 'collection':
|
|
46
|
+
return payload.findByID({
|
|
47
|
+
collection: ref.slug,
|
|
48
|
+
id: ref.id,
|
|
49
|
+
depth: 0
|
|
50
|
+
});
|
|
51
|
+
case 'global':
|
|
52
|
+
return payload.findGlobal({
|
|
53
|
+
slug: ref.slug,
|
|
54
|
+
depth: 0
|
|
55
|
+
});
|
|
56
|
+
default:
|
|
57
|
+
return uncaughtSwitchCase(ref);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export async function updateDocumentByReference(payload, ref, data) {
|
|
61
|
+
switch(ref.entity){
|
|
62
|
+
case 'collection':
|
|
63
|
+
return payload.update({
|
|
64
|
+
collection: ref.slug,
|
|
65
|
+
id: ref.id,
|
|
66
|
+
data: data
|
|
67
|
+
});
|
|
68
|
+
case 'global':
|
|
69
|
+
return payload.updateGlobal({
|
|
70
|
+
slug: ref.slug,
|
|
71
|
+
data: data
|
|
72
|
+
});
|
|
73
|
+
default:
|
|
74
|
+
return uncaughtSwitchCase(ref);
|
|
75
|
+
}
|
|
29
76
|
}
|
|
30
|
-
export const resolveForeignKey = (entity)=>typeof entity === 'object' ? entity.id : entity;
|
|
31
77
|
export { defineProcedure } from './procedure';
|
|
32
78
|
export { getAdminURL, getApiURL, getServerURL } from './urls';
|
|
33
79
|
export { findFields, uncaughtSwitchCase } from './utils';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/internals/index.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../src/internals/index.ts"],"sourcesContent":["import type {\n BasePayload,\n CollectionConfig,\n CollectionSlug,\n GlobalSlug,\n JsonObject,\n TypeWithID,\n} from 'payload';\nimport z from 'zod';\nimport { uncaughtSwitchCase } from './utils';\n\n// MARK: Types\n\nexport const documentIdSchema = z.union([z.number(), z.string()]);\nexport type DocumentID = TypeWithID['id'] & z.infer<typeof documentIdSchema>;\n\nexport const documentReferenceSchema = z.discriminatedUnion('entity', [\n z.object({\n entity: z.literal('collection'),\n slug: z.string(),\n id: documentIdSchema,\n }),\n z.object({\n entity: z.literal('global'),\n slug: z.string(),\n }),\n]);\n\nexport type DocumentReference = z.infer<typeof documentReferenceSchema>;\n\n// MARK: Type Guards\n\nexport const isPopulated = <T extends TypeWithID>(\n relationship: T | DocumentID,\n): relationship is T => typeof relationship === 'object';\n\nexport function assertPopulated<T extends TypeWithID | null>(\n docsOrIds: (T | DocumentID)[],\n errorMessage?: (id: DocumentID) => string,\n): T[];\nexport function assertPopulated<T extends TypeWithID | null>(\n docOrId: T | DocumentID,\n errorMessage?: (id: DocumentID) => string,\n): T;\nexport function assertPopulated<T extends TypeWithID | null>(\n value: T | DocumentID | (T | DocumentID)[],\n errorMessage = (id: DocumentID) => `Doc is not populated: [${id}]`,\n): T | T[] {\n if (value === null) return value;\n if (Array.isArray(value)) {\n return value.map((item) => assertPopulated(item, errorMessage));\n }\n if (isPopulated(value)) return value;\n throw new Error(errorMessage(value as DocumentID));\n}\n\n// MARK: Utilities\n\nexport const createCollectionConfigFactory =\n <T extends Record<string, unknown>>(\n factory:\n | Omit<CollectionConfig, 'slug'>\n | ((options: T & { slug: string }) => Omit<CollectionConfig, 'slug'>),\n ) =>\n (options: T & { slug: string }): CollectionConfig => ({\n slug: options.slug,\n ...(typeof factory === 'function' ? factory(options) : factory),\n });\n\nexport type IdentifiableDocument = TypeWithID['id'] | TypeWithID;\n\nexport function isIdentifiableDocument(\n value: unknown,\n): value is IdentifiableDocument {\n if (typeof value === 'string') return true;\n if (typeof value === 'number') return true;\n if (value === null) return false;\n if (typeof value !== 'object') return true;\n if (!('id' in value)) return false;\n return isIdentifiableDocument(value.id);\n}\n\nexport const resolveDocumentID = (entity: IdentifiableDocument): DocumentID =>\n typeof entity === 'object' ? entity.id : entity;\n\nexport function fetchDocumentByReference(\n payload: BasePayload,\n ref: DocumentReference,\n): Promise<JsonObject> {\n switch (ref.entity) {\n case 'collection':\n return payload.findByID({\n collection: ref.slug as CollectionSlug,\n id: ref.id,\n depth: 0,\n });\n case 'global':\n return payload.findGlobal({\n slug: ref.slug as GlobalSlug,\n depth: 0,\n });\n default:\n return uncaughtSwitchCase(ref);\n }\n}\n\nexport async function updateDocumentByReference(\n payload: BasePayload,\n ref: DocumentReference,\n data: JsonObject,\n) {\n switch (ref.entity) {\n case 'collection':\n return payload.update({\n collection: ref.slug as CollectionSlug,\n id: ref.id,\n data: data,\n });\n case 'global':\n return payload.updateGlobal({\n slug: ref.slug as GlobalSlug,\n data: data as any,\n });\n default:\n return uncaughtSwitchCase(ref);\n }\n}\n\nexport {\n defineProcedure,\n type Procedure,\n type ProcedureBuilder,\n} from './procedure';\nexport { getAdminURL, getApiURL, getServerURL } from './urls';\nexport { findFields, uncaughtSwitchCase } from './utils';\n"],"names":["z","uncaughtSwitchCase","documentIdSchema","union","number","string","documentReferenceSchema","discriminatedUnion","object","entity","literal","slug","id","isPopulated","relationship","assertPopulated","value","errorMessage","Array","isArray","map","item","Error","createCollectionConfigFactory","factory","options","isIdentifiableDocument","resolveDocumentID","fetchDocumentByReference","payload","ref","findByID","collection","depth","findGlobal","updateDocumentByReference","data","update","updateGlobal","defineProcedure","getAdminURL","getApiURL","getServerURL","findFields"],"mappings":"AAQA,OAAOA,OAAO,MAAM;AACpB,SAASC,kBAAkB,QAAQ,UAAU;AAE7C,cAAc;AAEd,OAAO,MAAMC,mBAAmBF,EAAEG,KAAK,CAAC;IAACH,EAAEI,MAAM;IAAIJ,EAAEK,MAAM;CAAG,EAAE;AAGlE,OAAO,MAAMC,0BAA0BN,EAAEO,kBAAkB,CAAC,UAAU;IACpEP,E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AI,EAAE,MAAM,SAAS,IAAI,GAAG,EAAE,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,GAClD,OAAO,CAAC,OAAO,CAAC,CAAC;CACrB;AAED,MAAM,WAAW,gBAAgB,CAAC,MAAM;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/C,QAAQ,CACN,OAAO,EAAE,CACP,GAAG,EAAE,cAAc,EACnB,GAAG,IAAI,EAAE,MAAM,SAAS,IAAI,GAAG,EAAE,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,KAChD,OAAO,CAAC,OAAO,GAAG,QAAQ,CAAC,GAC/B,QAAQ,CAAC;IACZ,IAAI,CACF,MAAM,EAAE,MAAM,EACd,GAAG,IAAI,EAAE,MAAM,SAAS,IAAI,GAAG,EAAE,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,GAClD,OAAO,CAAC,OAAO,CAAC,CAAC;CACrB;AA4GD,wBAAgB,eAAe,CAC7B,OAAO,SAAS,OAAO,GAAG,SAAS,GAAG,SAAS,EAE/C,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,GAC/B,gBAAgB,CAAC,OAAO,SAAS,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAazE"}
|
|
@@ -58,6 +58,7 @@ function createProcedure(config, inputSchema) {
|
|
|
58
58
|
const queryParams = {};
|
|
59
59
|
if (input) {
|
|
60
60
|
for (const [key, value] of Object.entries(input)){
|
|
61
|
+
if (value == null) continue;
|
|
61
62
|
if (resolvedPath.includes(`:${key}`)) {
|
|
62
63
|
resolvedPath = resolvedPath.replace(`:${key}`, encodeURIComponent(String(value)));
|
|
63
64
|
} else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/internals/procedure.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload';\n\ntype Method = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\n/** Any Zod-like schema with safeParse and inferred output */\ninterface ZodLike<TOutput = unknown> {\n safeParse(\n data: unknown,\n ): { success: true; data: TOutput } | { success: false; error: unknown };\n}\n\ntype InferOutput<T> = T extends ZodLike<infer O> ? O : never;\n\ninterface ProcedureConfig<TSchema extends ZodLike | undefined = undefined> {\n path: `/${string}`;\n method: Method;\n input?: TSchema;\n}\n\nexport interface Procedure<TInput, TOutput> {\n path: `/${string}`;\n method: Method;\n endpoint(\n handler: (\n req: PayloadRequest,\n ...args: TInput extends void ? [] : [input: TInput]\n ) => Promise<unknown | Response>,\n ): Endpoint;\n call(\n apiUrl: string,\n ...args: TInput extends void ? [] : [input: TInput]\n ): Promise<TOutput>;\n}\n\nexport interface ProcedureBuilder<TInput> {\n path: string;\n method: Method;\n returns<TOutput>(): Procedure<TInput, TOutput>;\n endpoint(\n handler: (\n req: PayloadRequest,\n ...args: TInput extends void ? [] : [input: TInput]\n ) => Promise<unknown | Response>,\n ): Endpoint;\n call(\n apiUrl: string,\n ...args: TInput extends void ? [] : [input: TInput]\n ): Promise<unknown>;\n}\n\nfunction wrapOutput(output: unknown): Response {\n if (output instanceof Response) return output;\n return Response.json(output);\n}\n\nfunction createProcedure<TInput, TOutput>(\n config: ProcedureConfig<ZodLike | undefined>,\n inputSchema: ZodLike | undefined,\n): Procedure<TInput, TOutput> {\n return {\n path: config.path,\n method: config.method,\n endpoint(handler) {\n return {\n path: config.path,\n method: config.method,\n handler: async (req) => {\n if (inputSchema) {\n if (config.method === 'get') {\n const routeParams = req.routeParams ?? {};\n const searchParams = req.searchParams\n ? Object.fromEntries(req.searchParams.entries())\n : {};\n const merged = { ...searchParams, ...routeParams };\n const result = inputSchema.safeParse(merged);\n if (!result.success) {\n return Response.json({ error: result.error }, { status: 400 });\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req, result.data);\n return wrapOutput(output);\n }\n\n const { addDataAndFileToRequest } = await import(\n /* webpackIgnore: true */ 'payload'\n );\n await addDataAndFileToRequest(req);\n const result = inputSchema.safeParse(req.data);\n if (!result.success) {\n return Response.json({ error: result.error }, { status: 400 });\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req, result.data);\n return wrapOutput(output);\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req);\n return wrapOutput(output);\n },\n };\n },\n call(apiUrl, ...args) {\n const input = args[0] as Record<string, unknown> | undefined;\n\n if (config.method === 'get') {\n let resolvedPath = config.path;\n const queryParams: Record<string, string> = {};\n\n if (input) {\n for (const [key, value] of Object.entries(input)) {\n if (resolvedPath.includes(`:${key}`)) {\n resolvedPath = resolvedPath.replace(\n `:${key}`,\n encodeURIComponent(String(value)),\n ) as `/${string}`;\n } else {\n queryParams[key] = String(value);\n }\n }\n }\n\n const queryString = new URLSearchParams(queryParams).toString();\n const url = `${apiUrl}${resolvedPath}${queryString ? `?${queryString}` : ''}`;\n\n return fetch(url, {\n method: 'GET',\n credentials: 'include',\n }).then(async (response) => {\n if (!response.ok) {\n throw new Error(\n `Request failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n }) as Promise<TOutput>;\n }\n\n const url = `${apiUrl}${config.path}`;\n return fetch(url, {\n method: config.method.toUpperCase(),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: input ? JSON.stringify(input) : undefined,\n }).then(async (response) => {\n if (!response.ok) {\n throw new Error(\n `Request failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n }) as Promise<TOutput>;\n },\n };\n}\n\nexport function defineProcedure<\n TSchema extends ZodLike | undefined = undefined,\n>(\n config: ProcedureConfig<TSchema>,\n): ProcedureBuilder<TSchema extends ZodLike ? InferOutput<TSchema> : void> {\n type TInput = TSchema extends ZodLike ? InferOutput<TSchema> : undefined;\n const proc = createProcedure<TInput, unknown>(config, config.input);\n\n return {\n path: config.path,\n method: config.method,\n returns<TOutput>(): Procedure<TInput, TOutput> {\n return createProcedure<TInput, TOutput>(config, config.input);\n },\n endpoint: proc.endpoint as unknown as ProcedureBuilder<TInput>['endpoint'],\n call: proc.call as ProcedureBuilder<TInput>['call'],\n };\n}\n"],"names":["wrapOutput","output","Response","json","createProcedure","config","inputSchema","path","method","endpoint","handler","req","routeParams","searchParams","Object","fromEntries","entries","merged","result","safeParse","success","error","status","data","addDataAndFileToRequest","call","apiUrl","args","input","resolvedPath","queryParams","key","value","includes","replace","encodeURIComponent","String","queryString","URLSearchParams","toString","url","fetch","credentials","then","response","ok","Error","statusText","toUpperCase","headers","body","JSON","stringify","undefined","defineProcedure","proc","returns"],"mappings":"AAkDA,SAASA,WAAWC,MAAe;IACjC,IAAIA,kBAAkBC,UAAU,OAAOD;IACvC,OAAOC,SAASC,IAAI,CAACF;AACvB;AAEA,SAASG,gBACPC,MAA4C,EAC5CC,WAAgC;IAEhC,OAAO;QACLC,MAAMF,OAAOE,IAAI;QACjBC,QAAQH,OAAOG,MAAM;QACrBC,UAASC,OAAO;YACd,OAAO;gBACLH,MAAMF,OAAOE,IAAI;gBACjBC,QAAQH,OAAOG,MAAM;gBACrBE,SAAS,OAAOC;oBACd,IAAIL,aAAa;wBACf,IAAID,OAAOG,MAAM,KAAK,OAAO;4BAC3B,MAAMI,cAAcD,IAAIC,WAAW,IAAI,CAAC;4BACxC,MAAMC,eAAeF,IAAIE,YAAY,GACjCC,OAAOC,WAAW,CAACJ,IAAIE,YAAY,CAACG,OAAO,MAC3C,CAAC;4BACL,MAAMC,SAAS;gCAAE,GAAGJ,YAAY;gCAAE,GAAGD,WAAW;4BAAC;4BACjD,MAAMM,SAASZ,YAAYa,SAAS,CAACF;4BACrC,IAAI,CAACC,OAAOE,OAAO,EAAE;gCACnB,OAAOlB,SAASC,IAAI,CAAC;oCAAEkB,OAAOH,OAAOG,KAAK;gCAAC,GAAG;oCAAEC,QAAQ;gCAAI;4BAC9D;4BACA,6DAA6D;4BAC7D,MAAMrB,SAAS,MAAM,AAACS,QAAqBC,KAAKO,OAAOK,IAAI;4BAC3D,OAAOvB,WAAWC;wBACpB;wBAEA,MAAM,EAAEuB,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAC9C,uBAAuB,GAAG;wBAE5B,MAAMA,wBAAwBb;wBAC9B,MAAMO,SAASZ,YAAYa,SAAS,CAACR,IAAIY,IAAI;wBAC7C,IAAI,CAACL,OAAOE,OAAO,EAAE;4BACnB,OAAOlB,SAASC,IAAI,CAAC;gCAAEkB,OAAOH,OAAOG,KAAK;4BAAC,GAAG;gCAAEC,QAAQ;4BAAI;wBAC9D;wBACA,6DAA6D;wBAC7D,MAAMrB,SAAS,MAAM,AAACS,QAAqBC,KAAKO,OAAOK,IAAI;wBAC3D,OAAOvB,WAAWC;oBACpB;oBACA,6DAA6D;oBAC7D,MAAMA,SAAS,MAAM,AAACS,QAAqBC;oBAC3C,OAAOX,WAAWC;gBACpB;YACF;QACF;QACAwB,MAAKC,MAAM,EAAE,GAAGC,IAAI;YAClB,MAAMC,QAAQD,IAAI,CAAC,EAAE;YAErB,IAAItB,OAAOG,MAAM,KAAK,OAAO;gBAC3B,IAAIqB,eAAexB,OAAOE,IAAI;gBAC9B,MAAMuB,cAAsC,CAAC;gBAE7C,IAAIF,OAAO;oBACT,KAAK,MAAM,CAACG,KAAKC,MAAM,IAAIlB,OAAOE,OAAO,CAACY,OAAQ;wBAChD,
|
|
1
|
+
{"version":3,"sources":["../../src/internals/procedure.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload';\n\ntype Method = 'get' | 'post' | 'put' | 'patch' | 'delete';\n\n/** Any Zod-like schema with safeParse and inferred output */\ninterface ZodLike<TOutput = unknown> {\n safeParse(\n data: unknown,\n ): { success: true; data: TOutput } | { success: false; error: unknown };\n}\n\ntype InferOutput<T> = T extends ZodLike<infer O> ? O : never;\n\ninterface ProcedureConfig<TSchema extends ZodLike | undefined = undefined> {\n path: `/${string}`;\n method: Method;\n input?: TSchema;\n}\n\nexport interface Procedure<TInput, TOutput> {\n path: `/${string}`;\n method: Method;\n endpoint(\n handler: (\n req: PayloadRequest,\n ...args: TInput extends void ? [] : [input: TInput]\n ) => Promise<unknown | Response>,\n ): Endpoint;\n call(\n apiUrl: string,\n ...args: TInput extends void ? [] : [input: TInput]\n ): Promise<TOutput>;\n}\n\nexport interface ProcedureBuilder<TInput> {\n path: string;\n method: Method;\n returns<TOutput>(): Procedure<TInput, TOutput>;\n endpoint(\n handler: (\n req: PayloadRequest,\n ...args: TInput extends void ? [] : [input: TInput]\n ) => Promise<unknown | Response>,\n ): Endpoint;\n call(\n apiUrl: string,\n ...args: TInput extends void ? [] : [input: TInput]\n ): Promise<unknown>;\n}\n\nfunction wrapOutput(output: unknown): Response {\n if (output instanceof Response) return output;\n return Response.json(output);\n}\n\nfunction createProcedure<TInput, TOutput>(\n config: ProcedureConfig<ZodLike | undefined>,\n inputSchema: ZodLike | undefined,\n): Procedure<TInput, TOutput> {\n return {\n path: config.path,\n method: config.method,\n endpoint(handler) {\n return {\n path: config.path,\n method: config.method,\n handler: async (req) => {\n if (inputSchema) {\n if (config.method === 'get') {\n const routeParams = req.routeParams ?? {};\n const searchParams = req.searchParams\n ? Object.fromEntries(req.searchParams.entries())\n : {};\n const merged = { ...searchParams, ...routeParams };\n const result = inputSchema.safeParse(merged);\n if (!result.success) {\n return Response.json({ error: result.error }, { status: 400 });\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req, result.data);\n return wrapOutput(output);\n }\n\n const { addDataAndFileToRequest } = await import(\n /* webpackIgnore: true */ 'payload'\n );\n await addDataAndFileToRequest(req);\n const result = inputSchema.safeParse(req.data);\n if (!result.success) {\n return Response.json({ error: result.error }, { status: 400 });\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req, result.data);\n return wrapOutput(output);\n }\n // biome-ignore lint/complexity/noBannedTypes: ugly type cast\n const output = await (handler as Function)(req);\n return wrapOutput(output);\n },\n };\n },\n call(apiUrl, ...args) {\n const input = args[0] as Record<string, unknown> | undefined;\n\n if (config.method === 'get') {\n let resolvedPath = config.path;\n const queryParams: Record<string, string> = {};\n\n if (input) {\n for (const [key, value] of Object.entries(input)) {\n if (value == null) continue;\n if (resolvedPath.includes(`:${key}`)) {\n resolvedPath = resolvedPath.replace(\n `:${key}`,\n encodeURIComponent(String(value)),\n ) as `/${string}`;\n } else {\n queryParams[key] = String(value);\n }\n }\n }\n\n const queryString = new URLSearchParams(queryParams).toString();\n const url = `${apiUrl}${resolvedPath}${queryString ? `?${queryString}` : ''}`;\n\n return fetch(url, {\n method: 'GET',\n credentials: 'include',\n }).then(async (response) => {\n if (!response.ok) {\n throw new Error(\n `Request failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n }) as Promise<TOutput>;\n }\n\n const url = `${apiUrl}${config.path}`;\n return fetch(url, {\n method: config.method.toUpperCase(),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: input ? JSON.stringify(input) : undefined,\n }).then(async (response) => {\n if (!response.ok) {\n throw new Error(\n `Request failed: ${response.status} ${response.statusText}`,\n );\n }\n return response.json();\n }) as Promise<TOutput>;\n },\n };\n}\n\nexport function defineProcedure<\n TSchema extends ZodLike | undefined = undefined,\n>(\n config: ProcedureConfig<TSchema>,\n): ProcedureBuilder<TSchema extends ZodLike ? InferOutput<TSchema> : void> {\n type TInput = TSchema extends ZodLike ? InferOutput<TSchema> : undefined;\n const proc = createProcedure<TInput, unknown>(config, config.input);\n\n return {\n path: config.path,\n method: config.method,\n returns<TOutput>(): Procedure<TInput, TOutput> {\n return createProcedure<TInput, TOutput>(config, config.input);\n },\n endpoint: proc.endpoint as unknown as ProcedureBuilder<TInput>['endpoint'],\n call: proc.call as ProcedureBuilder<TInput>['call'],\n };\n}\n"],"names":["wrapOutput","output","Response","json","createProcedure","config","inputSchema","path","method","endpoint","handler","req","routeParams","searchParams","Object","fromEntries","entries","merged","result","safeParse","success","error","status","data","addDataAndFileToRequest","call","apiUrl","args","input","resolvedPath","queryParams","key","value","includes","replace","encodeURIComponent","String","queryString","URLSearchParams","toString","url","fetch","credentials","then","response","ok","Error","statusText","toUpperCase","headers","body","JSON","stringify","undefined","defineProcedure","proc","returns"],"mappings":"AAkDA,SAASA,WAAWC,MAAe;IACjC,IAAIA,kBAAkBC,UAAU,OAAOD;IACvC,OAAOC,SAASC,IAAI,CAACF;AACvB;AAEA,SAASG,gBACPC,MAA4C,EAC5CC,WAAgC;IAEhC,OAAO;QACLC,MAAMF,OAAOE,IAAI;QACjBC,QAAQH,OAAOG,MAAM;QACrBC,UAASC,OAAO;YACd,OAAO;gBACLH,MAAMF,OAAOE,IAAI;gBACjBC,QAAQH,OAAOG,MAAM;gBACrBE,SAAS,OAAOC;oBACd,IAAIL,aAAa;wBACf,IAAID,OAAOG,MAAM,KAAK,OAAO;4BAC3B,MAAMI,cAAcD,IAAIC,WAAW,IAAI,CAAC;4BACxC,MAAMC,eAAeF,IAAIE,YAAY,GACjCC,OAAOC,WAAW,CAACJ,IAAIE,YAAY,CAACG,OAAO,MAC3C,CAAC;4BACL,MAAMC,SAAS;gCAAE,GAAGJ,YAAY;gCAAE,GAAGD,WAAW;4BAAC;4BACjD,MAAMM,SAASZ,YAAYa,SAAS,CAACF;4BACrC,IAAI,CAACC,OAAOE,OAAO,EAAE;gCACnB,OAAOlB,SAASC,IAAI,CAAC;oCAAEkB,OAAOH,OAAOG,KAAK;gCAAC,GAAG;oCAAEC,QAAQ;gCAAI;4BAC9D;4BACA,6DAA6D;4BAC7D,MAAMrB,SAAS,MAAM,AAACS,QAAqBC,KAAKO,OAAOK,IAAI;4BAC3D,OAAOvB,WAAWC;wBACpB;wBAEA,MAAM,EAAEuB,uBAAuB,EAAE,GAAG,MAAM,MAAM,CAC9C,uBAAuB,GAAG;wBAE5B,MAAMA,wBAAwBb;wBAC9B,MAAMO,SAASZ,YAAYa,SAAS,CAACR,IAAIY,I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sB,SAASG,UAAU,EAAE;oBAE/D;oBACA,OAAOH,SAASzC,IAAI;gBACtB;YACF;YAEA,MAAMqC,MAAM,GAAGd,SAASrB,OAAOE,IAAI,EAAE;YACrC,OAAOkC,MAAMD,KAAK;gBAChBhC,QAAQH,OAAOG,MAAM,CAACwC,WAAW;gBACjCN,aAAa;gBACbO,SAAS;oBAAE,gBAAgB;gBAAmB;gBAC9CC,MAAMtB,QAAQuB,KAAKC,SAAS,CAACxB,SAASyB;YACxC,GAAGV,IAAI,CAAC,OAAOC;gBACb,IAAI,CAACA,SAASC,EAAE,EAAE;oBAChB,MAAM,IAAIC,MACR,CAAC,gBAAgB,EAAEF,SAAStB,MAAM,CAAC,CAAC,EAAEsB,SAASG,UAAU,EAAE;gBAE/D;gBACA,OAAOH,SAASzC,IAAI;YACtB;QACF;IACF;AACF;AAEA,OAAO,SAASmD,gBAGdjD,MAAgC;IAGhC,MAAMkD,OAAOnD,gBAAiCC,QAAQA,OAAOuB,KAAK;IAElE,OAAO;QACLrB,MAAMF,OAAOE,IAAI;QACjBC,QAAQH,OAAOG,MAAM;QACrBgD;YACE,OAAOpD,gBAAiCC,QAAQA,OAAOuB,KAAK;QAC9D;QACAnB,UAAU8C,KAAK9C,QAAQ;QACvBgB,MAAM8B,KAAK9B,IAAI;IACjB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "payload-smart-deletion",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "Payload CMS plugin that adds PostgreSQL-style referential actions (cascade, set_null, restrict) to relationship fields.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"payload"
|
|
@@ -45,14 +45,14 @@
|
|
|
45
45
|
"access": "public"
|
|
46
46
|
},
|
|
47
47
|
"scripts": {
|
|
48
|
-
"prebuild": "rm -f src/internals 2>/dev/null; pnpm
|
|
48
|
+
"prebuild": "rm -f src/internals 2>/dev/null; pnpm check:types",
|
|
49
49
|
"build": "plugin-build",
|
|
50
|
+
"check:types": "tsc --noEmit",
|
|
50
51
|
"clean": "rm -rf dist && rm -rf node_modules",
|
|
51
52
|
"dev": "plugin-build --watch",
|
|
52
53
|
"lint": "biome check .",
|
|
53
54
|
"lint:fix": "biome check --write .",
|
|
54
55
|
"test": "vitest run --passWithNoTests",
|
|
55
|
-
"test:watch": "vitest"
|
|
56
|
-
"typecheck": "tsc --noEmit"
|
|
56
|
+
"test:watch": "vitest"
|
|
57
57
|
}
|
|
58
58
|
}
|