Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"build:essentials:force": "pnpm clean:build && turbo build --filter=\"payload...\" --filter=\"@payloadcms/ui\" --filter=\"@payloadcms/next\" --filter=\"@payloadcms/db-mongodb\" --filter=\"@payloadcms/db-postgres\" --filter=\"@payloadcms/richtext-lexical\" --filter=\"@payloadcms/translations\" --filter=\"@payloadcms/plugin-cloud\" --filter=\"@payloadcms/graphql\" --no-cache --force",
"build:force": "pnpm run build:core:force",
"build:graphql": "turbo build --filter \"@payloadcms/graphql\"",
"build:kv-cloudflare": "turbo build --filter \"@payloadcms/kv-cloudflare\"",
"build:kv-redis": "turbo build --filter \"@payloadcms/kv-redis\"",
"build:live-preview": "turbo build --filter \"@payloadcms/live-preview\"",
"build:live-preview-react": "turbo build --filter \"@payloadcms/live-preview-react\"",
Expand Down
10 changes: 10 additions & 0 deletions packages/kv-cloudflare/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.tmp
**/.git
**/.hg
**/.pnp.*
**/.svn
**/.yarn/**
**/build
**/dist/**
**/node_modules
**/temp
15 changes: 15 additions & 0 deletions packages/kv-cloudflare/.swcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"sourceMaps": true,
"jsc": {
"target": "esnext",
"parser": {
"syntax": "typescript",
"tsx": true,
"dts": true
}
},
"module": {
"type": "es6"
}
}
22 changes: 22 additions & 0 deletions packages/kv-cloudflare/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2018-2024 Payload CMS, Inc. <info@payloadcms.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 changes: 35 additions & 0 deletions packages/kv-cloudflare/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Cloudflare KV Adapter for Payload (beta)

This package lets you back Payload's KV API with [Cloudflare KV](https://developers.cloudflare.com/kv/).

## Installation

```sh
pnpm add @payloadcms/kv-cloudflare
```

## Usage

Provide a Cloudflare KV binding (Workers/Pages/Miniflare):

```ts
import { cloudflareKVAdapter } from '@payloadcms/kv-cloudflare'

export default buildConfig({
collections: [Media],
kv: cloudflareKVAdapter({
// Cloudflare KV namespace binding (required)
binding: env.PAYLOAD_KV,
// Optional prefix to isolate keys, defaults to 'payload-kv:'
keyPrefix: 'payload-kv:',
}),
})
```

Then access it through `payload.kv`:

```ts
await payload.kv.set('key', { value: 1 })
const data = await payload.kv.get('key')
payload.logger.info(data)
```
64 changes: 64 additions & 0 deletions packages/kv-cloudflare/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"name": "@payloadcms/kv-cloudflare",
"version": "3.64.0",
"description": "Cloudflare KV adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",
"url": "https://github.com/payloadcms/payload.git",
"directory": "packages/kv-cloudflare"
},
"license": "MIT",
"author": "Payload <dev@payloadcms.com> (https://payloadcms.com)",
"maintainers": [
{
"name": "Payload",
"email": "info@payloadcms.com",
"url": "https://payloadcms.com"
}
],
"type": "module",
"exports": {
".": {
"import": "./src/index.ts",
"types": "./src/index.ts",
"default": "./src/index.ts"
}
},
"main": "./src/index.ts",
"types": "./src/index.ts",
"files": [
"dist"
],
"scripts": {
"build": "pnpm build:types && pnpm build:swc",
"build:clean": "find . \\( -type d \\( -name build -o -name dist -o -name .cache \\) -o -type f -name tsconfig.tsbuildinfo \\) -exec rm -rf {} + && pnpm build",
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths",
"build:types": "tsc --emitDeclarationOnly --outDir dist",
"clean": "rimraf {dist,*.tsbuildinfo}",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"prepublishOnly": "pnpm clean && pnpm turbo build"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20251004.0",
"payload": "workspace:*"
},
"peerDependencies": {
"payload": "workspace:*"
},
"engines": {
"node": "^18.20.2 || >=20.9.0"
},
"publishConfig": {
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts"
}
}
117 changes: 117 additions & 0 deletions packages/kv-cloudflare/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import type { KVNamespace } from '@cloudflare/workers-types'
import type { KVAdapter, KVAdapterResult, KVStoreValue } from 'payload'

export type CloudflareKVNamespace = KVNamespace

const defaultPrefix = 'payload-kv:'

export class CloudflareKVAdapter implements KVAdapter {
constructor(
readonly binding: CloudflareKVNamespace,
readonly keyPrefix: string,
) {}

private prefixKey(key: string): string {
return `${this.keyPrefix}${key}`
}

async clear(): Promise<void> {
let cursor: string | undefined

while (true) {
const result = await this.binding.list({
cursor,
prefix: this.keyPrefix || undefined,
})

const { keys, list_complete } = result
const nextCursor = 'cursor' in result ? result.cursor : undefined

if (keys.length) {
await Promise.all(keys.map(({ name }) => this.binding.delete(name)))
}

if (list_complete || !nextCursor) {
break
}
cursor = nextCursor
}
}

async delete(key: string): Promise<void> {
await this.binding.delete(this.prefixKey(key))
}

async get<T extends KVStoreValue>(key: string): Promise<null | T> {
const value = await this.binding.get(this.prefixKey(key))

if (value === null) {
return null
}

return JSON.parse(value) as T
}

async has(key: string): Promise<boolean> {
const value = await this.binding.get(this.prefixKey(key))
return value !== null
}

async keys(): Promise<string[]> {
const keys: string[] = []
let cursor: string | undefined

while (true) {
const result = await this.binding.list({
cursor,
prefix: this.keyPrefix || undefined,
})

const { keys: batch, list_complete } = result
const nextCursor = 'cursor' in result ? result.cursor : undefined

if (batch.length) {
keys.push(
...batch.map(({ name }) => (this.keyPrefix ? name.replace(this.keyPrefix, '') : name)),
)
}

if (list_complete || !nextCursor) {
break
}
cursor = nextCursor
}

return keys
}

async set(key: string, data: KVStoreValue): Promise<void> {
await this.binding.put(this.prefixKey(key), JSON.stringify(data))
}
}

export type CloudflareKVAdapterOptions = {
/**
* Cloudflare KV namespace binding (required)
*/
binding: CloudflareKVNamespace
/**
* Optional prefix for keys in the namespace
*
* @default 'payload-kv:'
*/
keyPrefix?: string
}

export const cloudflareKVAdapter = (options: CloudflareKVAdapterOptions): KVAdapterResult => {
const keyPrefix = options.keyPrefix ?? defaultPrefix
const { binding } = options

if (!binding) {
throw new Error('Cloudflare KV binding is required')
}

return {
init: () => new CloudflareKVAdapter(binding, keyPrefix),
}
}
14 changes: 14 additions & 0 deletions packages/kv-cloudflare/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"noEmit": false,
"emitDeclarationOnly": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true
},
"exclude": ["dist", "node_modules"],
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.d.ts", "src/**/*.json"],
"references": [{ "path": "../payload" }]
}
Loading