james-elicx / cf-bindings-proxy

Experimental proxy for interfacing with bindings in projects targeting Cloudflare Pages
MIT License
94 stars 4 forks source link

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

Open yalamber opened 9 months ago

yalamber commented 9 months ago

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
        });
    }
}