All Products
Search
Document Center

Edge Security Acceleration:Edge KV API

Last Updated:Sep 19, 2024

This topic describes the built-in API operations of Edge KV.

Constructor

Creates an instance that is associated with the specified namespace in Edge KV.

  • Definition

    const edgeKv = new EdgeKV({ namespace: "ns"});
  • Parameters

    Parameter

    Description

    namespace

    Enter the name of the namespace that you created by using the Edge Security Acceleration (ESA) console. You can query your namespaces in the namespace list.

get

Reads data from a namespace.

  • Definition

    get(key[, {type: "type"}])
  • Parameters

    Parameter

    Description

    key

    The key is a string.

    type

    You can specify one of the following types:

    • stream (default): returns a readable stream.

    • text: returns a string.

    • json: converts the stored JSON content into an object and then returns the object.

    • arrayBuffer: returns binary data.

  • Return value

    A Promise object is returned. You can call await to ensure that the execution of the get method is complete.

    • If the key does not exist, the Promise object is resolved to undefined.

    • If the get method fails to be executed due to an exception, the Promise object is rejected with an error.

  • Sample code

    addEventListener("fetch", event => {
      event.respondWith(handleRequest(event.request))
    })
    
    async function handleRequest(request) {
      try {
        const edgeKV = new EdgeKV({ namespace: "ns" });
        let getType = { type: "text" };
        let value = await edgeKV.get("key", getType);
        if (value === undefined) {
          return "EdgeKV get: key not found";
        } else {
          return new Response(value);
        }
      } catch (e) {
        return "EdgeKV get error" + e;
      }
    }

delete

Deletes a key and its value from a namespace.

  • Definition

    delete(key)
  • Parameters

    Parameter

    Description

    key

    The key that you want to delete. It is a string.

  • Return value

    A Promise object is returned. You can call await to ensure that the execution of the delete method is complete.

    • If the delete method is successful, the Promise object is resolved to true.

    • If the delete method fails to be executed, the Promise object is resolved to false.

    • If an exception occurs when you execute the delete method, the Promise object is rejected with an error.

  • Sample code

    addEventListener("fetch", event => {
      event.respondWith(handleRequest(event.request))
    })
    
    async function handleRequest() {
      try {
        const edgeKV = new EdgeKV({ namespace: "ns" });
        let resp = await edgeKV.delete("key");
        if (resp) {
          return "EdgeKV delete success";
        } else {
          return "EdgeKV delete failed";
        }
      }
      catch (e) {
        return "EdgeKV delete error" + e;
      }
    }