Skip to content
File

Blob: src/workerd/api/tests/actor-kv-test.js

javascript73 lines
1// Copyright (c) 2023 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5import * as assert from 'node:assert';
6import { DurableObject } from 'cloudflare:workers';
7 
8async function testKvOperations(state) {
9 const storage = state.storage;
10 
11 // Test basic put/get operations
12 await storage.put('testKey1', 'testValue');
13 await storage.put({
14 foo1: 'bar1',
15 foo2: 'bar2',
16 foo3: 'bar3',
17 foo4: 'bar4',
18 });
19 await storage.get('testKey2');
20 await storage.get(['testKey1', 'testKey2']);
21 await storage.delete('testKey1');
22 await storage.list();
23 await storage.deleteAll();
24 await storage.setAlarm(Date.now() + 50);
25 await storage.getAlarm();
26 await storage.deleteAlarm();
27 await storage.transaction(() => {
28 return 'test';
29 });
30 await storage.sync();
31}
32 
33export class ActorKvTest extends DurableObject {
34 constructor(state, env) {
35 super(state, env);
36 this.state = state;
37 }
38 
39 async fetch(req) {
40 const url = new URL(req.url);
41 
42 if (url.pathname.endsWith('/kv-test')) {
43 await testKvOperations(this.state);
44 return Response.json({ ok: true, test: 'kv-operations' });
45 }
46 
47 return Response.json(
48 { error: 'Unknown endpoint', path: url.pathname },
49 { status: 404 }
50 );
51 }
52 
53 alarm() {}
54}
55 
56export default {
57 async test(ctrl, env, ctx) {
58 let id = env.ns.idFromName('actor-kv-test');
59 let obj = env.ns.get(id);
60 
61 let doReq = async (path, init = {}) => {
62 let resp = await obj.fetch('http://test.example/' + path, init);
63 return await resp.json();
64 };
65 
66 // Test KV operations
67 assert.deepEqual(await doReq('kv-test'), {
68 ok: true,
69 test: 'kv-operations',
70 });
71 },
72};