@voyantjs/plugin-payload-cms 0.1.0
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/LICENSE +109 -0
- package/README.md +42 -0
- package/dist/src/client.d.ts +48 -0
- package/dist/src/client.d.ts.map +1 -0
- package/dist/src/client.js +79 -0
- package/dist/src/index.d.ts +6 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +2 -0
- package/dist/src/plugin.d.ts +59 -0
- package/dist/src/plugin.d.ts.map +1 -0
- package/dist/src/plugin.js +85 -0
- package/dist/src/types.d.ts +31 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/types.js +1 -0
- package/dist/tests/unit/client.test.d.ts +2 -0
- package/dist/tests/unit/client.test.d.ts.map +1 -0
- package/dist/tests/unit/client.test.js +192 -0
- package/dist/tests/unit/plugin.test.d.ts +2 -0
- package/dist/tests/unit/plugin.test.d.ts.map +1 -0
- package/dist/tests/unit/plugin.test.js +164 -0
- package/package.json +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, Apache 2.0 Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-Apache-2.0
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 PixelMakers Studio SRL
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly
|
|
28
|
+
display and redistribute the Software for any Permitted Purpose identified
|
|
29
|
+
below.
|
|
30
|
+
|
|
31
|
+
### Permitted Purpose
|
|
32
|
+
|
|
33
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing
|
|
34
|
+
Use means making the Software available to others in a commercial product or
|
|
35
|
+
service that:
|
|
36
|
+
|
|
37
|
+
1. substitutes for the Software;
|
|
38
|
+
|
|
39
|
+
2. substitutes for any other product or service we offer using the Software
|
|
40
|
+
that exists as of the date we make the Software available; or
|
|
41
|
+
|
|
42
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
43
|
+
|
|
44
|
+
Permitted Purposes specifically include using the Software:
|
|
45
|
+
|
|
46
|
+
1. for your internal use and access;
|
|
47
|
+
|
|
48
|
+
2. for non-commercial education;
|
|
49
|
+
|
|
50
|
+
3. for non-commercial research; and
|
|
51
|
+
|
|
52
|
+
4. in connection with professional services that you provide to a licensee
|
|
53
|
+
using the Software in accordance with these Terms and Conditions.
|
|
54
|
+
|
|
55
|
+
### Patents
|
|
56
|
+
|
|
57
|
+
To the extent your use for a Permitted Purpose would necessarily infringe
|
|
58
|
+
our patents, the license grant above includes a license under our patents.
|
|
59
|
+
If you make a claim against any party that the Software infringes or
|
|
60
|
+
contributes to the infringement of any patent, then your patent license to
|
|
61
|
+
the Software ends immediately.
|
|
62
|
+
|
|
63
|
+
### Redistribution
|
|
64
|
+
|
|
65
|
+
The Terms and Conditions apply to all copies, modifications and derivatives
|
|
66
|
+
of the Software.
|
|
67
|
+
|
|
68
|
+
If you redistribute any copies, modifications or derivatives of the
|
|
69
|
+
Software, you must include a copy of or a link to these Terms and Conditions
|
|
70
|
+
and not remove any copyright notices provided in or with the Software.
|
|
71
|
+
|
|
72
|
+
### Disclaimer
|
|
73
|
+
|
|
74
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS
|
|
75
|
+
OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A
|
|
76
|
+
PARTICULAR PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
77
|
+
|
|
78
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO
|
|
79
|
+
THE SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
|
|
80
|
+
DAMAGES, EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
81
|
+
|
|
82
|
+
### Trademarks
|
|
83
|
+
|
|
84
|
+
Except for displaying the License Details and identifying us as the origin
|
|
85
|
+
of the Software, you have no right under these Terms and Conditions to use
|
|
86
|
+
our trademarks, trade names, service marks or product names.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Grant of Future License
|
|
91
|
+
|
|
92
|
+
We hereby irrevocably grant you an additional license to use the Software
|
|
93
|
+
under the Apache License, Version 2.0 that is effective on the second
|
|
94
|
+
anniversary of the date we make the Software available. On or after that
|
|
95
|
+
date, you may use the Software under the Apache License, Version 2.0, in
|
|
96
|
+
which case the following will apply:
|
|
97
|
+
|
|
98
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
|
99
|
+
use this file except in compliance with the License.
|
|
100
|
+
|
|
101
|
+
You may obtain a copy of the License at
|
|
102
|
+
|
|
103
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
104
|
+
|
|
105
|
+
Unless required by applicable law or agreed to in writing, software
|
|
106
|
+
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
|
107
|
+
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
|
108
|
+
License for the specific language governing permissions and limitations
|
|
109
|
+
under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# @voyantjs/plugin-payload-cms
|
|
2
|
+
|
|
3
|
+
Payload CMS sync plugin for Voyant. Subscribes to module events and mirrors documents into a Payload collection keyed by a `voyantId` field.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @voyantjs/plugin-payload-cms
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { payloadCmsPlugin } from "@voyantjs/plugin-payload-cms"
|
|
15
|
+
import { createApp } from "@voyantjs/hono"
|
|
16
|
+
|
|
17
|
+
const app = createApp({
|
|
18
|
+
plugins: [
|
|
19
|
+
payloadCmsPlugin({
|
|
20
|
+
apiUrl: "https://cms.example.com/api",
|
|
21
|
+
apiKey: env.PAYLOAD_API_KEY,
|
|
22
|
+
collection: "products",
|
|
23
|
+
// optional: events, mapEvent, logger, apiKeyAuthScheme
|
|
24
|
+
}),
|
|
25
|
+
],
|
|
26
|
+
})
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
By default the plugin wires up 3 subscribers (`product.created`, `product.updated`, `product.deleted`) that upsert/delete documents keyed by `voyantId`. All error handling is fire-and-forget per the EventBus contract.
|
|
30
|
+
|
|
31
|
+
## Exports
|
|
32
|
+
|
|
33
|
+
| Entry | Description |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| `.` | Barrel re-exports |
|
|
36
|
+
| `./plugin` | `payloadCmsPlugin(options)` |
|
|
37
|
+
| `./client` | `createPayloadClient` — `upsertByVoyantId`, `deleteByVoyantId`, `findByVoyantId` |
|
|
38
|
+
| `./types` | Plugin option types |
|
|
39
|
+
|
|
40
|
+
## License
|
|
41
|
+
|
|
42
|
+
FSL-1.1-Apache-2.0
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { PayloadDocBody, PayloadFetch } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Options for {@link createPayloadClient}.
|
|
4
|
+
*/
|
|
5
|
+
export interface PayloadClientOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Base URL of the Payload REST API including `/api` suffix.
|
|
8
|
+
* Example: `"https://cms.example.com/api"`.
|
|
9
|
+
*/
|
|
10
|
+
apiUrl: string;
|
|
11
|
+
/** Payload API key. Sent as `Authorization: ${apiKeyHeader} API-Key ${apiKey}`. */
|
|
12
|
+
apiKey: string;
|
|
13
|
+
/**
|
|
14
|
+
* Field on the Payload collection that stores the Voyant record's ID.
|
|
15
|
+
* Defaults to `"voyantId"`. The Payload collection must declare this
|
|
16
|
+
* field (unique recommended).
|
|
17
|
+
*/
|
|
18
|
+
voyantIdField?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Header used to carry the API key. Defaults to `"users API-Key"` which
|
|
21
|
+
* matches Payload's default `users` auth collection. Override if your
|
|
22
|
+
* Payload deployment uses a different auth collection.
|
|
23
|
+
*/
|
|
24
|
+
apiKeyAuthScheme?: string;
|
|
25
|
+
/** Override `fetch` (e.g. in tests). Defaults to global `fetch`. */
|
|
26
|
+
fetch?: PayloadFetch;
|
|
27
|
+
}
|
|
28
|
+
export interface PayloadClient {
|
|
29
|
+
/**
|
|
30
|
+
* Create or update a document whose {@link PayloadClientOptions.voyantIdField}
|
|
31
|
+
* equals `voyantId`.
|
|
32
|
+
*/
|
|
33
|
+
upsertByVoyantId(collection: string, voyantId: string, body: PayloadDocBody): Promise<{
|
|
34
|
+
id: string;
|
|
35
|
+
created: boolean;
|
|
36
|
+
}>;
|
|
37
|
+
/**
|
|
38
|
+
* Delete a document whose `voyantId` field equals the given value. Returns
|
|
39
|
+
* `false` if no matching document was found.
|
|
40
|
+
*/
|
|
41
|
+
deleteByVoyantId(collection: string, voyantId: string): Promise<boolean>;
|
|
42
|
+
/** Find at most one document whose `voyantId` field equals the given value. */
|
|
43
|
+
findByVoyantId(collection: string, voyantId: string): Promise<{
|
|
44
|
+
id: string;
|
|
45
|
+
} | null>;
|
|
46
|
+
}
|
|
47
|
+
export declare function createPayloadClient(options: PayloadClientOptions): PayloadClient;
|
|
48
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE9D;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAA;IACd,mFAAmF;IACnF,MAAM,EAAE,MAAM,CAAA;IACd;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,oEAAoE;IACpE,KAAK,CAAC,EAAE,YAAY,CAAA;CACrB;AAUD,MAAM,WAAW,aAAa;IAC5B;;;OAGG;IACH,gBAAgB,CACd,UAAU,EAAE,MAAM,EAClB,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,cAAc,GACnB,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAA;IAC5C;;;OAGG;IACH,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IACxE,+EAA+E;IAC/E,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CAAA;CACrF;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,oBAAoB,GAAG,aAAa,CA+FhF"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
export function createPayloadClient(options) {
|
|
2
|
+
const voyantIdField = options.voyantIdField ?? "voyantId";
|
|
3
|
+
const authScheme = options.apiKeyAuthScheme ?? "users API-Key";
|
|
4
|
+
const apiUrl = options.apiUrl.replace(/\/$/, "");
|
|
5
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
6
|
+
function headers() {
|
|
7
|
+
return {
|
|
8
|
+
Authorization: `${authScheme} ${options.apiKey}`,
|
|
9
|
+
"Content-Type": "application/json",
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
async function request(method, path, body) {
|
|
13
|
+
if (!fetchImpl) {
|
|
14
|
+
throw new Error("Payload client requires a fetch implementation");
|
|
15
|
+
}
|
|
16
|
+
const init = {
|
|
17
|
+
method,
|
|
18
|
+
headers: headers(),
|
|
19
|
+
};
|
|
20
|
+
if (body !== undefined)
|
|
21
|
+
init.body = JSON.stringify(body);
|
|
22
|
+
const response = await fetchImpl(`${apiUrl}${path}`, init);
|
|
23
|
+
// Payload sends JSON for all 2xx/4xx; pull both eagerly.
|
|
24
|
+
let text = "";
|
|
25
|
+
let json = null;
|
|
26
|
+
try {
|
|
27
|
+
text = await response.text();
|
|
28
|
+
json = text ? JSON.parse(text) : null;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
// leave json as null, surface text
|
|
32
|
+
}
|
|
33
|
+
return { ok: response.ok, status: response.status, json, text };
|
|
34
|
+
}
|
|
35
|
+
async function findByVoyantId(collection, voyantId) {
|
|
36
|
+
const query = `where[${encodeURIComponent(voyantIdField)}][equals]=${encodeURIComponent(voyantId)}&limit=1&depth=0`;
|
|
37
|
+
const res = await request("GET", `/${collection}?${query}`);
|
|
38
|
+
if (!res.ok) {
|
|
39
|
+
throw new Error(`Payload findByVoyantId(${collection}) failed (${res.status}): ${res.text}`);
|
|
40
|
+
}
|
|
41
|
+
const body = (res.json ?? {});
|
|
42
|
+
const first = body.docs?.[0];
|
|
43
|
+
if (!first)
|
|
44
|
+
return null;
|
|
45
|
+
return { id: first.id };
|
|
46
|
+
}
|
|
47
|
+
async function upsertByVoyantId(collection, voyantId, body) {
|
|
48
|
+
const existing = await findByVoyantId(collection, voyantId);
|
|
49
|
+
const fullBody = { ...body, [voyantIdField]: voyantId };
|
|
50
|
+
if (existing) {
|
|
51
|
+
const res = await request("PATCH", `/${collection}/${existing.id}`, fullBody);
|
|
52
|
+
if (!res.ok) {
|
|
53
|
+
throw new Error(`Payload update(${collection}/${existing.id}) failed (${res.status}): ${res.text}`);
|
|
54
|
+
}
|
|
55
|
+
return { id: existing.id, created: false };
|
|
56
|
+
}
|
|
57
|
+
const res = await request("POST", `/${collection}`, fullBody);
|
|
58
|
+
if (!res.ok) {
|
|
59
|
+
throw new Error(`Payload create(${collection}) failed (${res.status}): ${res.text}`);
|
|
60
|
+
}
|
|
61
|
+
const json = (res.json ?? {});
|
|
62
|
+
const id = json.doc?.id ?? json.id;
|
|
63
|
+
if (!id) {
|
|
64
|
+
throw new Error(`Payload create(${collection}) response missing id`);
|
|
65
|
+
}
|
|
66
|
+
return { id, created: true };
|
|
67
|
+
}
|
|
68
|
+
async function deleteByVoyantId(collection, voyantId) {
|
|
69
|
+
const existing = await findByVoyantId(collection, voyantId);
|
|
70
|
+
if (!existing)
|
|
71
|
+
return false;
|
|
72
|
+
const res = await request("DELETE", `/${collection}/${existing.id}`);
|
|
73
|
+
if (!res.ok && res.status !== 404) {
|
|
74
|
+
throw new Error(`Payload delete(${collection}/${existing.id}) failed (${res.status}): ${res.text}`);
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
return { upsertByVoyantId, deleteByVoyantId, findByVoyantId };
|
|
79
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type { PayloadClient, PayloadClientOptions } from "./client.js";
|
|
2
|
+
export { createPayloadClient } from "./client.js";
|
|
3
|
+
export type { PayloadCmsPluginOptions, PayloadLogger, PayloadMapFn, PayloadSyncEventNames, } from "./plugin.js";
|
|
4
|
+
export { payloadCmsPlugin } from "./plugin.js";
|
|
5
|
+
export type { PayloadDocBody, PayloadFetch, VoyantEntityEvent } from "./types.js";
|
|
6
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AACtE,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AACjD,YAAY,EACV,uBAAuB,EACvB,aAAa,EACb,YAAY,EACZ,qBAAqB,GACtB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAC9C,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { Plugin } from "@voyantjs/core";
|
|
2
|
+
import { type PayloadClientOptions } from "./client.js";
|
|
3
|
+
import type { PayloadDocBody, VoyantEntityEvent } from "./types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Event names the plugin subscribes to. Defaults match the `<resource>.<pastTenseAction>`
|
|
6
|
+
* naming convention documented by the EventBus contract.
|
|
7
|
+
*/
|
|
8
|
+
export interface PayloadSyncEventNames {
|
|
9
|
+
created?: string;
|
|
10
|
+
updated?: string;
|
|
11
|
+
deleted?: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Mapper from a Voyant event payload (assumed to carry at least `id: string`)
|
|
15
|
+
* to a Payload document body. The `voyantId` field is injected automatically
|
|
16
|
+
* by the client — do not set it here.
|
|
17
|
+
*/
|
|
18
|
+
export type PayloadMapFn = (event: VoyantEntityEvent) => PayloadDocBody;
|
|
19
|
+
/**
|
|
20
|
+
* Logger shape used to surface plugin errors without coupling to any specific
|
|
21
|
+
* runtime. Defaults to `console`.
|
|
22
|
+
*/
|
|
23
|
+
export interface PayloadLogger {
|
|
24
|
+
error: (message: string, meta?: unknown) => void;
|
|
25
|
+
info?: (message: string, meta?: unknown) => void;
|
|
26
|
+
}
|
|
27
|
+
export interface PayloadCmsPluginOptions extends PayloadClientOptions {
|
|
28
|
+
/**
|
|
29
|
+
* Payload collection slug to sync Voyant records into (e.g. "products").
|
|
30
|
+
*/
|
|
31
|
+
collection: string;
|
|
32
|
+
/**
|
|
33
|
+
* Event names this plugin subscribes to. Defaults to
|
|
34
|
+
* `product.created` / `product.updated` / `product.deleted`.
|
|
35
|
+
*/
|
|
36
|
+
events?: PayloadSyncEventNames;
|
|
37
|
+
/**
|
|
38
|
+
* Map a Voyant event payload into a Payload document body. Defaults to
|
|
39
|
+
* passing through every property except `id` (which becomes `voyantId`).
|
|
40
|
+
*/
|
|
41
|
+
mapEvent?: PayloadMapFn;
|
|
42
|
+
/** Override logger. Defaults to `console`. */
|
|
43
|
+
logger?: PayloadLogger;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Build a Voyant {@link Plugin} that pushes event payloads to a Payload
|
|
47
|
+
* collection as documents, keyed by `voyantId` for idempotent upserts.
|
|
48
|
+
*
|
|
49
|
+
* The plugin subscribes to three events (configurable via
|
|
50
|
+
* {@link PayloadCmsPluginOptions.events}):
|
|
51
|
+
* - `product.created` → upsert document
|
|
52
|
+
* - `product.updated` → upsert document
|
|
53
|
+
* - `product.deleted` → delete document by `voyantId`
|
|
54
|
+
*
|
|
55
|
+
* Errors are caught and logged — subscribers are fire-and-forget per the
|
|
56
|
+
* EventBus contract, so a Payload outage never blocks the emitter.
|
|
57
|
+
*/
|
|
58
|
+
export declare function payloadCmsPlugin(options: PayloadCmsPluginOptions): Plugin;
|
|
59
|
+
//# sourceMappingURL=plugin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAc,MAAM,gBAAgB,CAAA;AAExD,OAAO,EAAuB,KAAK,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAC5E,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAEnE;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,cAAc,CAAA;AAEvE;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;IAChD,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;CACjD;AAED,MAAM,WAAW,uBAAwB,SAAQ,oBAAoB;IACnE;;OAEG;IACH,UAAU,EAAE,MAAM,CAAA;IAClB;;;OAGG;IACH,MAAM,CAAC,EAAE,qBAAqB,CAAA;IAC9B;;;OAGG;IACH,QAAQ,CAAC,EAAE,YAAY,CAAA;IACvB,8CAA8C;IAC9C,MAAM,CAAC,EAAE,aAAa,CAAA;CACvB;AAcD;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,MAAM,CA+DzE"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { createPayloadClient } from "./client.js";
|
|
2
|
+
function defaultMapEvent(event) {
|
|
3
|
+
const { id: _id, ...rest } = event;
|
|
4
|
+
return rest;
|
|
5
|
+
}
|
|
6
|
+
function coerceEvent(data) {
|
|
7
|
+
if (data == null || typeof data !== "object")
|
|
8
|
+
return null;
|
|
9
|
+
const maybe = data;
|
|
10
|
+
if (typeof maybe.id !== "string")
|
|
11
|
+
return null;
|
|
12
|
+
return maybe;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Build a Voyant {@link Plugin} that pushes event payloads to a Payload
|
|
16
|
+
* collection as documents, keyed by `voyantId` for idempotent upserts.
|
|
17
|
+
*
|
|
18
|
+
* The plugin subscribes to three events (configurable via
|
|
19
|
+
* {@link PayloadCmsPluginOptions.events}):
|
|
20
|
+
* - `product.created` → upsert document
|
|
21
|
+
* - `product.updated` → upsert document
|
|
22
|
+
* - `product.deleted` → delete document by `voyantId`
|
|
23
|
+
*
|
|
24
|
+
* Errors are caught and logged — subscribers are fire-and-forget per the
|
|
25
|
+
* EventBus contract, so a Payload outage never blocks the emitter.
|
|
26
|
+
*/
|
|
27
|
+
export function payloadCmsPlugin(options) {
|
|
28
|
+
const client = createPayloadClient(options);
|
|
29
|
+
const mapEvent = options.mapEvent ?? defaultMapEvent;
|
|
30
|
+
const logger = options.logger ?? console;
|
|
31
|
+
const eventNames = {
|
|
32
|
+
created: options.events?.created ?? "product.created",
|
|
33
|
+
updated: options.events?.updated ?? "product.updated",
|
|
34
|
+
deleted: options.events?.deleted ?? "product.deleted",
|
|
35
|
+
};
|
|
36
|
+
const subscribers = [
|
|
37
|
+
{
|
|
38
|
+
event: eventNames.created,
|
|
39
|
+
handler: async (data) => {
|
|
40
|
+
const event = coerceEvent(data);
|
|
41
|
+
if (!event)
|
|
42
|
+
return;
|
|
43
|
+
try {
|
|
44
|
+
await client.upsertByVoyantId(options.collection, event.id, mapEvent(event));
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
logger.error(`[payload-cms] upsert on "${eventNames.created}" failed for ${event.id}`, err);
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
event: eventNames.updated,
|
|
53
|
+
handler: async (data) => {
|
|
54
|
+
const event = coerceEvent(data);
|
|
55
|
+
if (!event)
|
|
56
|
+
return;
|
|
57
|
+
try {
|
|
58
|
+
await client.upsertByVoyantId(options.collection, event.id, mapEvent(event));
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
logger.error(`[payload-cms] upsert on "${eventNames.updated}" failed for ${event.id}`, err);
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
event: eventNames.deleted,
|
|
67
|
+
handler: async (data) => {
|
|
68
|
+
const event = coerceEvent(data);
|
|
69
|
+
if (!event)
|
|
70
|
+
return;
|
|
71
|
+
try {
|
|
72
|
+
await client.deleteByVoyantId(options.collection, event.id);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
logger.error(`[payload-cms] delete on "${eventNames.deleted}" failed for ${event.id}`, err);
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
];
|
|
80
|
+
return {
|
|
81
|
+
name: "payload-cms",
|
|
82
|
+
version: "0.1.0",
|
|
83
|
+
subscribers,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal shape Voyant events expose when carrying a record identifier.
|
|
3
|
+
* The plugin accepts anything with `id: string`; everything else is passed
|
|
4
|
+
* through to `mapProduct` untouched.
|
|
5
|
+
*/
|
|
6
|
+
export interface VoyantEntityEvent {
|
|
7
|
+
id: string;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A Payload document, as a bag of properties. Payload always assigns its own
|
|
12
|
+
* `id`; the plugin additionally sets a `voyantId` (configurable) for
|
|
13
|
+
* idempotent lookups.
|
|
14
|
+
*/
|
|
15
|
+
export type PayloadDocBody = Record<string, unknown>;
|
|
16
|
+
/**
|
|
17
|
+
* Minimal `fetch` shape the Payload client depends on. Works with the global
|
|
18
|
+
* `fetch` in Node 18+ / Cloudflare Workers / browsers, and is trivially
|
|
19
|
+
* stubbable in tests.
|
|
20
|
+
*/
|
|
21
|
+
export type PayloadFetch = (input: string, init: {
|
|
22
|
+
method: string;
|
|
23
|
+
headers: Record<string, string>;
|
|
24
|
+
body?: string;
|
|
25
|
+
}) => Promise<{
|
|
26
|
+
ok: boolean;
|
|
27
|
+
status: number;
|
|
28
|
+
json: () => Promise<unknown>;
|
|
29
|
+
text: () => Promise<string>;
|
|
30
|
+
}>;
|
|
31
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAA;IACV,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAED;;;;GAIG;AACH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAEpD;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE;IACJ,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,KACE,OAAO,CAAC;IACX,EAAE,EAAE,OAAO,CAAA;IACX,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;IAC5B,IAAI,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAA;CAC5B,CAAC,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.test.d.ts","sourceRoot":"","sources":["../../../tests/unit/client.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { createPayloadClient } from "../../src/client.js";
|
|
3
|
+
function jsonResponse(status, body) {
|
|
4
|
+
const text = JSON.stringify(body);
|
|
5
|
+
return {
|
|
6
|
+
ok: status >= 200 && status < 300,
|
|
7
|
+
status,
|
|
8
|
+
json: async () => JSON.parse(text),
|
|
9
|
+
text: async () => text,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function textResponse(status, text) {
|
|
13
|
+
return {
|
|
14
|
+
ok: status >= 200 && status < 300,
|
|
15
|
+
status,
|
|
16
|
+
json: async () => {
|
|
17
|
+
throw new Error("not json");
|
|
18
|
+
},
|
|
19
|
+
text: async () => text,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const baseOptions = {
|
|
23
|
+
apiUrl: "https://cms.example.com/api",
|
|
24
|
+
apiKey: "test-key",
|
|
25
|
+
};
|
|
26
|
+
describe("createPayloadClient.findByVoyantId", () => {
|
|
27
|
+
it("returns the first matching doc", async () => {
|
|
28
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { docs: [{ id: "pl_1", name: "a" }], totalDocs: 1 }));
|
|
29
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
30
|
+
const result = await client.findByVoyantId("products", "prod_xyz");
|
|
31
|
+
expect(result).toEqual({ id: "pl_1" });
|
|
32
|
+
const [url, init] = fetchMock.mock.calls[0];
|
|
33
|
+
expect(url).toContain("https://cms.example.com/api/products?");
|
|
34
|
+
expect(url).toContain("where[voyantId][equals]=prod_xyz");
|
|
35
|
+
expect(url).toContain("limit=1");
|
|
36
|
+
expect(init.method).toBe("GET");
|
|
37
|
+
expect(init.headers.Authorization).toBe("users API-Key test-key");
|
|
38
|
+
});
|
|
39
|
+
it("returns null when no docs match", async () => {
|
|
40
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { docs: [], totalDocs: 0 }));
|
|
41
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
42
|
+
expect(await client.findByVoyantId("products", "missing")).toBeNull();
|
|
43
|
+
});
|
|
44
|
+
it("respects a custom voyantIdField", async () => {
|
|
45
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { docs: [] }));
|
|
46
|
+
const client = createPayloadClient({
|
|
47
|
+
...baseOptions,
|
|
48
|
+
voyantIdField: "externalId",
|
|
49
|
+
fetch: fetchMock,
|
|
50
|
+
});
|
|
51
|
+
await client.findByVoyantId("products", "prod_1");
|
|
52
|
+
const [url] = fetchMock.mock.calls[0];
|
|
53
|
+
expect(url).toContain("where[externalId][equals]=prod_1");
|
|
54
|
+
});
|
|
55
|
+
it("respects a custom apiKeyAuthScheme", async () => {
|
|
56
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { docs: [] }));
|
|
57
|
+
const client = createPayloadClient({
|
|
58
|
+
...baseOptions,
|
|
59
|
+
apiKeyAuthScheme: "admins API-Key",
|
|
60
|
+
fetch: fetchMock,
|
|
61
|
+
});
|
|
62
|
+
await client.findByVoyantId("products", "prod_1");
|
|
63
|
+
const [, init] = fetchMock.mock.calls[0];
|
|
64
|
+
expect(init.headers.Authorization).toBe("admins API-Key test-key");
|
|
65
|
+
});
|
|
66
|
+
it("strips trailing slash from apiUrl", async () => {
|
|
67
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { docs: [] }));
|
|
68
|
+
const client = createPayloadClient({
|
|
69
|
+
...baseOptions,
|
|
70
|
+
apiUrl: "https://cms.example.com/api/",
|
|
71
|
+
fetch: fetchMock,
|
|
72
|
+
});
|
|
73
|
+
await client.findByVoyantId("products", "x");
|
|
74
|
+
const [url] = fetchMock.mock.calls[0];
|
|
75
|
+
expect(url.startsWith("https://cms.example.com/api/products?")).toBe(true);
|
|
76
|
+
});
|
|
77
|
+
it("throws on non-2xx response", async () => {
|
|
78
|
+
const fetchMock = vi.fn(async () => textResponse(500, "boom"));
|
|
79
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
80
|
+
await expect(client.findByVoyantId("products", "x")).rejects.toThrow(/Payload findByVoyantId\(products\) failed \(500\)/);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
describe("createPayloadClient.upsertByVoyantId", () => {
|
|
84
|
+
it("creates a new doc when none exists", async () => {
|
|
85
|
+
const fetchMock = vi
|
|
86
|
+
.fn()
|
|
87
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [] }))
|
|
88
|
+
.mockResolvedValueOnce(jsonResponse(201, { doc: { id: "pl_new", name: "X" } }));
|
|
89
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
90
|
+
const result = await client.upsertByVoyantId("products", "prod_1", { name: "X" });
|
|
91
|
+
expect(result).toEqual({ id: "pl_new", created: true });
|
|
92
|
+
const createCall = fetchMock.mock.calls[1];
|
|
93
|
+
expect(createCall[0]).toBe("https://cms.example.com/api/products");
|
|
94
|
+
expect(createCall[1].method).toBe("POST");
|
|
95
|
+
const body = JSON.parse(createCall[1].body ?? "{}");
|
|
96
|
+
expect(body).toEqual({ name: "X", voyantId: "prod_1" });
|
|
97
|
+
});
|
|
98
|
+
it("updates an existing doc when found", async () => {
|
|
99
|
+
const fetchMock = vi
|
|
100
|
+
.fn()
|
|
101
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [{ id: "pl_existing" }] }))
|
|
102
|
+
.mockResolvedValueOnce(jsonResponse(200, { doc: { id: "pl_existing", name: "Y" } }));
|
|
103
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
104
|
+
const result = await client.upsertByVoyantId("products", "prod_1", { name: "Y" });
|
|
105
|
+
expect(result).toEqual({ id: "pl_existing", created: false });
|
|
106
|
+
const patchCall = fetchMock.mock.calls[1];
|
|
107
|
+
expect(patchCall[0]).toBe("https://cms.example.com/api/products/pl_existing");
|
|
108
|
+
expect(patchCall[1].method).toBe("PATCH");
|
|
109
|
+
});
|
|
110
|
+
it("accepts a top-level id in create response", async () => {
|
|
111
|
+
const fetchMock = vi
|
|
112
|
+
.fn()
|
|
113
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [] }))
|
|
114
|
+
.mockResolvedValueOnce(jsonResponse(201, { id: "pl_top" }));
|
|
115
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
116
|
+
const result = await client.upsertByVoyantId("products", "prod_1", {});
|
|
117
|
+
expect(result.id).toBe("pl_top");
|
|
118
|
+
});
|
|
119
|
+
it("throws if create response has no id", async () => {
|
|
120
|
+
const fetchMock = vi
|
|
121
|
+
.fn()
|
|
122
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [] }))
|
|
123
|
+
.mockResolvedValueOnce(jsonResponse(201, {}));
|
|
124
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
125
|
+
await expect(client.upsertByVoyantId("products", "p", {})).rejects.toThrow(/response missing id/);
|
|
126
|
+
});
|
|
127
|
+
it("throws on create error", async () => {
|
|
128
|
+
const fetchMock = vi
|
|
129
|
+
.fn()
|
|
130
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [] }))
|
|
131
|
+
.mockResolvedValueOnce(textResponse(400, "bad request"));
|
|
132
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
133
|
+
await expect(client.upsertByVoyantId("products", "p", {})).rejects.toThrow(/Payload create\(products\) failed \(400\)/);
|
|
134
|
+
});
|
|
135
|
+
it("throws on update error", async () => {
|
|
136
|
+
const fetchMock = vi
|
|
137
|
+
.fn()
|
|
138
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [{ id: "pl_1" }] }))
|
|
139
|
+
.mockResolvedValueOnce(textResponse(409, "conflict"));
|
|
140
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
141
|
+
await expect(client.upsertByVoyantId("products", "p", {})).rejects.toThrow(/Payload update\(products\/pl_1\) failed \(409\)/);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
describe("createPayloadClient.deleteByVoyantId", () => {
|
|
145
|
+
it("deletes when doc exists", async () => {
|
|
146
|
+
const fetchMock = vi
|
|
147
|
+
.fn()
|
|
148
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [{ id: "pl_1" }] }))
|
|
149
|
+
.mockResolvedValueOnce(jsonResponse(200, {}));
|
|
150
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
151
|
+
expect(await client.deleteByVoyantId("products", "p")).toBe(true);
|
|
152
|
+
const deleteCall = fetchMock.mock.calls[1];
|
|
153
|
+
expect(deleteCall[0]).toBe("https://cms.example.com/api/products/pl_1");
|
|
154
|
+
expect(deleteCall[1].method).toBe("DELETE");
|
|
155
|
+
});
|
|
156
|
+
it("returns false when doc does not exist", async () => {
|
|
157
|
+
const fetchMock = vi.fn().mockResolvedValueOnce(jsonResponse(200, { docs: [] }));
|
|
158
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
159
|
+
expect(await client.deleteByVoyantId("products", "p")).toBe(false);
|
|
160
|
+
expect(fetchMock).toHaveBeenCalledOnce();
|
|
161
|
+
});
|
|
162
|
+
it("treats 404 on delete as success", async () => {
|
|
163
|
+
const fetchMock = vi
|
|
164
|
+
.fn()
|
|
165
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [{ id: "pl_1" }] }))
|
|
166
|
+
.mockResolvedValueOnce(textResponse(404, "gone"));
|
|
167
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
168
|
+
expect(await client.deleteByVoyantId("products", "p")).toBe(true);
|
|
169
|
+
});
|
|
170
|
+
it("throws on non-2xx, non-404 delete response", async () => {
|
|
171
|
+
const fetchMock = vi
|
|
172
|
+
.fn()
|
|
173
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [{ id: "pl_1" }] }))
|
|
174
|
+
.mockResolvedValueOnce(textResponse(500, "boom"));
|
|
175
|
+
const client = createPayloadClient({ ...baseOptions, fetch: fetchMock });
|
|
176
|
+
await expect(client.deleteByVoyantId("products", "p")).rejects.toThrow(/Payload delete\(products\/pl_1\) failed \(500\)/);
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
describe("createPayloadClient — fetch handling", () => {
|
|
180
|
+
it("throws when no fetch implementation is available", async () => {
|
|
181
|
+
const originalFetch = globalThis.fetch;
|
|
182
|
+
globalThis.fetch = undefined;
|
|
183
|
+
try {
|
|
184
|
+
// biome-ignore lint/suspicious/noExplicitAny: simulating missing fetch
|
|
185
|
+
const client = createPayloadClient({ ...baseOptions, fetch: undefined });
|
|
186
|
+
await expect(client.findByVoyantId("products", "x")).rejects.toThrow(/requires a fetch implementation/);
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
globalThis.fetch = originalFetch;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.test.d.ts","sourceRoot":"","sources":["../../../tests/unit/plugin.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { createEventBus, registerPlugins } from "@voyantjs/core";
|
|
2
|
+
import { describe, expect, it, vi } from "vitest";
|
|
3
|
+
import { payloadCmsPlugin } from "../../src/plugin.js";
|
|
4
|
+
function jsonResponse(status, body) {
|
|
5
|
+
const text = JSON.stringify(body);
|
|
6
|
+
return {
|
|
7
|
+
ok: status >= 200 && status < 300,
|
|
8
|
+
status,
|
|
9
|
+
json: async () => JSON.parse(text),
|
|
10
|
+
text: async () => text,
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
const baseOptions = {
|
|
14
|
+
apiUrl: "https://cms.example.com/api",
|
|
15
|
+
apiKey: "test-key",
|
|
16
|
+
collection: "products",
|
|
17
|
+
};
|
|
18
|
+
describe("payloadCmsPlugin", () => {
|
|
19
|
+
it("exposes a stable identity", () => {
|
|
20
|
+
const plugin = payloadCmsPlugin({ ...baseOptions });
|
|
21
|
+
expect(plugin.name).toBe("payload-cms");
|
|
22
|
+
expect(plugin.version).toBeDefined();
|
|
23
|
+
expect(plugin.subscribers).toHaveLength(3);
|
|
24
|
+
});
|
|
25
|
+
it("subscribes to default product.* events", () => {
|
|
26
|
+
const plugin = payloadCmsPlugin({ ...baseOptions });
|
|
27
|
+
const names = plugin.subscribers?.map((s) => s.event);
|
|
28
|
+
expect(names).toEqual(["product.created", "product.updated", "product.deleted"]);
|
|
29
|
+
});
|
|
30
|
+
it("honors custom event names", () => {
|
|
31
|
+
const plugin = payloadCmsPlugin({
|
|
32
|
+
...baseOptions,
|
|
33
|
+
events: {
|
|
34
|
+
created: "departure.created",
|
|
35
|
+
updated: "departure.updated",
|
|
36
|
+
deleted: "departure.deleted",
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
const names = plugin.subscribers?.map((s) => s.event);
|
|
40
|
+
expect(names).toEqual(["departure.created", "departure.updated", "departure.deleted"]);
|
|
41
|
+
});
|
|
42
|
+
it("pushes product.created to Payload as an upsert", async () => {
|
|
43
|
+
const fetchMock = vi
|
|
44
|
+
.fn()
|
|
45
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [] }))
|
|
46
|
+
.mockResolvedValueOnce(jsonResponse(201, { doc: { id: "pl_1" } }));
|
|
47
|
+
const bus = createEventBus();
|
|
48
|
+
const plugin = payloadCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
49
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
50
|
+
await bus.emit("product.created", { id: "prod_1", name: "Tour A" });
|
|
51
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
52
|
+
const [, createInit] = fetchMock.mock.calls[1];
|
|
53
|
+
expect(createInit.method).toBe("POST");
|
|
54
|
+
const body = JSON.parse(createInit.body ?? "{}");
|
|
55
|
+
expect(body).toEqual({ name: "Tour A", voyantId: "prod_1" });
|
|
56
|
+
});
|
|
57
|
+
it("pushes product.updated to Payload as an upsert", async () => {
|
|
58
|
+
const fetchMock = vi
|
|
59
|
+
.fn()
|
|
60
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [{ id: "pl_99" }] }))
|
|
61
|
+
.mockResolvedValueOnce(jsonResponse(200, { doc: { id: "pl_99" } }));
|
|
62
|
+
const bus = createEventBus();
|
|
63
|
+
const plugin = payloadCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
64
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
65
|
+
await bus.emit("product.updated", { id: "prod_1", name: "Tour B" });
|
|
66
|
+
const [url, init] = fetchMock.mock.calls[1];
|
|
67
|
+
expect(url).toBe("https://cms.example.com/api/products/pl_99");
|
|
68
|
+
expect(init.method).toBe("PATCH");
|
|
69
|
+
});
|
|
70
|
+
it("deletes from Payload on product.deleted", async () => {
|
|
71
|
+
const fetchMock = vi
|
|
72
|
+
.fn()
|
|
73
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [{ id: "pl_50" }] }))
|
|
74
|
+
.mockResolvedValueOnce(jsonResponse(200, {}));
|
|
75
|
+
const bus = createEventBus();
|
|
76
|
+
const plugin = payloadCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
77
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
78
|
+
await bus.emit("product.deleted", { id: "prod_1" });
|
|
79
|
+
const [url, init] = fetchMock.mock.calls[1];
|
|
80
|
+
expect(url).toBe("https://cms.example.com/api/products/pl_50");
|
|
81
|
+
expect(init.method).toBe("DELETE");
|
|
82
|
+
});
|
|
83
|
+
it("applies a custom mapEvent function", async () => {
|
|
84
|
+
const fetchMock = vi
|
|
85
|
+
.fn()
|
|
86
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [] }))
|
|
87
|
+
.mockResolvedValueOnce(jsonResponse(201, { doc: { id: "pl_1" } }));
|
|
88
|
+
const bus = createEventBus();
|
|
89
|
+
const plugin = payloadCmsPlugin({
|
|
90
|
+
...baseOptions,
|
|
91
|
+
fetch: fetchMock,
|
|
92
|
+
mapEvent: (event) => ({
|
|
93
|
+
title: String(event.name ?? ""),
|
|
94
|
+
_syncedAt: "2024-01-01",
|
|
95
|
+
}),
|
|
96
|
+
});
|
|
97
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
98
|
+
await bus.emit("product.created", { id: "prod_x", name: "Cool Tour" });
|
|
99
|
+
const [, init] = fetchMock.mock.calls[1];
|
|
100
|
+
const body = JSON.parse(init.body ?? "{}");
|
|
101
|
+
expect(body).toEqual({
|
|
102
|
+
title: "Cool Tour",
|
|
103
|
+
_syncedAt: "2024-01-01",
|
|
104
|
+
voyantId: "prod_x",
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
it("ignores events with no string id", async () => {
|
|
108
|
+
const fetchMock = vi.fn();
|
|
109
|
+
const bus = createEventBus();
|
|
110
|
+
const plugin = payloadCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
111
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
112
|
+
await bus.emit("product.created", { name: "no id here" });
|
|
113
|
+
await bus.emit("product.created", null);
|
|
114
|
+
await bus.emit("product.created", { id: 42 });
|
|
115
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
116
|
+
});
|
|
117
|
+
it("logs and swallows Payload errors (fire-and-forget)", async () => {
|
|
118
|
+
const fetchMock = vi.fn().mockResolvedValue({
|
|
119
|
+
ok: false,
|
|
120
|
+
status: 500,
|
|
121
|
+
json: async () => ({}),
|
|
122
|
+
text: async () => "server down",
|
|
123
|
+
});
|
|
124
|
+
const errorFn = vi.fn();
|
|
125
|
+
const bus = createEventBus();
|
|
126
|
+
const plugin = payloadCmsPlugin({
|
|
127
|
+
...baseOptions,
|
|
128
|
+
fetch: fetchMock,
|
|
129
|
+
logger: { error: errorFn },
|
|
130
|
+
});
|
|
131
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
132
|
+
await bus.emit("product.created", { id: "prod_1", name: "X" });
|
|
133
|
+
expect(errorFn).toHaveBeenCalledOnce();
|
|
134
|
+
const [msg] = errorFn.mock.calls[0];
|
|
135
|
+
expect(msg).toContain('[payload-cms] upsert on "product.created" failed for prod_1');
|
|
136
|
+
});
|
|
137
|
+
it("uses a custom collection name for the Payload path", async () => {
|
|
138
|
+
const fetchMock = vi
|
|
139
|
+
.fn()
|
|
140
|
+
.mockResolvedValueOnce(jsonResponse(200, { docs: [] }))
|
|
141
|
+
.mockResolvedValueOnce(jsonResponse(201, { doc: { id: "pl_1" } }));
|
|
142
|
+
const bus = createEventBus();
|
|
143
|
+
const plugin = payloadCmsPlugin({
|
|
144
|
+
...baseOptions,
|
|
145
|
+
collection: "tours",
|
|
146
|
+
fetch: fetchMock,
|
|
147
|
+
});
|
|
148
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
149
|
+
await bus.emit("product.created", { id: "prod_1", name: "X" });
|
|
150
|
+
const [findUrl] = fetchMock.mock.calls[0];
|
|
151
|
+
expect(findUrl).toContain("https://cms.example.com/api/tours?");
|
|
152
|
+
const [createUrl] = fetchMock.mock.calls[1];
|
|
153
|
+
expect(createUrl).toBe("https://cms.example.com/api/tours");
|
|
154
|
+
});
|
|
155
|
+
it("does not delete if the doc is missing on product.deleted", async () => {
|
|
156
|
+
const fetchMock = vi.fn().mockResolvedValueOnce(jsonResponse(200, { docs: [] }));
|
|
157
|
+
const bus = createEventBus();
|
|
158
|
+
const plugin = payloadCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
159
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
160
|
+
await bus.emit("product.deleted", { id: "prod_missing" });
|
|
161
|
+
// Only the find call should have been made.
|
|
162
|
+
expect(fetchMock).toHaveBeenCalledOnce();
|
|
163
|
+
});
|
|
164
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@voyantjs/plugin-payload-cms",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "FSL-1.1-Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"import": "./dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./client": {
|
|
12
|
+
"types": "./dist/client.d.ts",
|
|
13
|
+
"import": "./dist/client.js"
|
|
14
|
+
},
|
|
15
|
+
"./plugin": {
|
|
16
|
+
"types": "./dist/plugin.d.ts",
|
|
17
|
+
"import": "./dist/plugin.js"
|
|
18
|
+
},
|
|
19
|
+
"./types": {
|
|
20
|
+
"types": "./dist/types.d.ts",
|
|
21
|
+
"import": "./dist/types.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@voyantjs/core": "0.1.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"typescript": "^6.0.2",
|
|
29
|
+
"vitest": "^4.1.2",
|
|
30
|
+
"@voyantjs/voyant-typescript-config": "0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"lint": "biome check src/",
|
|
41
|
+
"test": "vitest run",
|
|
42
|
+
"build": "tsc -p tsconfig.json",
|
|
43
|
+
"clean": "rm -rf dist"
|
|
44
|
+
},
|
|
45
|
+
"main": "./dist/index.js",
|
|
46
|
+
"types": "./dist/index.d.ts"
|
|
47
|
+
}
|