Skip to content

Latest commit

 

History

History
83 lines (59 loc) · 2.31 KB

File metadata and controls

83 lines (59 loc) · 2.31 KB
title Runtime
description The runtime APIs available on the bunny.net platform.

Runtime

The bunny.net EdgeScript Runtime is based on Deno, so you can use a subset of what is available from Deno or Node. Given the environment where we run EdgeScripts, we also provide functions you can use to alter the behavior of the script or bind to other bunny.net Services.

waitUntil

The waitUntil function allows you to extend the duration of the isolate running a request. It can be useful when you want a script to continue doing work after the request it answered has finished. Even if no other requests are being routed to this script, it will extend the duration of this script invocation.

It can be quite useful if you want to maintain WebSocket connections, refresh a cache entry in the background, or fire off telemetry after the response has been returned to the client.

Signature

Bunny.v1.waitUntil(promise: Promise<unknown>): void;

Parameters

A promise representing background work. The isolate will stay alive until this promise settles (resolves or rejects).

Returns

voidwaitUntil does not return a value.

You can call `waitUntil` multiple times; the script will only be evicted once every given promise has been resolved.

Example

Return the response to the client immediately while a slower task — here, populating the cache — finishes in the background.

import * as BunnySDK from "@bunny.net/edgescript-sdk";

BunnySDK.net.http.serve(async (request: Request): Promise<Response> => {
  const url = new URL(request.url);
  const cache = caches.default;
  const cacheKey = new Request(url.toString(), { method: "GET" });

  const hit = await cache.match(cacheKey);
  if (hit) {
    return hit;
  }

  const fresh = Response.json(
    { generatedAt: new Date().toISOString(), random: Math.random() },
    { headers: { "Cache-Control": "s-maxage=60" } },
  );

  // Don't block the response on the cache write — let it finish after we
  // return. The isolate stays alive until cache.put() resolves.
  Bunny.v1.waitUntil(cache.put(cacheKey, fresh.clone()));

  return fresh;
});

References