Created
November 7, 2022 21:19
-
-
Save remotesynth/97c69486ab8defd0baa17c238c99cae2 to your computer and use it in GitHub Desktop.
Deno Deploy function calling the LaunchDarkly API for flag values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { serve } from "https://deno.land/std@0.114.0/http/server.ts"; | |
import { DOMParser } from "https://esm.sh/linkedom"; | |
async function handler(req: Request): Promise<Response> { | |
const document = new DOMParser().parseFromString(`<html> | |
<head><title>Just a simple page</title></head> | |
<body> | |
<h1>This header will change</h1> | |
<p>The above header will change depending on the flag value.</p> | |
</body> | |
</html>`); | |
const headerText: string = await getFlagValue("default","production","header-text"); | |
const h1 = document.querySelector("h1"); | |
h1.innerHTML = headerText; | |
return new Response(document.toString(), { | |
headers: { "content-type": "text/html; charset=utf-8" }, | |
}); | |
} | |
// this is a very basic API function that only handles on/off | |
async function getFlagValue(project:string, environment:string, key:string) { | |
const flagDataResponse: ReadableStream = await fetch(new Request(`https://app.launchdarkly.com/api/v2/flags/${project}/${key}?env=${environment}`, { | |
headers: { Authorization: Deno.env.get("LAUNCHDARKLY_API") } | |
})); | |
const flagData: object = await flagDataResponse.json(); | |
if (flagData.environments.production.on) | |
return flagData.variations[flagData.defaults.onVariation].value; | |
else | |
return flagData.variations[flagData.defaults.offVariation].value; | |
} | |
serve(handler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment