Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reference error process is not defined when using in coudflare pages #49

Open
yalamber opened this issue Feb 12, 2024 · 0 comments
Open

Comments

@yalamber
Copy link

yalamber commented Feb 12, 2024

I am using this on cloudflare pages, When I try to use KV I receive below error.
"ReferenceError: process is not defined"
My CFKV class is as below

import { binding } from 'cf-bindings-proxy';
import type { KVNamespace, KVNamespaceListResult } from '@cloudflare/workers-types';

type KVGetOptions = 'text' | 'json' | 'arrayBuffer' | 'stream';

export default class CFKV {
	namespaceBinding: KVNamespace;
	constructor(namespace: string) {
		this.namespaceBinding = binding<KVNamespace>(namespace);
	}

	get<T = 'text'>(KEY: string, type: KVGetOptions = 'text'): Promise<T | null> {
		switch (type) {
			case 'json':
				return this.namespaceBinding.get<T>(KEY, 'json');
			case 'text':
				return this.namespaceBinding.get(KEY, 'text') as Promise<T | null>;
			case 'arrayBuffer':
				return this.namespaceBinding.get(KEY, 'arrayBuffer') as Promise<T | null>;
			case 'stream':
				return this.namespaceBinding.get(KEY, 'stream') as Promise<T | null>;
			default:
				return this.namespaceBinding.get(KEY, 'text') as Promise<T | null>;
		}
	}

	set(KEY: string, value: string, { ttl }: { ttl: number }) {
		return this.namespaceBinding.put(KEY, value, {
			expirationTtl: ttl
		});
	}
	remove(KEY: string) {
		return this.namespaceBinding.delete(KEY);
	}

	async removeAllWithPrefix(prefix: string) {
		let cursor: string | undefined = undefined;
		do {
			try {
				const result = await this.list(prefix, 1000, cursor);
				if (!result.list_complete && result.cursor) {
					cursor = result.cursor;
				} else {
					cursor = undefined;
				}
				// Remove each key
				for (const key of result.keys) {
					await this.remove(key.name);
				}
			} catch (error) {
				console.error('Error removing keys with prefix:', error);
				throw error;
			}
		} while (cursor !== undefined);
	}

	list(
		prefix: string,
		limit: number = 1000,
		cursor: string | undefined = undefined
	): Promise<KVNamespaceListResult<unknown, string>> {
		return this.namespaceBinding.list({
			prefix,
			limit,
			cursor
		});
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant