This topic describes the built-in EdgeKV API for EdgeRoutine (ER).
Constructor
Creates an EdgeKV instance for a specified namespace.
Syntax
const edgeKv = new EdgeKV({ namespace: "ns"});Parameters
Parameter
Description
namespace
The namespace you created in the console. You can view your namespaces in the namespace list.
get
Reads data from a namespace.
Syntax
get(key[, {type: “type”}])Parameters
Parameter
Description
key
The key to retrieve, specified as a string.
type
The return type. You can specify one of the following values:
stream(default): Returns the value as aReadableStream.text: Returns the value as a string.json: Parses the value as JSON and returns the resulting object.arrayBuffer: Returns the value as anArrayBuffer.
Return value
Returns a
Promise. You can useawaitto ensure the operation is complete.If the key is not found, the promise resolves with
undefined.If an exception occurs and the operation fails, the promise is rejected with an
Errorobject.
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-value pair from a namespace.
Syntax
delete(key)Parameters
Parameter
Description
key
The key to delete, specified as a string.
Return value
Returns a
Promise. You can useawaitto ensure the operation is complete.If the deletion is successful, the promise resolves with
true.If the deletion fails, the promise resolves with
false.If an exception occurs, the promise is rejected with an
Errorobject.
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; } }
JavaScript exception handling
When an exception occurs, a JS error is returned. If you want to ignore this error, you must catch it in your JS code. Otherwise, a 599 status code is returned and the request automatically falls back to the fallback origin server for a retry. The fallback origin server is the origin server that you configured when you added the domain name to CDN/DCDN.