This topic describes the built-in API operations of EdgeRoutine (ER).
Constructor
Passes the namespace parameter to create an edge key-value object.
- Syntax
const edgeKv = new EdgeKV({ namespace: "ns"});
- Parameter description
Parameter Description namespace The value of the namespace parameter is the name of the namespace that you created in the Dynamic Route for CDN (DCDN) console. You can view the namespace in the namespace list.
get
Reads data from a namespace.
- Syntax
get(key[, {type: “type”}])
- Parameter description
Parameter Description key The type is string. type You can select one of the following types: - stream: returns a readable stream. This is the default type.
- text: returns a string.
- json: converts the stored JSON content into an object and then returns the object.
- arrayBuffer: returns binary data.
- Return valueA 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.
- Syntax
delete(key)
- Parameter description
Parameter Description key The key that you want to delete. The type is string. - Return valueA 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; } }
JavaScript exception handling
If an exception occurs, a JavaScript error is returned. If you want to ignore this error, you must capture the error in the JavaScript code. If you do not capture the error, the 599 status code is returned, and the request is redirected to the origin server. The origin server that processes the request is the origin server that you configure when you add the domain name to Alibaba Cloud CDN or DCDN.